用java写一个拼图的游戏
时间: 2023-12-19 08:04:28 浏览: 35
当然可以!下面是一个简单的拼图游戏的 Java 代码示例:
```java
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class PuzzleGame {
private static final int SIZE = 4;
private static final int EMPTY_CELL = SIZE * SIZE;
private int[][] board;
private int[] emptyCell;
public PuzzleGame() {
board = new int[SIZE][SIZE];
emptyCell = new int[]{SIZE - 1, SIZE - 1};
initializeBoard();
}
private void initializeBoard() {
int number = 1;
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
board[i][j] = number++;
}
}
board[SIZE - 1][SIZE - 1] = EMPTY_CELL;
}
private void shuffleBoard() {
Random rand = new Random();
for (int i = SIZE - 1; i >= 0; i--) {
for (int j = SIZE - 1; j >= 0; j--) {
int swapI = rand.nextInt(i + 1);
int swapJ = rand.nextInt(j + 1);
int temp = board[i][j];
board[i][j] = board[swapI][swapJ];
board[swapI][swapJ] = temp;
}
}
emptyCell[0] = SIZE - 1;
emptyCell[1] = SIZE - 1;
}
private void printBoard() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (board[i][j] == EMPTY_CELL) {
System.out.print(" ");
} else {
System.out.print(board[i][j] + " ");
}
}
System.out.println();
}
}
private boolean isMoveValid(int row, int col) {
if (row < 0 || row >= SIZE || col < 0 || col >= SIZE) {
return false;
}
return (Math.abs(emptyCell[0] - row) + Math.abs(emptyCell[1] - col)) == 1;
}
private void move(int row, int col) {
if (!isMoveValid(row, col)) {
System.out.println("Invalid move!");
return;
}
board[emptyCell[0]][emptyCell[1]] = board[row][col];
board[row][col] = EMPTY_CELL;
emptyCell[0] = row;
emptyCell[1] = col;
}
private boolean isSolved() {
int number = 1;
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (board[i][j] != number && !(i == SIZE - 1 && j == SIZE - 1)) {
return false;
}
number++;
}
}
return true;
}
public void play() {
Scanner scanner = new Scanner(System.in);
shuffleBoard();
while (!isSolved()) {
printBoard();
System.out.print("Enter row: ");
int row = scanner.nextInt();
System.out.print("Enter column: ");
int col = scanner.nextInt();
move(row, col);
}
printBoard();
System.out.println("Congratulations! You solved the puzzle!");
}
public static void main(String[] args) {
PuzzleGame game = new PuzzleGame();
game.play();
}
}
```
这个代码示例实现了一个简单的拼图游戏,使用了一个4x4的二维数组来表示拼图的棋盘。游戏开始时,棋盘会被打乱顺序,然后玩家可以通过输入行和列来移动棋子,直到成功还原拼图。
请注意,这只是一个简单的示例,如果你想要更多功能,比如计时器、计分等,你需要根据自己的需求进行扩展。希望对你有所帮助!