Java

Java实现简单连连看游戏

小云
113
2023-08-10 14:17:08
栏目: 编程语言

下面是一个简单的Java实现连连看游戏的例子:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class LianLianKan {
private static final int ROWS = 5;
private static final int COLS = 6;
private static final int EMPTY = 0;
private static final int WALL = -1;
private static int[][] board = new int[ROWS][COLS];
public static void main(String[] args) {
initializeBoard();
printBoard();
while (true) {
System.out.println("请输入两个相同的数字坐标,以空格分隔(例如:1 2 3 4):");
Scanner scanner = new Scanner(System.in);
int x1 = scanner.nextInt();
int y1 = scanner.nextInt();
int x2 = scanner.nextInt();
int y2 = scanner.nextInt();
if (isValidMove(x1, y1, x2, y2)) {
if (isConnectable(x1, y1, x2, y2)) {
board[x1][y1] = EMPTY;
board[x2][y2] = EMPTY;
printBoard();
} else {
System.out.println("两个坐标不能连通,请重新输入!");
}
} else {
System.out.println("输入的坐标不合法,请重新输入!");
}
}
}
private static void initializeBoard() {
// 初始化边界为墙
for (int i = 0; i < ROWS; i++) {
board[i][0] = WALL;
board[i][COLS - 1] = WALL;
}
for (int j = 0; j < COLS; j++) {
board[0][j] = WALL;
board[ROWS - 1][j] = WALL;
}
// 随机生成数字
for (int i = 1; i < ROWS - 1; i++) {
for (int j = 1; j < COLS - 1; j++) {
board[i][j] = (int) (Math.random() * 10);
}
}
}
private static void printBoard() {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (board[i][j] == WALL) {
System.out.print("# ");
} else if (board[i][j] == EMPTY) {
System.out.print("  ");
} else {
System.out.print(board[i][j] + " ");
}
}
System.out.println();
}
}
private static boolean isValidMove(int x1, int y1, int x2, int y2) {
return x1 > 0 && x1 < ROWS - 1 && y1 > 0 && y1 < COLS - 1 &&
x2 > 0 && x2 < ROWS - 1 && y2 > 0 && y2 < COLS - 1 &&
board[x1][y1] != WALL && board[x2][y2] != WALL &&
board[x1][y1] != EMPTY && board[x2][y2] != EMPTY;
}
private static boolean isConnectable(int x1, int y1, int x2, int y2) {
if (board[x1][y1] != board[x2][y2]) {
return false;
}
List<Point> path = new ArrayList<>();
if (findPath(x1, y1, x2, y2, path)) {
return true;
}
return false;
}
private static boolean findPath(int x1, int y1, int x2, int y2, List<Point> path) {
if (x1 == x2 && y1 == y2) {
return true;
}
if (board[x1][y1] == EMPTY || board[x2][y2] == EMPTY) {
return false;
}
Point point1 = new Point(x1, y1);
Point point2 = new Point(x2, y2);
// 横向直连
if (isHorizontalConnectable(point1, point2)) {
path.add(point1);
path.add(point2);
return true;
}
// 纵向直连
if (isVerticalConnectable(point1, point2)) {
path.add(point1);
path.add(point2);
return true;
}
// 单转折连接
if (isSingleTurn

0
看了该问题的人还看了