java实现界面化回合制对战游戏代码示例
时间: 2023-08-17 14:04:35 浏览: 135
以下是一个简单的Java代码示例,展示了如何使用JavaFX库实现一个简单的界面化回合制对战游戏:
```java
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class TurnBasedGame extends Application {
private int playerHP = 100;
private int enemyHP = 100;
private boolean playerTurn = true;
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Turn-Based Game");
GridPane gridPane = new GridPane();
gridPane.setAlignment(Pos.CENTER);
gridPane.setVgap(10);
Text playerText = new Text("Player HP: " + playerHP);
Text enemyText = new Text("Enemy HP: " + enemyHP);
Button attackButton = new Button("Attack");
attackButton.setOnAction(e -> {
if (playerTurn) {
int damage = calculateDamage();
enemyHP -= damage;
enemyText.setText("Enemy HP: " + enemyHP);
}
if (enemyHP <= 0) {
enemyText.setText("Enemy HP: 0");
gameOver("Player wins!");
} else {
playerTurn = !playerTurn;
}
});
HBox buttonBox = new HBox(10, attackButton);
buttonBox.setAlignment(Pos.CENTER);
gridPane.add(playerText, 0, 0);
gridPane.add(enemyText, 0, 1);
gridPane.add(buttonBox, 0, 2);
Scene scene = new Scene(gridPane, 400, 300);
primaryStage.setScene(scene);
primaryStage.show();
}
private int calculateDamage() {
// TODO: Add logic for calculating damage
return 10;
}
private void gameOver(String message) {
// TODO: Handle game over logic, display message to the player
}
public static void main(String[] args) {
launch(args);
}
}
```
这个示例展示了一个简单的界面化回合制对战游戏,玩家可以点击"Attack"按钮攻击敌人,敌人的生命值会相应减少,直到敌人生命值为0时游戏结束。你可以根据需要添加更多的功能和交互元素来丰富游戏体验。请注意,这只是一个简单的示例,实际的游戏实现可能需要更多的代码和逻辑。
阅读全文