控制台实现拼图游戏的算法

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;
			}
		}
	}

	/**
	 * 打印拼图完成情况
	 * @param a
	 */
	public static void printfResult(int[][] a) {
		for (int[] i : a) {
			for (int j : i)
				System.out.print((j != 9 ? j : " ") + "\t");
			System.out.println();
		}
	}

	/**
	 * 初始化游戏
	 * @param 打乱拼图
	 */
	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++;
		}
	}

	/**
	 * 判断游戏是否成功
	 * @return TRUE:游戏胜利
	 */
	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;
	}

	/**
	 * 产生[0,a)的一个随机整数
	 */
	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;
				}
	}

	/**
	 * 键盘接收要移动的数字
	 * @return 1~8
	 */
	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();
		}
	}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值