用java写一个拼图游戏代码
时间: 2024-05-07 13:20:16 浏览: 129
JAVA拼图游戏源码 JAVAPTYX.rar
好的,以下是一个简单的拼图游戏Java代码:
```
import java.util.*;
public class PuzzleGame {
public static void main(String[] args) {
int[][] board = {{1, 2, 3}, {4, 5, 6}, {7, 8, 0}}; //初始状态
shuffle(board); //打乱拼图
int steps = playGame(board); //开始游戏
System.out.println("完成游戏,步数为:" + steps);
}
//打乱拼图
public static void shuffle(int[][] board) {
Random rand = new Random();
for (int i = board.length - 1; i > 0; i--) {
for (int j = board[0].length - 1; j > 0; j--) {
int x = rand.nextInt(i+1);
int y = rand.nextInt(j+1);
int temp = board[i][j];
board[i][j] = board[x][y];
board[x][y] = temp;
}
}
}
//开始游戏,返回步数
public static int playGame(int[][] board) {
int steps = 0;
while (!isFinished(board)) {
printBoard(board);
System.out.print("请输入要移动的数码(1-8):");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
if (moveTile(board, num)) {
steps++;
} else {
System.out.println("移动失败,请重新输入!");
}
}
return steps;
}
//判断是否完成游戏
public static boolean isFinished(int[][] board) {
int count = 1;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] != count) {
return false;
}
count++;
}
}
return true;
}
//移动数码
public static boolean moveTile(int[][] board, int num) {
int row = -1, col = -1;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == num) {
row = i;
col = j;
break;
}
}
}
if (row == -1 || col == -1) {
return false; //数码不存在
}
if (row > 0 && board[row-1][col] == 0) { //向上移动
board[row-1][col] = num;
board[row][col] = 0;
return true;
} else if (row < board.length-1 && board[row+1][col] == 0) { //向下移动
board[row+1][col] = num;
board[row][col] = 0;
return true;
} else if (col > 0 && board[row][col-1] == 0) { //向左移动
board[row][col-1] = num;
board[row][col] = 0;
return true;
} else if (col < board[0].length-1 && board[row][col+1] == 0) { //向右移动
board[row][col+1] = num;
board[row][col] = 0;
return true;
}
return false; //移动失败
}
//输出当前状态
public static void printBoard(int[][] board) {
System.out.println("当前状态:");
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
}
```
请注意,这只是一个简单的示例,实际上,拼图游戏需要实现更复杂的算法和图形界面。如果您有其他问题或需要更详细的解释,请随时问我。
阅读全文