使用Java写一个消消乐游戏
时间: 2023-07-20 19:06:37 浏览: 225
基于Java实现的开心消消乐游戏设计源码
好的,下面是一个简单的Java消消乐游戏代码:
```java
import java.util.*;
public class EliminationGame {
private static final int BOARD_SIZE = 10;
private static final int MIN_GROUP_SIZE = 3;
private static final char[] COLORS = {'R', 'G', 'B', 'Y', 'P'};
private static char[][] board = new char[BOARD_SIZE][BOARD_SIZE];
public static void main(String[] args) {
initBoard();
printBoard();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter row and column of the block you want to eliminate (e.g. 1 2): ");
int row = scanner.nextInt();
int col = scanner.nextInt();
if (isOutOfBounds(row, col) || board[row][col] == ' ') {
System.out.println("Invalid input. Please try again.");
continue;
}
if (!eliminateGroup(row, col)) {
System.out.println("No group can be eliminated from this block. Please try again.");
continue;
}
printBoard();
if (!findGroups()) {
System.out.println("Game over. No more groups can be eliminated.");
break;
}
}
}
private static void initBoard() {
Random random = new Random();
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = COLORS[random.nextInt(COLORS.length)];
}
}
}
private static void printBoard() {
System.out.println();
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
System.out.println();
}
private static boolean isOutOfBounds(int row, int col) {
return row < 0 || row >= BOARD_SIZE || col < 0 || col >= BOARD_SIZE;
}
private static boolean eliminateGroup(int row, int col) {
char color = board[row][col];
if (color == ' ') {
return false;
}
List<int[]> group = new ArrayList<>();
findGroup(row, col, color, group);
if (group.size() < MIN_GROUP_SIZE) {
return false;
}
for (int[] block : group) {
board[block[0]][block[1]] = ' ';
}
return true;
}
private static void findGroup(int row, int col, char color, List<int[]> group) {
if (isOutOfBounds(row, col) || board[row][col] != color || group.contains(new int[]{row, col})) {
return;
}
group.add(new int[]{row, col});
findGroup(row - 1, col, color, group);
findGroup(row + 1, col, color, group);
findGroup(row, col - 1, color, group);
findGroup(row, col + 1, color, group);
}
private static boolean findGroups() {
boolean foundGroup = false;
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
if (eliminateGroup(i, j)) {
foundGroup = true;
}
}
}
return foundGroup;
}
}
```
这个游戏有一个 10x10 的方格棋盘,每个格子可以是五种颜色中的一种(R, G, B, Y, P)。玩家每次选择一个格子,如果它所在的颜色与它周围的同色格子数量不少于 3 个,则这些格子都会被消除,得分加一。游戏结束条件是所有同色格子都被消除。
阅读全文