贪食蛇

#include<bits/stdc++.h>
#include<conio.h>
using namespace std;
#define ms(a) memset(a,0,sizeof a)

const int maxn=1e2;
int grid[maxn][maxn];
char chain[maxn][maxn];
int N,M,cnt;
pair<int,int> head,tail,food;
map<char,pair<int,int> > direction;
map<pair<int,int>,char> inv_direction;

void init()
{
    srand((unsigned)time(NULL));
    ms(grid);
    ms(chain);
    cnt=1;
    direction['a']=make_pair(0,-1);
    direction['d']=make_pair(0,1);
    direction['w']=make_pair(-1,0);
    direction['s']=make_pair(1,0);
    inv_direction[make_pair(0,-1)]='a';
    inv_direction[make_pair(0,1)]='d';
    inv_direction[make_pair(-1,0)]='w';
    inv_direction[make_pair(1,0)]='s';
    head=tail=make_pair(rand()%N+1,rand()%M+1);
    food=make_pair(rand()%N+1,rand()%M+1);
    grid[head.first][head.second]=1;
}
bool judge(int x,int y)
{
    if(x<1||x>N||y<1||y>M)return false;
    return grid[x][y]==0;
}
char c='w',cc='w';
bool Move(char ch)
{
    pair<int,int> dir=direction[ch];
    //head
    int x,y;
    x=head.first+dir.first;
    y=head.second+dir.second;
    if(!judge(x,y))
    {
        if(x>=1&&x<=N&&y>=1&&y<=M)
        {
            char tmp=chain[x][y];
            if(direction[tmp].first+dir.first==0&&direction[tmp].second+dir.second==0)
            {
                c=cc;
                Move(c);
                return true;
            }
        }
        return false;
    }
    cc=c;
    grid[x][y]=1;
    chain[head.first][head.second]=inv_direction[dir];
    head=make_pair(x,y);
    //tail
    if(x==food.first&&y==food.second)
    {
        food=make_pair(rand()%N+1,rand()%M+1);
        cnt++;
        return true;
    }
    x=tail.first,y=tail.second;
    dir=direction[chain[x][y]];
    tail=make_pair(x+dir.first,y+dir.second);
    grid[x][y]=0;
    chain[x][y]=0;
    return true;
}
void Print()
{
    system("cls");
    for(int i=1;i<=M+2;++i)printf("X");printf("\n");
    for(int i=1;i<=N;++i)
    {
        printf("X");
        for(int j=1;j<=M;++j)
        {
            if(i==food.first&&j==food.second)printf("*");
            else if(grid[i][j])printf("O");
            else printf(" ");
        }
        printf("X\n");
    }
    for(int i=1;i<=M+2;++i)printf("X");printf("\n");
}
int main()
{
    printf("(N,M)=");
    scanf("%d%d",&N,&M);
    init();
    Print();

    while(1)
    {
        int tmp=500-cnt*10;
        tmp=max(tmp,50);
        _sleep(tmp);
        if(kbhit())c=getch();
        if(c!='a'&&c!='s'&&c!='d'&&c!='w')continue;
        if(!Move(c))
        {
            printf("You lose, LOSER!\n");
            break;
        }
        Print();
    }
    main();
}

猜你喜欢

转载自www.cnblogs.com/maoruimas/p/9962671.html