这个是一个基本的“打地鼠”游戏,其中玩家将尝试在格子中击打随机出现的“地鼠”。由于这是一个文本界面的游戏,它不需要复杂的图形或额外的库,非常适合初学者学习Java编程和游戏逻辑。
以下是一个简单的“打地鼠”游戏的源代码:
java复制代码
import java.util.Random; | |
import java.util.Scanner; | |
public class WhackAMoleGame { | |
private static final int GRID_SIZE = 3; // 网格大小 | |
private static final int MAX_ATTEMPTS = 10; // 最大尝试次数 | |
private static final char MOLE = 'M'; // 地鼠字符 | |
private static final char EMPTY = '.'; // 空格字符 | |
private char[][] grid = new char[GRID_SIZE][GRID_SIZE]; | |
private Random random = new Random(); | |
private Scanner scanner = new Scanner(System.in); | |
private int score = 0; // 分数 | |
private int attempts = 0; // 尝试次数 | |
public static void main(String[] args) { | |
WhackAMoleGame game = new WhackAMoleGame(); | |
game.startGame(); | |
} | |
public void startGame() { | |
initializeGrid(); | |
System.out.println("欢迎来到打地鼠游戏!"); | |
System.out.println("网格大小:" + GRID_SIZE + "x" + GRID_SIZE); | |
System.out.println("你最多可以尝试 " + MAX_ATTEMPTS + " 次。"); | |
System.out.println("输入行和列来击打地鼠(例如:1 2),输入'quit'退出游戏。"); | |
while (attempts < MAX_ATTEMPTS) { | |
displayGrid(); | |
spawnMole(); | |
System.out.print("你的选择:"); | |
String input = scanner.nextLine(); | |
if (input.equalsIgnoreCase("quit")) { | |
System.out.println("游戏结束。你的得分是:" + score); | |
break; | |
} | |
try { | |
String[] parts = input.split(" "); | |
int row = Integer.parseInt(parts[0]) - 1; | |
int col = Integer.parseInt(parts[1]) - 1; | |
if (row >= 0 && row < GRID_SIZE && col >= 0 && col < GRID_SIZE && grid[row][col] == MOLE) { | |
System.out.println("击中!"); | |
score++; | |
attempts++; // 只有击中时才增加尝试次数,以鼓励多次尝试 | |
} else { | |
System.out.println("未击中!"); | |
attempts++; | |
} | |
} catch (Exception e) { | |
System.out.println("无效输入。请重新输入行和列。"); | |
attempts++; // 无效输入也算作一次尝试 | |
} | |
} | |
if (attempts == MAX_ATTEMPTS) { | |
System.out.println("游戏结束。你没有更多的尝试机会了。你的得分是:" + score); | |
} | |
scanner.close(); | |
} | |
private void initializeGrid() { | |
for (int i = 0; i < GRID_SIZE; i++) { | |
for (int j = 0; j < GRID_SIZE; j++) { | |
grid[i][j] = EMPTY; | |
} | |
} | |
} | |
private void displayGrid() { | |
for (int i = 0; i < GRID_SIZE; i++) { | |
for (int j = 0; j < GRID_SIZE; j++) { | |
System.out.print(grid[i][j] + " "); | |
} | |
System.out.println(); | |
} | |
} | |
private void spawnMole() { | |
int row = random.nextInt(GRID_SIZE); | |
int col = random.nextInt(GRID_SIZE); | |
grid[row][col] = MOLE; | |
} | |
} |
在这个游戏中:
GRID_SIZE
定义了网格的大小。MAX_ATTEMPTS
定义了玩家可以尝试的最大次数。MOLE
和EMPTY
分别代表地鼠字符和空格字符。grid
是一个二维字符数组,用于表示游戏网格。random
用于生成随机数,以确定地鼠出现的位置。scanner
用于从控制台读取玩家的输入。score
和attempts
分别跟踪玩家的得分和尝试次数。
游戏开始时,网格被初始化为全空。在每轮中,地鼠随机出现在网格中的一个位置,玩家输入行和列来尝试击打它。如果玩家击中地鼠,则得分增加,并且不立即结束游戏(为了鼓励多次尝试,只有击中时才增加尝试计数)。如果玩家输入无效或未击中地鼠,则尝试次数增加。当玩家达到最大尝试次数时,游戏结束,并显示最终得分。玩家也可以选择输入“quit”来提前结束游戏。