2048
Posted maoruimas
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2048相关的知识,希望对你有一定的参考价值。
#include<bits/stdc++.h>
#include<conio.h>
using namespace std;
const int maxn=1e2;
int grid[maxn][maxn];
int N,M;
vector<pair<int,int> > rec;
void init()
{
srand((unsigned)time(NULL));
memset(grid,0,sizeof grid);
for(int i=1;i<=N;++i)
{
for(int j=1;j<=M;++j)rec.push_back(make_pair(i,j));
}
}
void print()
{
for(int i=1;i<=N;++i)
{
for(int j=1;j<=M;++j)
{
if(grid[i][j]==0)printf(" ");
else printf("%4d ",grid[i][j]);
}
printf("
");
}
}
void left()
{
for(int i=1;i<=N;++i)
{
int pos=1,tmp=0;
for(int j=1;j<=M;++j)
{
if(grid[i][j]==0)continue;
int get=grid[i][j];
grid[i][j]=0;
if(get==tmp)
{
grid[i][pos-1]*=2;
tmp=0;
}
else
{
grid[i][pos++]=get;
tmp=get;
}
}
}
}
void right()
{
for(int i=1;i<=N;++i)
{
int pos=M,tmp=0;
for(int j=M;j>=1;--j)
{
if(grid[i][j]==0)continue;
int get=grid[i][j];
grid[i][j]=0;
if(get==tmp)
{
grid[i][pos+1]*=2;
tmp=0;
}
else
{
grid[i][pos--]=get;
tmp=get;
}
}
}
}
void up()
{
for(int i=1;i<=M;++i)
{
int pos=1,tmp=0;
for(int j=1;j<=N;++j)
{
if(grid[j][i]==0)continue;
int get=grid[j][i];
grid[j][i]=0;
if(get==tmp)
{
grid[pos-1][i]*=2;
tmp=0;
}
else
{
grid[pos++][i]=get;
tmp=get;
}
}
}
}
void down()
{
for(int i=1;i<=M;++i)
{
int pos=N,tmp=0;
for(int j=N;j>=1;--j)
{
if(grid[j][i]==0)continue;
int get=grid[j][i];
grid[j][i]=0;
if(get==tmp)
{
grid[pos+1][i]*=2;
tmp=0;
}
else
{
grid[pos--][i]=get;
tmp=get;
}
}
}
}
bool push()
{
int sz=rec.size();
if(sz==0)return false;
int a;
a=rand()%sz;
grid[rec[a].first][rec[a].second]=(rand()%10)>7?4:2;
return true;
}
int main()
{
system("cls");
printf("N = ");
scanf("%d",&N);
printf("M = ");
scanf("%d",&M);
init();
char ch=0;
do{
if(ch==‘a‘)left();
else if(ch==‘d‘)right();
else if(ch==‘w‘)up();
else if(ch==‘s‘)down();
else if(ch!=0)continue;
rec.clear();
for(int i=1;i<=N;++i)
{
for(int j=1;j<=M;++j)
{
if(grid[i][j]==0)rec.push_back(make_pair(i,j));
}
}
system("cls");
if(!push())
{
printf("Game Over
");
break;
}
print();
}while((ch=getch()));
printf("Try again ? y/n
");
//getch();
ch=getch();
if(ch==‘y‘)main();
else return 0;
}
以上是关于2048的主要内容,如果未能解决你的问题,请参考以下文章