一个简单的翻牌游戏
如截图所示,输入一对数组元素下标,如果此对数组元素相等,则翻牌成功,显示数据
11.05,改版做了一个对话框应用,如下,基本思想与控制台程序一致
#include <iostream> #include <ctime> using namespace std; class Game { public: void initial(); void start(); void print(); void printall(); void getPairNum(); private: int game[4][4];//保存随机生成的16个数字 bool checked[4][4];//标记该元素是否已经配对 int pair;//记录生成的数组中相同元素的对数,以判断是否结束 bool end;//结束标志 int temp[16];//将生成的二维数组以保存至临时一维数组中,以判断二维数组中有多少对相同元素 int tag[16];//对于已经进行查找的元素值,设置标记位,防止重复计算相同元素个数 }; void Game::initial() { srand(time(NULL)); int k=0; for (int i=0;i<4;i++) { for (int j=0;j<4;j++,k++) { game[i][j]=rand()%8; temp[k]=game[i][j]; } } for (int i=0;i<16;i++) { tag[i]=0; } for (int i=0;i<4;i++) { for (int j=0;j<4;j++) { checked[i][j]=false; } } end=false; } void Game::getPairNum() { pair=0; int count=0; for (int i=0;i<16;i++) { count=1; if (tag[temp[i]]==0) { for (int j=i+1;j<16;j++) { if (temp[i]==temp[j]) { count++; tag[temp[i]]=1;//若此元素已进行配对,则设标记为1 } } } pair+=count/2;//统计得到的个数模2即为对数 } } void Game::start() { getPairNum(); //printall(); //system("pause"); int count=0; while(!end) { system("cls"); print(); cout<<"please input which you want to click"<<endl; int a,b,c,d; cin>>a>>b>>c>>d; if (((a==c)&&(b==d))||a>3||b>3||c>3||d>3) { cout<<"error input!"<<endl; system("pause"); } else { checked[a][b]=true; checked[c][d]=true; system("cls"); print(); system("pause"); cout<<endl; if (game[a][b]!=game[c][d]) { checked[a][b]=false; checked[c][d]=false; } else count++; if (count==pair) { end=true; } } } cout<<"congratulations!"<<endl; system("pause"); printall(); system("pause"); } void Game::printall() { system("cls"); for (int i=0;i<4;i++) { for (int j=0;j<4;j++) { cout<<game[i][j]<<"\t"; } cout<<endl; } } void Game::print() { for (int i=0;i<4;i++) { for (int j=0;j<4;j++) { if (checked[i][j]==true) { cout<<game[i][j]<<"\t"; } else { cout<<"*"<<"\t"; } } cout<<endl; } } int main() { Game game; game.initial(); game.start(); return 0; }