Java 实现植物大战僵尸游戏简单代码示例
import java.util.*;
public class PlantVsZombie {
static class Plant {
int position;
int power;
}
static class Zombie {
int position;
int power;
}
public static void main(String[] args) {
Plant[] plants = new Plant[5];
Zombie[] zombies = new Zombie[5];
initPlants(plants);
initZombies(zombies);
while (true) {
// Plants attack
for (Plant p : plants) {
attack(p, zombies);
}
// Zombies attack
for (Zombie z : zombies) {
attack(z, plants);
}
// Check whether all zombies and plants are destroyed
boolean allPlantsDestroyed = true;
boolean allZombiesDestroyed = true;
for (Plant p : plants) {
if (p.power > 0) {
allPlantsDestroyed = false;
break;
}
}
for (Zombie z : zombies) {
if (z.power > 0) {
allZombiesDestroyed = false;
break;
}
}
if (allPlantsDestroyed || allZombiesDestroyed) {
break;
}
}
if (allPlantsDestroyed) {
System.out.println('Zombies win!');
} else {
System.out.println('Plants win!');
}
}
private static void attack(Plant p, Zombie[] zombies) {
for (Zombie z : zombies) {
if (z.position == p.position) {
z.power -= p.power;
}
}
}
private static void attack(Zombie z, Plant[] plants) {
for (Plant p : plants) {
if (p.position == z.position) {
p.power -= z.power;
}
}
}
private static void initPlants(Plant[] plants) {
for (int i = 0; i < plants.length; i++) {
Plant p = new Plant();
p.position = i + 1;
p.power = 10;
plants[i] = p;
}
}
private static void initZombies(Zombie[] zombies) {
for (int i = 0; i < zombies.length; i++) {
Zombie z = new Zombie();
z.position = i + 1;
z.power = 15;
zombies[i] = z;
}
}
}
原文地址: https://www.cveoy.top/t/topic/lgR5 著作权归作者所有。请勿转载和采集!