问题
I am currently in my first year of Java and have stumbled upon this code on the internet about a battleship game. What I would like to do is understand this code in more simple code. The part that confuses me is the first line: "computerGameBoard = new GameBoard(true, event ->". I am familiar with buttons and how they have action events, but how does this code compare to that and is it possible to turn this into a similar action event to a button? Could I split it into another method? Thanks in advance. Also note that the line of code below should be attached to the code segment, but its not.
computerGameBoard = new GameBoard(true, event ->
{
if (!playing)
return;
BoardSquare boardsquare = (BoardSquare) event.getSource();
if (boardsquare.wasHit)
return;
AIMove = !boardsquare.fire();
System.out.println("enemyBoard shipcount:"+computerGameBoard.shipcount);
if (computerGameBoard.shipcount == 0) {
System.out.println("Winner!");
}
if (AIMove)
AI1();
});
回答1:
An example of onClickListener() without lambda:
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something here
}
});
can be rewritten with lambda:
mButton.setOnClickListener((View v) -> {
// do something here
});
So your code is using Lambda expression (Java 8 feature)
来源:https://stackoverflow.com/questions/61875846/how-do-i-transform-this-code-into-something-simpler-that-i-am-more-familiar-with