java打地鼠游戏_用Java控制台实现打地鼠游戏(简版)代码
时间: 2023-12-09 08:04:02 浏览: 111
好的,以下是用Java控制台实现打地鼠游戏(简版)的代码示例:
```java
import java.util.Random;
import java.util.Scanner;
public class WhackAMoleGame {
private static final int ROWS = 3;
private static final int COLS = 3;
private static final int MOLES = 3;
private static final int MAX_TRIES = 10;
private static final int POINTS_PER_HIT = 1;
private static final char MOLE_SYMBOL = 'M';
private static final char WHACK_SYMBOL = 'X';
private static final char MISS_SYMBOL = 'O';
private char[][] board;
private int score;
private int tries;
private Random random;
private Scanner scanner;
public WhackAMoleGame() {
board = new char[ROWS][COLS];
random = new Random();
scanner = new Scanner(System.in);
score = 0;
tries = MAX_TRIES;
}
public void play() {
// 初始化游戏面板
initBoard();
// 开始游戏
while (tries > 0) {
System.out.println("你还有" + tries + "次机会,得分:" + score);
displayBoard();
System.out.print("请输入要打的行号(1-" + ROWS + "):");
int row = scanner.nextInt() - 1;
System.out.print("请输入要打的列号(1-" + COLS + "):");
int col = scanner.nextInt() - 1;
if (row >= 0 && row < ROWS && col >= 0 && col < COLS) {
if (board[row][col] == MOLE_SYMBOL) {
System.out.println("恭喜你,打到了地鼠!");
board[row][col] = WHACK_SYMBOL;
score += POINTS_PER_HIT;
} else {
System.out.println("很遗憾,你没有打到地鼠");
board[row][col] = MISS_SYMBOL;
}
tries--;
} else {
System.out.println("输入无效,请重新输入");
}
// 重新生成地鼠
if (random.nextInt(10) < MOLES) {
int moleRow = random.nextInt(ROWS);
int moleCol = random.nextInt(COLS);
board[moleRow][moleCol] = MOLE_SYMBOL;
}
}
// 游戏结束
System.out.println("游戏结束,得分:" + score);
}
private void initBoard() {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
board[i][j] = '-';
}
}
for (int i = 0; i < MOLES; i++) {
int moleRow = random.nextInt(ROWS);
int moleCol = random.nextInt(COLS);
board[moleRow][moleCol] = MOLE_SYMBOL;
}
}
private void displayBoard() {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
WhackAMoleGame game = new WhackAMoleGame();
game.play();
}
}
```
希望这个代码示例可以帮助您更好地理解如何用Java控制台实现打地鼠游戏。
阅读全文