c++學習筆記
試著寫了一下
用乙個二維陣列模擬遊戲棋盤,在二維陣列上的空位置隨機位置生成數字2或4,然後接收使用者操作,向指定的方向移動並合併數字,再次生成數字,如此往復,直到遊戲結束。
這裡有幾個問題:
遊戲結束條件
如何保證隨機生成的位置不會覆蓋已有數字
如何移動與合併數字
遊戲結束的條件為,隨機生成數字後棋盤為滿,且此時已經沒有數字可以再合併。而為了保證隨機生成的位置不會覆蓋已有數字,可以將還沒空的數字單獨存在乙個陣列中,生成數字時在這個陣列中生成。
移動與合併數字可以根據使用者輸入的操作依次掃瞄每排或每列的相鄰兩個非零數字,判斷是否相同,如果有相同數字則可以移動,依次將可合併的數字合併,並排列到使用者輸入的方向即可
具體實現:
//遊戲類
//提供棋盤與函式介面
#pragma once
#include
#include
#include
using
namespace std;
#define gamesize 4
class
game_2048
;
//編寫遊戲規則,呼叫函式介面
#include
using
namespace std;
#include
"2048.h"
intmain()
system
("pause");
return0;
}
具體的函式實現:
#include
using
namespace std;
#include
"2048.h"
game_2048::
game_2048()
}this
->counter =0;
this
->
updateea()
;}void game_2048::
showchessboard()
cout << endl;
cout << endl;}}
bool game_2048::
makenum()
}void game_2048::
updateea()
this
->empty_array =
newint
*[gamesize*gamesize]
;int flag =0;
for(
int i =
0; i < gamesize*gamesize ; i++)}
}bool game_2048::
isfull()
char game_2048::
direction()
//讀取鍵盤的方向鍵
bool game_2048::
moveable()
}}}for
(int i =
0; i < gamesize; i++)}
}}return0;
}}bool game_2048::
move
(char op)
elseif(
*line2 !=
*line1 &&
*line1 !=0&&
*line2 !=0)
//排序
else
}elseif(
*line2 ==0&&
*line1 !=0)
//排序
}else
}else
//右移
elseif(
*line2 !=
*line1 &&
*line1 !=0&&
*line2 !=0)
//排序
else
}elseif(
*line2 ==0&&
*line1 !=0)
//排序
}else}}
line2 =
null;}
}else
//上下移動
elseif(
*line2 !=
*line1 &&
*line1 !=0&&
*line2 !=0)
//排序
else
}elseif(
*line2 ==0&&
*line1 !=0)
//排序
}else
}else
//下移
elseif(
*line2 !=
*line1 &&
*line1 !=0&&
*line2 !=0)
//排序
else
}elseif(
*line2 ==0&&
*line1 !=0)
//排序
}else}}
line2 =
null;}
}this
->
updateea()
;return flag;
}else
}bool game_2048::
gameover
(bool creat)
else
cout <<
"遊戲結束"
<< endl;
return1;
}game_2048::
~game_2048()
}
C 實現2048小遊戲
1 define crt secure no warnings 去掉編譯器內部擴增問題 2 include3 include4 include5 include 6 include7 include8 include 9 include10 include11 include12 using nam...
C 自實現2048小遊戲
include include using namespace std const int n 5 地圖為4 4 int map n n 存圖 inline void generate rand 在隨機位置產生2或4 map x y rand 2?2 4 inline void build star...
js實現2048小遊戲
頁面class hidden id end id endspan id table colspan 4 id s1 id s2 id s3 id s4 id s5 id s6 id s7 id s8 id s9 id s10 id s11 id s12 id s13 id s14 id s15 id...