中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

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
莱阳市| 黄浦区| 边坝县| 密山市| 安多县| 余姚市| 正宁县| 济宁市| 永仁县| 通河县| 岚皋县| 红安县| 麦盖提县| 海宁市| 平乐县| 岐山县| 营口市| 新津县| 思茅市| 碌曲县| 宝坻区| 石家庄市| 奉新县| 广丰县| 霞浦县| 嘉祥县| 江都市| 济宁市| 太白县| 阳朔县| 南澳县| 凌源市| 新龙县| 金溪县| 视频| 日喀则市| 庄浪县| 无为县| 德清县| 抚顺县| 高淳县|