这款游戏前段时间很火。前几天早上的课太无聊了,所以我决定自己写这个游戏。写了一个多小时,300行左右,没有什么复杂的算法,但是懒得优化,不过估计优化可以控制在200行以下,有兴趣的朋友可以自己优化。说明:我一开始玩的是IOSAPP版的TRHEES,后来玩的是2048,两者的滑动规则有些差异。我的版本是两者的结合。***,祝您试用愉快!界面很丑,请不要笑。以下是源码:/*ByReason*/#include#include#include#include#include#include//为了读取方向键#includeusingnamespacestd;//srand((unsigned)time(NULL));//这里不能使用随机数种子intpane[4][4];//棋盘intN=1;//2的n次方voidshowpane()//显示棋盘{cout<N)N=n;返回标志;}}返回标志;}intupmove()//上移{intflag=0;for(intj=0;j<=3;j++)for(inti=0;i<3;i++){if(if2n(pane[i][j]+pane[i+1][j])==1){pane[i][j]=pane[i][j]+pane[i+1][j];窗格[i+1][j]=0;标志=1;}}返回标志;}intdownmove()//下移{intflag=0;for(intj=0;j<=3;j++)for(inti=3;i>0;i--){if(if2n(pane[i][j]+pane[i-1][j])==1){pane[i][j]=pane[i][j]+pane[i-1][j];窗格[i-1][j]=0;标志=1;}}返回标志;}intleftmove()//左移{intflag=0;for(inti=0;i<=3;i++)for(intj=0;j<3;j++){if(if2n(pane[i][j]+pane[i][j+1])==1){窗格[i][j]=窗格[i][j]+窗格[i][j+1];窗格[i][j+1]=0;标志=1;}}返回标志;}intrightmove()//右移{intflag=0;for(inti=0;i<=3;i++)for(intj=3;j>0;j--){if(if2n(pane[i][j]+pane[i][j-1])==1){窗格[i][j]=窗格[i][j]+窗格[i][j-1];窗格[i][j-1]=0;旗帜=1;}}返回标志;}inttestup()//可以向上移动测试{intflag=0;for(intj=0;j<=3;j++)for(inti=0;i<3;i++){if(if2n(pane[i][j]+pane[i+1][j])==1){标志=1;}}返回标志;}inttestdown()//测试是否向下移动{intflag=0;for(intj=0;j<=3;j++)for(inti=3;i>0;i--){if(if2n(pane[i][j]+pane[i-1][j])==1){标志=1;}}返回标志;}inttestleft()//测试是否向左移动{intflag=0;for(inti=0;i<=3;i++)for(intj=0;j<3;j++){if(if2n(pane[i][j]+pane[i][j+1])==1){标志=1;}}返回标志;}inttestright()//测试是否右移{intflag=0;for(inti=0;i<=3;i++)for(intj=3;j>0;j--){if(if2n(pane[i][j]+pane[i][j-1])==1){标志=1;}}返回标志;}intpanemax()//棋盘格数{intmax=pane[0][0];for(inti=0;i<=3;i++)for(intj=0;j<=3;j++)if(pane[i][j]>max)max=pane[i][j];返回最大值;}intifwin()//判断是否获胜{intflag=0;如果(panemax()==2048){cout<=0;i--)for(intj=0;j<=3;j++)if(pane[i][j]==0){pane[i][j]=新号码;返回;}}voidaddnewnumberdown()//下移后增加新数{srand((unsigned)time(NULL));国际;如果(N==1)n=1;elsen=(rand()%(N)+1);intnewnumber=pow(2,n);for(inti=0;i<=3;i++)for(intj=0;j<=3;j++)if(pane[i][j]==0){pane[i][j]=newnumber;返回;}}voidaddnewnumberleft()//左移后添加新数{srand((unsigned)time(NULL));国际;如果(N==1)n=1;否则=(兰德()%(N)+1);intnewnumber=pow(2,n);for(intj=3;j>=0;j--)for(inti=0;i<=3;i++)if(pane[i][j]==0){pane[i][j]=新号码;返回;}}voidaddnewnumberright()//右移后添加新数{srand((unsigned)time(NULL));国际;如果(N==1)n=1;其他=(rand()%(N)+1);intnewnumber=pow(2,n);for(intj=0;j<=3;j++)for(inti=0;i<=3;i++)if(pane[i][j]==0){pane[i][j]=newnumber;返回;}}intGetDirection()//读取方向{intret=0;做{intch=_getch();如果(isascii(ch))继续;ch=_getch();switch(ch){case72:ret=2;//顶部中断;case75:ret=1;//左中断;case77:ret=3;//右中断;case80:ret=4;//向下突破;默认值:中断;}}while(ret==0);返回;}voidmain()//主函数{system("colorf9");intmakesure=1;同时(确保){系统(“cls”);新游戏();while(ifwin()+ifGameOver()==0){intc=GetDirection();switch(c){case2:upmove();添加新数字();系统(“cls”);显示窗格();休息;case4:向下移动();添加新数字向下();系统(“cls”);显示窗格();休息;case1:左移();添加新数字左();系统(“cls”);显示窗格();休息;case3:右移();addnewnumberright();系统(“cls”);显示窗格();休息;默认值:中断;}}输出<<设置w(43)<<"你的***结果是:"<>确定;while(makesure!=1&&makesure!=0){cout<<"输入错误,请重新输入!"<>确定;}}cout<<"再见!"<