用javafx实现农夫过河这个游戏(通过按钮的点击来使得物品过河)
时间: 2024-03-06 12:51:32 浏览: 47
JavaFx的中国象棋小游戏.zip
好的,我可以为您提供一个简单的实现。
首先,我们需要准备好游戏的界面。在JavaFX中,我们可以使用GridPane来布置按钮。下面是一个简单的界面示例:
```java
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
GridPane gridPane = new GridPane();
gridPane.setAlignment(Pos.CENTER);
gridPane.setHgap(20);
gridPane.setVgap(20);
Button farmer = new Button("农夫");
Button sheep = new Button("羊");
Button wolf = new Button("狼");
Button cabbage = new Button("白菜");
gridPane.add(farmer, 0, 0);
gridPane.add(sheep, 1, 0);
gridPane.add(wolf, 2, 0);
gridPane.add(cabbage, 3, 0);
Scene scene = new Scene(gridPane, 400, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
```
上面的代码创建了一个GridPane,并添加了四个按钮。现在我们需要实现按钮的点击事件。
游戏规则如下:
- 农夫可以单独过河或者携带一件物品过河。
- 狼和羊不能在没有农夫的情况下单独相处。
- 羊和白菜不能在没有农夫的情况下单独相处。
因此,我们需要在点击按钮时检查当前状态是否符合游戏规则。下面是实现游戏逻辑的代码:
```java
public class Main extends Application {
private boolean farmerOnLeft = true;
private boolean sheepOnLeft = true;
private boolean wolfOnLeft = true;
private boolean cabbageOnLeft = true;
@Override
public void start(Stage primaryStage) throws Exception{
GridPane gridPane = new GridPane();
gridPane.setAlignment(Pos.CENTER);
gridPane.setHgap(20);
gridPane.setVgap(20);
Button farmer = new Button("农夫");
farmer.setOnAction(e -> {
if (sheepOnLeft == farmerOnLeft && wolfOnLeft == farmerOnLeft && cabbageOnLeft == farmerOnLeft) {
farmerOnLeft = !farmerOnLeft;
}
});
Button sheep = new Button("羊");
sheep.setOnAction(e -> {
if (sheepOnLeft == farmerOnLeft) {
sheepOnLeft = !sheepOnLeft;
} else {
System.out.println("游戏结束");
}
});
Button wolf = new Button("狼");
wolf.setOnAction(e -> {
if (wolfOnLeft == farmerOnLeft) {
wolfOnLeft = !wolfOnLeft;
} else {
System.out.println("游戏结束");
}
});
Button cabbage = new Button("白菜");
cabbage.setOnAction(e -> {
if (cabbageOnLeft == farmerOnLeft) {
cabbageOnLeft = !cabbageOnLeft;
} else {
System.out.println("游戏结束");
}
});
gridPane.add(farmer, 0, 0);
gridPane.add(sheep, 1, 0);
gridPane.add(wolf, 2, 0);
gridPane.add(cabbage, 3, 0);
Scene scene = new Scene(gridPane, 400, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
```
上面的代码中,我们使用了四个布尔值来表示每个物品当前是否在左岸,然后在按钮点击事件中更新这些值。当某个物品与农夫在不同的岸边时,游戏结束。
这是一个简单的实现,您可以根据自己的需要进行修改和扩展。
阅读全文