运用java写一个坦克大战小游戏的代码
时间: 2024-05-18 12:11:42 浏览: 176
java制作简单的坦克大战
好的,以下是一个简单的Java代码示例,实现了一个“坦克大战”小游戏:
```java
import java.util.Scanner;
public class TankWarGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[][] map = new int[10][10];
int playerX = 0, playerY = 0;
int enemyX = 9, enemyY = 9;
int playerHP = 10, enemyHP = 10;
System.out.println("欢迎来到坦克大战游戏!");
// 初始化地图
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
map[i][j] = 0;
}
}
map[playerX][playerY] = 1;
map[enemyX][enemyY] = 2;
while (true) {
// 输出当前地图
System.out.println("当前地图:");
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (map[i][j] == 0) {
System.out.print("-");
} else if (map[i][j] == 1) {
System.out.print("P");
} else if (map[i][j] == 2) {
System.out.print("E");
} else if (map[i][j] == 3) {
System.out.print("*");
}
System.out.print(" ");
}
System.out.println();
}
// 让玩家进行操作
System.out.println("请操作:W上 S下 A左 D右 F开火");
String operation = scanner.next();
int moveX = 0, moveY = 0;
boolean fire = false;
switch (operation) {
case "W":
moveY = -1;
break;
case "S":
moveY = 1;
break;
case "A":
moveX = -1;
break;
case "D":
moveX = 1;
break;
case "F":
fire = true;
break;
default:
System.out.println("无效操作!");
break;
}
// 检查玩家是否越界
if (playerX + moveX < 0 || playerX + moveX >= 10 || playerY + moveY < 0 || playerY + moveY >= 10) {
System.out.println("玩家越界了!");
continue;
}
// 检查玩家是否碰到敌人
if (playerX + moveX == enemyX && playerY + moveY == enemyY) {
System.out.println("玩家撞到了敌人!");
playerHP--;
if (playerHP <= 0) {
System.out.println("玩家被击败了!");
break;
}
}
// 检查敌人是否越界
if (enemyX + moveX < 0 || enemyX + moveX >= 10 || enemyY + moveY < 0 || enemyY + moveY >= 10) {
System.out.println("敌人越界了!");
continue;
}
// 敌人移动
if (Math.random() < 0.5) {
if (enemyX < playerX) {
enemyX++;
} else if (enemyX > playerX) {
enemyX--;
}
} else {
if (enemyY < playerY) {
enemyY++;
} else if (enemyY > playerY) {
enemyY--;
}
}
// 检查敌人是否碰到玩家
if (enemyX == playerX && enemyY == playerY) {
System.out.println("敌人撞到了玩家!");
enemyHP--;
if (enemyHP <= 0) {
System.out.println("敌人被击败了!");
break;
}
}
// 玩家移动
map[playerX][playerY] = 0;
playerX += moveX;
playerY += moveY;
map[playerX][playerY] = 1;
// 玩家开火
if (fire) {
int bulletX = playerX + moveX;
int bulletY = playerY + moveY;
while (bulletX >= 0 && bulletX < 10 && bulletY >= 0 && bulletY < 10) {
if (map[bulletX][bulletY] == 0) {
map[bulletX][bulletY] = 3;
} else if (map[bulletX][bulletY] == 2) {
System.out.println("玩家击中了敌人!");
enemyHP--;
if (enemyHP <= 0) {
System.out.println("敌人被击败了!");
break;
}
map[bulletX][bulletY] = 0;
break;
} else {
break;
}
bulletX += moveX;
bulletY += moveY;
}
}
}
}
}
```
这个小游戏的规则很简单:玩家需要控制坦克移动并射击敌人,同时避免敌人撞到自己。坦克每次可以向上、下、左、右移动一个格子,并可以发射子弹。如果坦克撞到敌人或被敌人撞到,会受到伤害;如果血量降为0,坦克就会被击败。如果成功击败敌人,游戏胜利。
阅读全文