java完整代码进入教学项目《打地鼠》的开发 (1)生成有10个位置的地图(含10个元素的一维数组),每个元素都是数字0表示空 (2)在地图中的每个位置都有一定几率随机放入老鼠,使用数字1表示 (3)把地图打印在控制台 (4)在控制台提示用户输入打击的位置(坐标),判断并提示是否打中 (5)玩家一开始有血量2,玩家打中老鼠会加血量1,没打中老鼠扣1滴血值 ,当血量为0的时候提示失败,血量为4的时候提示胜利,失败或者胜利都提问玩家是否重新开始游戏,玩家输入1继续游戏,输入0退出游戏
时间: 2023-12-05 21:03:49 浏览: 77
很高兴为您提供帮助!以下是Java完整代码进入教学项目《打地鼠》的开发:
```
import java.util.Random;
import java.util.Scanner;
public class WhackAMoleGame {
private static final int MAP_SIZE = 10;
private static final int MOLE_PROBABILITY = 3; //老鼠出现的概率为1/3
private static final int MAX_HEALTH = 4;
private static final int MIN_HEALTH = 0;
private static final int HIT_POINT = 1;
private static final int MISS_POINT = -1;
private int[] map;
private int health;
public static void main(String[] args) {
WhackAMoleGame game = new WhackAMoleGame();
game.play();
}
public WhackAMoleGame() {
map = new int[MAP_SIZE];
health = MAX_HEALTH;
}
public void play() {
Scanner scanner = new Scanner(System.in);
boolean isPlaying = true;
while (isPlaying) {
initializeMap();
printMap();
while (health > MIN_HEALTH && health < MAX_HEALTH) {
int position = promptUserForPosition(scanner);
if (hitMole(position)) {
System.out.println("恭喜你,打中老鼠了!");
health += HIT_POINT;
} else {
System.out.println("很遗憾,你没有打中老鼠!");
health += MISS_POINT;
}
printMap();
}
if (health == MIN_HEALTH) {
System.out.println("很抱歉,你失败了!");
} else {
System.out.println("恭喜你,你胜利了!");
}
isPlaying = promptUserForRestart(scanner);
if (isPlaying) {
health = MAX_HEALTH;
}
}
}
private void initializeMap() {
Random random = new Random();
for (int i = 0; i < map.length; i++) {
if (random.nextInt(MOLE_PROBABILITY) == 0) {
map[i] = 1;
} else {
map[i] = 0;
}
}
}
private void printMap() {
System.out.println("------------");
for (int i = 0; i < map.length; i++) {
if (i != 0 && i % 10 == 0) {
System.out.println("|");
}
System.out.print("| " + map[i] + " ");
}
System.out.println("|");
System.out.println("------------");
}
private int promptUserForPosition(Scanner scanner) {
int position;
do {
System.out.print("请输入打击的位置(0-9):");
position = scanner.nextInt();
if (position < 0 || position > 9) {
System.out.println("输入的位置不正确,请重新输入!");
}
} while (position < 0 || position > 9);
return position;
}
private boolean hitMole(int position) {
if (map[position] == 1) {
map[position] = 0;
return true;
} else {
return false;
}
}
private boolean promptUserForRestart(Scanner scanner) {
int choice;
do {
System.out.print("是否重新开始游戏?(1-继续,0-退出):");
choice = scanner.nextInt();
if (choice != 0 && choice != 1) {
System.out.println("输入错误,请重新输入!");
}
} while (choice != 0 && choice != 1);
return choice == 1;
}
}
```
代码中使用了一个 `WhackAMoleGame` 类来实现游戏逻辑,其中 `initializeMap` 方法用于初始化地图, `printMap` 方法用于打印地图, `promptUserForPosition` 方法用于提示用户输入打击的位置, `hitMole` 方法用于判断用户是否打中老鼠, `promptUserForRestart` 方法用于提示用户是否重新开始游戏。在 `play` 方法中,通过循环实现了多次游戏的机制,当血量为0或者4时,结束一次游戏,并询问用户是否重新开始游戏。
阅读全文
相关推荐


















