0 1 2 3
4 5 6 7
8 9 10 11
12 13 14
因爲前些日子做了一些簡單的益智遊戲,所以涉及了一些算法上的問題,本來以爲這些小遊戲非常簡單,但也爲了效率的確令我小頭痛了一下。
開始很快的寫玩拼圖遊戲,玩了玩發現有時候會無解,到論壇看了看,好多人在探討如何驗證拼圖無解,大概就是矩陣的逆序數+數眼的奇偶性判斷。
正痛苦的時候老付跟我說,你回憶一下咱小時候玩拼圖怎麼玩的呢,我說我拼不好的話就給它們都扣下來再按上,他說都是完整的拼圖手動隨意打亂的。
果然啊,其實如果是拼圖遊戲不必如此費力還要去驗證是否有解,如果是生成的整齊矩陣,手動打亂的話必然能保證有解。
初始化時,根據隨機數去讓圖塊4方向填補空位。循環100次就ok了。
部分代碼如下:
- //4X4的數組
- public static final int game1[][]={
- {0,1,2,3},
- {4,5,6,7},
- {8,9,10,11},
- {12,13,14,15}
- };
- //得到順序2維數組
- public int [][] get2arry(int arry[][]){
- arry=null;
- arry=new int[4][4];
- for(int i=0;i<arry.length;++i){
- for(int j=0;j<arry[i].length;++j){
- arry[i][j]=i*4+j;
- }
- }
- return arry;
- }
- //初始化圖塊數組
- public void InitMy() {
- if (buffergame == null) {
- int index = 0;
- int bufferInt = 0;
- buffergame = this.get2arry(buffergame);
- while (true) {
- for (int i = 0; i < buffergame.length; ++i) {
- for (int j = 0; j < buffergame[i].length; ++j) {
- if (buffergame[i][j] == 0) {
- bufferInt = t.getRandomNumber(0, 2000);
- if (bufferInt < 500) {
- if (i == 3) {
- break;
- }
- buffergame[i][j] = buffergame[i +
- 1][j];
- buffergame[i + 1][j] = 0;
- ++index;
- } else if (bufferInt < 1000) {
- if (i == 0) {
- break;
- }
- buffergame[i][j] = buffergame[i -
- 1][j];
- buffergame[i - 1][j] = 0;
- ++index;
- } else if (bufferInt < 1500) {
- if (j == 3) {
- break;
- }
- buffergame[i][j] = buffergame[i][j +
- 1];
- buffergame[i][j + 1] = 0;
- ++index;
- } else {
- if (j == 0) {
- break;
- }
- buffergame[i][j] = buffergame[i][j -
- 1];
- buffergame[i][j - 1] = 0;
- ++index;
- }
- }
- }
- }
- if (index > 200) {
- break;
- }
- // int pos1, pos2;
- // for (int i = 0; i < buffergame.length; ++i) {
- // for (int j = 0; j < buffergame[i].length; ++j) {
- // while (true) {
- // pos1 = t.getRandomNumber(0, 3);
- // pos2 = t.getRandomNumber(0, 3);
- // if (buffer[pos1][pos2] != 100) {
- // buffergame[i][j] = buffer[pos1][pos2];
- // buffer[pos1][pos2] = 100;
- //// System.out.println("buffergame[" + i +
- //// "][" + j + "]==" +
- //// buffergame[i][j]);
- // break;
- // }
- // }
- // }
- // }
- // //如果奇偶性不同 從新生成
- // if(this.TestArry(buffergame)){
- // if(Type.isprint)
- // System.out.println("有解");
- // break;
- // }else{
- // if(Type.isprint)
- // System.out.println("無解");
- // }
- // }
- }
- }
- if (Type.isprint)
- System.out.println("Init is ok!!");
- }