写一段角色扮演游戏java运行代码
时间: 2023-12-20 10:03:14 浏览: 85
以下是一个简单的角色扮演游戏Java代码,它包括一个Player类、一个Enemy类和一个Game类。游戏的目标是让玩家与敌人战斗并获得胜利。
```java
import java.util.Random;
public class Player {
private String name;
private int health;
private int attack;
public Player(String name, int health, int attack) {
this.name = name;
this.health = health;
this.attack = attack;
}
public String getName() {
return name;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public int getAttack() {
return attack;
}
public void attack(Enemy enemy) {
int damage = this.attack - enemy.getDefense();
if (damage > 0) {
enemy.setHealth(enemy.getHealth() - damage);
System.out.println(this.name + "攻击了" + enemy.getName() + "造成了" + damage + "点伤害!");
if (enemy.getHealth() <= 0) {
System.out.println(enemy.getName() + "被" + this.name + "击败了!");
}
} else {
System.out.println(this.name + "攻击了" + enemy.getName() + "但是没有造成伤害...");
}
}
}
public class Enemy {
private String name;
private int health;
private int attack;
private int defense;
public Enemy(String name, int health, int attack, int defense) {
this.name = name;
this.health = health;
this.attack = attack;
this.defense = defense;
}
public String getName() {
return name;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public int getAttack() {
return attack;
}
public int getDefense() {
return defense;
}
}
public class Game {
private Player player;
private Enemy enemy;
public Game() {
player = new Player("玩家", 100, 20);
enemy = new Enemy("敌人", 50, 10, 5);
}
public void start() {
System.out.println("欢迎来到角色扮演游戏!");
System.out.println("你的任务是与敌人战斗并获得胜利。");
System.out.println("开始战斗!");
Random random = new Random();
int turn = 1;
while (player.getHealth() > 0 && enemy.getHealth() > 0) {
System.out.println("第" + turn + "回合:");
if (random.nextBoolean()) {
player.attack(enemy);
} else {
enemy.attack(player);
}
turn++;
}
if (player.getHealth() > 0) {
System.out.println("恭喜你获得了胜利!");
} else {
System.out.println("很遗憾,你失败了...");
}
}
public static void main(String[] args) {
Game game = new Game();
game.start();
}
}
```
在这个游戏中,玩家和敌人都有名称、健康值和攻击力。玩家可以攻击敌人并造成伤害,而敌人也可以攻击玩家。游戏将一直进行,直到玩家或敌人的健康值降为零。如果玩家胜利,游戏将打印“恭喜你获得了胜利!”;如果玩家失败,游戏将打印“很遗憾,你失败了...”
阅读全文