java拼图游戏 java控制台实现拼图游戏

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

java拼图游戏 java控制台实现拼图游戏

yyjnz   2021-07-23 我要评论
想了解java控制台实现拼图游戏的相关内容吗,yyjnz在本文为您仔细讲解java拼图游戏的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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;
   }
  }
 }

 /**
  * 打印拼图完成情况
  * @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();
  }
 }

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们