
# 人狗大战的JAVA实现
在闲暇时光,编写一个有趣的小游戏总是能带来乐趣。今天,我们将用Java实现一个简单的人狗大战游戏。这个游戏的设定是在一个二维网格上,玩家控制一个人类角色,而计算机控制一只狗。在这个游戏中,玩家需要躲避狗的追击,并尽量收集道具。
游戏规则
1. 游戏在一个5x5的网格上进行。
2. 玩家和狗各自在网格中的随机位置。
3. 玩家可以通过输入方向(上、下、左、右)来移动。
4. 狗会自动随机移动,尽量接近玩家。
5. 如果狗追上了玩家,游戏结束。
代码实现
下面是这个游戏的简单实现:
java
import java.util.Random;
import java.util.Scanner;
public class HumanDogBattle {
static char[][] grid = new char[5][5];
static int humanX, humanY, dogX, dogY;
static Random rand = new Random();
public static void main(String[] args) {
initializeGame();
Scanner scanner = new Scanner(System.in);
while (true) {
printGrid();
System.out.println("请输入移动方向(WASD):");
char move = scanner.next().toUpperCase().charAt(0);
moveHuman(move);
moveDog();
if (humanX == dogX && humanY == dogY) {
printGrid();
System.out.println("狗抓住了你!游戏结束。");
break;
}
}
scanner.close();
}
static void initializeGame() {
humanX = rand.nextInt(5);
humanY = rand.nextInt(5);
dogX = rand.nextInt(5);
dogY = rand.nextInt(5);
while (humanX == dogX && humanY == dogY) {
dogX = rand.nextInt(5);
dogY = rand.nextInt(5);
}
}
static void printGrid() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i == humanX && j == humanY) {
System.out.print("H ");
} else if (i == dogX && j == dogY) {
System.out.print("D ");
} else {
System.out.print(". ");
}
}
System.out.println();
}
}
static void moveHuman(char direction) {
switch (direction) {
case "W": humanX = Math.max(0, humanX - 1); break;
case "S": humanX = Math.min(4, humanX + 1); break;
case "A": humanY = Math.max(0, humanY - 1); break;
case "D": humanY = Math.min(4, humanY + 1); break;
default: System.out.println("无效的指令!");
}
}
static void moveDog() {
if (dogX < humanX) dogX++;
else if (dogX > humanX) dogX--;
if (dogY < humanY) dogY++;
else if (dogY > humanY) dogY--;
}
}
总结
这段代码展示了一个简单的人狗大战游戏的基本实现。通过不断循环,让玩家和狗在二维网格中进行互动。玩家需要通过灵活的控制来避开狗的追击,增加了游戏的趣味性。希望这个小项目能激励你更深入地探索Java编程的乐趣!