本文主要是介绍java-文字版格斗游戏,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
下面是一个简单的文字版格斗游戏的Java代码示例。这个游戏中有两个角色:玩家1和玩家2。玩家可以通过输入不同的按键来控制角色进行攻击、防御和闪避。游戏会根据玩家的输入和角色的属性来计算战斗结果。
```java
import java.util.Scanner;
public class TextFightGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("欢迎来到文字版格斗游戏!请输入玩家1的名称:");
String player1Name = scanner.nextLine();
System.out.println("请输入玩家2的名称:");
String player2Name = scanner.nextLine();
// 初始化角色属性
Player player1 = new Player(player1Name, 100, 50, 20);
Player player2 = new Player(player2Name, 100, 50, 20);
// 游戏主循环
while (player1.getHp() > 0 && player2.getHp() > 0) {
System.out.println("---------------------------------");
System.out.println("玩家1:" + player1.getName() + ",血量:" + player1.getHp());
System.out.println("玩家2:" + player2.getName() + ",血量:" + player2.getHp());
System.out.println("1. 攻击 2. 防御 3. 闪避 4. 投降");
System.out.print("玩家1请选择行动:");
int player1Action = scanner.nextInt();
scanner.nextLine(); // 清除输入缓冲区
System.out.println("玩家2请选择行动:");
int player2Action = scanner.nextInt();
scanner.nextLine(); // 清除输入缓冲区
// 执行玩家行动
player1.performAction(player2, player1Action);
player2.performAction(player1, player2Action);
// 检查游戏结束条件
if (player1.getHp() <= 0) {
System.out.println("玩家1:" + player1.getName() + " 已败北!");
break;
}
if (player2.getHp() <= 0) {
System.out.println("玩家2:" + player2.getName() + " 已败北!");
break;
}
}
System.out.println("游戏结束,感谢参与!");
scanner.close();
}
}
class Player {
private String name;
private int hp;
private int attack;
private int defense;
public Player(String name, int hp, int attack, int defense) {
this.name = name;
this.hp = hp;
this.attack = attack;
this.defense = defense;
}
public String getName() {
return name;
}
public int getHp() {
return hp;
}
public void performAction(Player opponent, int action) {
int damage = 0;
switch (action) {
case 1:
damage = attack - opponent.defense;
if (damage > 0) {
System.out.println(this.name + " 对 " + opponent.name + " 造成了 " + damage + " 点伤害!");
opponent.hp -= damage;
} else {
System.out.println(this.name + " 的攻击被 " + opponent.name + " 抵挡住了!");
}
break;
case 2:
System.out.println(this.name + " 处于防御状态!");
break;
case 3:
System.out.println(this.name + " 成功闪避了 " + opponent.name + " 的攻击!");
break;
case 4:
System.out.println(this.name + " 投降了!");
break;
default:
System.out.println("无效的行动,请重新选择!");
}
}
}
```
这个游戏
这篇关于java-文字版格斗游戏的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!