用java实现游戏开心消消乐
时间: 2023-09-02 22:07:37 浏览: 49
好的,我可以为您提供一个简单的 Java 实现,下面是代码:
```
import java.util.Random;
import java.util.Scanner;
public class HappyEliminationGame {
public static void main(String[] args) {
int[][] board = new int[6][6];
Random random = new Random();
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
board[i][j] = random.nextInt(5) + 1;
}
}
display(board);
while (true) {
System.out.print("请输入要消除的方块坐标(如:1 2):");
Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();
int y = scanner.nextInt();
if (x < 1 || x > 6 || y < 1 || y > 6) {
System.out.println("输入的坐标不合法,请重新输入!");
continue;
}
if (board[x - 1][y - 1] == 0) {
System.out.println("该方块已经被消除,请重新输入!");
continue;
}
if (!canBeEliminated(board, x - 1, y - 1)) {
System.out.println("该方块无法消除,请重新输入!");
continue;
}
eliminate(board, x - 1, y - 1);
display(board);
if (isGameOver(board)) {
System.out.println("游戏结束!");
break;
}
}
}
public static void display(int[][] board) {
System.out.println(" 1 2 3 4 5 6");
for (int i = 0; i < 6; i++) {
System.out.print(i + 1 + " ");
for (int j = 0; j < 6; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
public static boolean canBeEliminated(int[][] board, int x, int y) {
int color = board[x][y];
int count = 0;
if (x > 0 && board[x - 1][y] == color) {
count++;
}
if (x < 5 && board[x + 1][y] == color) {
count++;
}
if (y > 0 && board[x][y - 1] == color) {
count++;
}
if (y < 5 && board[x][y + 1] == color) {
count++;
}
return count >= 2;
}
public static void eliminate(int[][] board, int x, int y) {
int color = board[x][y];
board[x][y] = 0;
if (x > 0 && board[x - 1][y] == color) {
eliminate(board, x - 1, y);
}
if (x < 5 && board[x + 1][y] == color) {
eliminate(board, x + 1, y);
}
if (y > 0 && board[x][y - 1] == color) {
eliminate(board, x, y - 1);
}
if (y < 5 && board[x][y + 1] == color) {
eliminate(board, x, y + 1);
}
}
public static boolean isGameOver(int[][] board) {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
if (board[i][j] != 0 && canBeEliminated(board, i, j)) {
return false;
}
}
}
return true;
}
}
```
这个程序实现了一个 6x6 的游戏界面,其中每个方块的颜色是随机生成的。玩家通过输入坐标来选择要消除的方块,如果该方块无法消除,则需要重新输入,直到输入合法的坐标为止。如果成功消除一个方块,则会重新显示游戏界面;如果所有方块都被消除完,则游戏结束。