拼圖遊戲(控制檯)

涉及的相關知識點有,一維數組的創建,一維數組的打亂排序,一維數組轉化爲二維數組,switch()的使用。

package demo;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Test3 {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] a = { 1, 2, 3, 4, 0, 6, 7, 8, 5 };
		int[] crr = { 1, 2, 3, 4, 0, 6, 7, 8, 5 };	//保留原始數據
		System.out.println(Arrays.toString(crr));
		System.out.println();
		
		Random r = new Random();
		int k = 0;
		
		 /**
		  *  打亂一維數組
		 **/ 
		 
		while (k < 20) {

			int i = r.nextInt(8);
			int j = r.nextInt(8);
			int t = a[i];
			a[i] = a[j];
			a[j] = t;
			k++;
		}
		System.out.println(Arrays.toString(a));
		System.out.println("--------------");
		int b[][] = new int[3][3];//定義二維數組
		/*
		 * 一維轉二維
		 */
		for (int i = 0; i < a.length; i++) {
			b[i / 3][i % 3] = a[i];

		}
		for (int j = 0; j < b.length; j++) {
			System.out.println(Arrays.toString(b[j]));
		}

		System.out.println("------------------");
        /*
         * 尋找0
         */
		int indexX = 0;//二維行下標
		int indexY = 0;//二維列下標
		for (int i = 0; i < b.length; i++) {
			for (int j = 0; j < b[i].length; j++) {
				if (b[i][j] == 0) {
					indexX = i;
					indexY = j;
					break;
				}

			}
		}
		Scanner sc = new Scanner(System.in);
		while (true) {
			System.out.println("請輸入w上移,s下移,a左移,d右移");
			String ch = sc.next();
			switch (ch) {
			case "w":
				if (indexX > 0) {
					int t = b[indexX][indexY];
					b[indexX][indexY] = b[indexX- 1][indexY ];
					b[indexX- 1][indexY ] = t;
					indexX--;
				}
				break;

			case "s":
				if (indexX < b.length - 1) {
					int t = b[indexX][indexY];
					b[indexX][indexY] = b[indexX+ 1][indexY ];
					b[indexX+ 1][indexY ] = t;
					indexX++;
				}

				break;
			case "a":
				if (indexY >0) {
					int t = b[indexX][indexY];
					b[indexX][indexY] = b[indexX][indexY - 1 ];
					b[indexX][indexY -1] = t;
					indexY--;
				}
				break;
			case "d":
				if (indexY < b.length -1) {
					int t = b[indexX][indexY];
					b[indexX][indexY] = b[indexX][indexY + 1 ];
					b[indexX][indexY + 1] = t;
					indexY++;
				}
				break;
			}
			for (int j = 0; j < b.length; j++) {
				System.out.println(Arrays.toString(b[j]));
			}
			/*
			 * 判斷是否拼圖成功
			 */
			int g = 0;//一維下標
			boolean flag = true;
			for(int i = 0 ; i < b.length && flag; i++){				
				for(int j = 0; j < b[i].length; j++){
					
					  if( b[i][j] != crr[g]){
						  flag = false;
						  //System.out.println(crr[g]);
						  System.out.println("拼圖失敗");
						  break;
					  }
					   g++;
				}
			}
			if(flag){
				System.out.println("拼圖成功");
				break;
			}
		}
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章