用java写一个消消乐的小游戏
时间: 2023-09-03 22:09:52 浏览: 199
用java写的一个小游戏
4星 · 用户满意度95%
好的,以下是一个简单的消消乐小游戏的 Java 代码示例:
```java
import java.util.Random;
import java.util.Scanner;
public class XOXOLE {
private static int ROWS = 8; // 行数
private static int COLS = 8; // 列数
private static char[][] board = new char[ROWS][COLS]; // 游戏面板
private static int[] scores = {0, 100, 300, 600, 1000}; // 分数表,根据消除数量计算得分
private static int score = 0; // 当前得分
private static Random rand = new Random(); // 随机数生成器
// 初始化游戏面板
public static void initBoard() {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
board[i][j] = (char) (rand.nextInt(5) + 'A'); // 随机生成字母填充面板
}
}
}
// 打印游戏面板
public static void printBoard() {
System.out.println("Score: " + score);
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 int eliminate(int row, int col) {
char c = board[row][col];
int count = 1;
int i, j;
// 横向消除
for (i = col - 1; i >= 0 && board[row][i] == c; i--) {
count++;
}
for (j = col + 1; j < COLS && board[row][j] == c; j++) {
count++;
}
if (count >= 3) {
for (i = i + 1; i < j; i++) {
board[row][i] = ' ';
}
}
// 纵向消除
count = 1;
for (i = row - 1; i >= 0 && board[i][col] == c; i--) {
count++;
}
for (j = row + 1; j < ROWS && board[j][col] == c; j++) {
count++;
}
if (count >= 3) {
for (i = i + 1; i < j; i++) {
board[i][col] = ' ';
}
}
return scores[Math.min(count, 4)]; // 根据消除数量计算得分,最多4个方块
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
initBoard();
while (true) {
printBoard();
System.out.print("Enter row and column to eliminate (q to quit): ");
String line = scanner.nextLine();
if (line.equalsIgnoreCase("q")) {
break;
}
String[] tokens = line.split("\\s+");
if (tokens.length != 2) {
continue;
}
int row = Integer.parseInt(tokens[0]);
int col = Integer.parseInt(tokens[1]);
if (row < 0 || row >= ROWS || col < 0 || col >= COLS) {
continue;
}
int s = eliminate(row, col);
if (s > 0) {
score += s;
}
}
System.out.println("Final score: " + score);
}
}
```
这个小游戏的玩法是消除相邻的相同字母方块,消除的方块越多得分越高。玩家通过输入行列坐标来选择消除哪个方块,输入 q 可以结束游戏。
阅读全文