以下是一个简化版的植物大战僵尸游戏的Java代码示例:
import java.util.Scanner;
class Game {
private int sunPoints;
private int zombieCount;
public Game() {
sunPoints = 50;
zombieCount = 0;
}
public void play() {
System.out.println("欢迎来到植物大战僵尸游戏!");
System.out.println("你的目标是通过种植植物来抵御僵尸的入侵。");
System.out.println("你有一定的阳光点数可以用来购买植物,每个植物有不同的价格。");
System.out.println("每回合你可以选择种植植物或攻*击僵尸。");
System.out.println("游戏结束条件是僵尸数量达到一定值。");
System.out.println("开始游戏!");
Scanner scanner = new Scanner(System.in);
while (zombieCount < 10) { // 控制僵尸数量,这里设定为10个
System.out.println("请选择操作:");
System.out.println("1. 种植植物");
System.out.println("2. 攻*击僵尸");
System.out.println("3. 跳过回合");
int choice = scanner.nextInt();
switch (choice) {
case 1:
plantPlant();
break;
case 2:
attackZombie();
break;
case 3:
System.out.println("跳过回合,不进行任何操作。");
break;
default:
System.out.println("无效选择,请重新选择。");
break;
}
// 僵尸行动
if (zombieCount < 10) {
System.out.println("僵尸正在接近...");
zombieCount++;
}
System.out.println("当前阳光点数:" + sunPoints);
System.out.println("当前僵尸数量:" + zombieCount);
System.out.println("--------------------------------------");
}
System.out.println("恭喜!你成功击败了所有僵尸!");
scanner.close();
}
private void plantPlant() {
System.out.println("选择要种植的植物:");
System.out.println("1. 向日葵(花费10阳光)");
System.out.println("2. 豌豆射手(花费20阳光)");
System.out.println("3. 寒冰射手(花费30阳光)");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
if (sunPoints >= 10) {
System.out.println("种植了向日葵。");
sunPoints -= 10;
} else {
System.out.println("阳光点数不足,无法购买。");
}
break;
case 2:
if (sunPoints >= 20) {
System.out.println("种植了豌豆射手。");
sunPoints -= 20;
} else {
System.out.println("阳光点数
不足,无法购买。");
}
break;
case 3:
if (sunPoints >= 30) {
System.out.println("种植了寒冰射手。");
sunPoints -= 30;
} else {
System.out.println("阳光点数不足,无法购买。");
}
break;
default:
System.out.println("无效选择,请重新选择。");
break;
}
scanner.close();
}
private void attackZombie() {
if (zombieCount > 0) {
System.out.println("攻*击了一个僵尸!");
zombieCount--;
} else {
System.out.println("没有僵尸可攻*击。");
}
}
}
public class Main {
public static void main(String[] args) {
Game game = new Game();
game.play();
}
}
该代码创建了一个名为 Game
的游戏类,通过在控制台上展示游戏提示信息和提供选项来模拟游戏过程。玩家可以选择种植植物、*僵尸或跳过回合。游戏以控制僵尸数量的方式进行,当僵尸数量达到设定值时游戏结束。
请注意,这只是一个简化的示例,没有实现游戏的完整功能和交互细节。在实际开发中,你可能需要更多的类和方法来管理植物、僵尸、游戏场景、游戏规则等。此外,还可以添加图形界面、音效、更多的游戏功能等来增强游戏体验。