本文实例为大家分享了java控制台实现拼图游戏的具体代码,供大家参考,具体内容如下
1、首先对原始的拼图进行多次无规律的移动,将拼图打乱
2、然后进行游戏,在游戏移动同时对拼图顺序进行判断
①如果拼图成功,则跳出循环,结束游戏;
②如果拼图失败,陷入死循环,继续移动拼图,直至拼图成功为止。
import java.util.Random;
import java.util.Scanner;
public class GrameOfPingTuTest{
private static Scanner scanner = new Scanner(System.in);
private static int h = 2;
private static int l = 2;
private static int x = 0;
private static int y = 0;
private static Random random = new Random();
public static void main(String[] args) {
int[][] youxi = new int[][] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
initGrame(youxi);
System.out.println("游戏开始!");
playGrame(youxi);
}
public static void playGrame(int[][] a) {
int c = 0;
while (true) {
printfResult(a);
c=event();
houQuXY(c,a);
if (isDon(x, y)) {// 先判断是否能够移动,开始移动拼图
yiDon(x, y,a);
if (resultOfGrame(a)) {
System.out.println("游戏完成,恭喜你取得胜利!!");
printfResult(a);
break;
}
continue;
} else {
System.out.println("无法移动,请重新输入移动数字!");
continue;
}
}
}
public static void printfResult(int[][] a) {
for (int[] i : a) {
for (int j : i)
System.out.print((j != 9 ? j : " ") + "\t");
System.out.println();
}
}
public static void initGrame(int[][] a) {
int m = 1;
while (m <= 100) {
while (true) {
x = runNum(3);
y = runNum(3);
if (isDon(x, y))
break;
}
yiDon(x, y, a);
m++;
}
}
public static boolean resultOfGrame(int [][] a) {
int c = 1;
for (int[] b : a)
for (int i : b)
if (i != c++)
return false;
return true;
}
public static void yiDon(int x, int y,int[][] a) {
int m = a[h][l];
a[h][l] = a[x][y];
a[x][y] = m;
h = x;
l = y;
}
public static boolean isDon(int x, int y) {
if (h == x && Math.abs(l - y) == 1)
return true;
if (l == y && Math.abs(h - x) == 1)
return true;
return false;
}
public static int runNum(int a) {
return random.nextInt(a);
}
public static void houQuXY(int c,int[][] a) {
for (int i = 0; i < a.length; i++)
for (int j = 0; j < a[i].length; j++)
if (c == a[i][j]) {
x = i;
y = j;
}
}
public static int event() {
System.out.println("请输入要移动的数字");
String output = scanner.nextLine();// 输入失败重写输入
if (output.length() == 1) {// 只能输入一个字符
char s = output.charAt(0);// 只能输入1~8
if (s > '0' && s < '9')
return (Integer.parseInt(output));
}
System.out.println("输入不合法,请重新输入!!");
return event();
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。