贪吃蛇c++ 乱写的

来源:互联网 发布:上海知金教育 编辑:程序博客网 时间:2024/05/20 04:11
#include<iostream>#include<conio.h>#include<windows.h>#include<ctime>#include<stdlib.h>using namespace std;struct node{    int x,y;    struct node *next;};int cnt,fx,fy;// 蛇长node *tou,*wei;//头、尾指针char dir;void gotoXY(short x, short y){    COORD pos = {x,y};    HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);    SetConsoleCursorPosition(out,pos);}void creatfood(){    srand((unsigned)time(0));    fx=rand()%36;    if(fx%2==0)        fx+=2;    else        fx++;    fy=rand()%18;    fy++;    gotoXY(fx,fy);    cout<<"卍";}void fang(){    gotoXY(5,20);    char t;    while(kbhit())    {        t=getch();        if(t=='w'||t=='W')            if(dir!='s') dir='w';        if(t=='a'||t=='A')            if(dir!='d') dir='a';        if(t=='s'||t=='S')            if(dir!='w') dir='s';        if(t=='d'||t=='D')            if(dir!='a') dir='d';    }}void init(){    system("cls");    dir='s';    cnt=3;    node* p;    tou=p=(node*)malloc(sizeof(node));    p->x=4;    p->y=1;    p->next=(node*)malloc(sizeof(node));    p=p->next;    p->x=4;    p->y=2;    p->next=(node*)malloc(sizeof(node));    p=p->next;    p->x=4;    p->y=3;    p->next=NULL;    wei=p;    int i;    for(i=0; i<40; i+=2)    {        gotoXY(i,0);        cout<<"■";        gotoXY(i,19);        cout<<"■";    }    for(i=0; i<20; i++)    {        gotoXY(0,i);        cout<<"■";        gotoXY(38,i);        cout<<"■";    }    gotoXY(46,5);    cout<<"按a,w,s,d移动,仅供学习之用!";    creatfood();    gotoXY(46,6);    cout<<"蛇长:"<<cnt;}void move(){    node *p;    int x,y;    if(dir=='w')    {        x=wei->x;        y=wei->y-1;    }    if(dir=='s')    {        x=wei->x;        y=wei->y+1;    }    if(dir=='a')    {        x=wei->x-2;        y=wei->y;    }    if(dir=='d')    {        x=wei->x+2;        y=wei->y;    }    gotoXY(x,y);    cout<<"★";    if(wei->x==fx&&wei->y==fy)    {        cnt++;        gotoXY(46,6);        cout<<"蛇长:"<<cnt;        creatfood();        p=(node*)malloc(sizeof(node));        p->x=x;        p->y=y;        wei->next=p;        wei=p;        wei->next=NULL;    }    else    {        if(tou->x!=fx||tou->y!=fy)        {            gotoXY(tou->x,tou->y);            cout<<"  ";        }        tou->x=x;        tou->y=y;        wei->next=tou;        tou=tou->next;        wei=wei->next;        wei->next=NULL;    }    if(wei->x>=38||wei->y>=19||wei->y<=0||wei->x<=0)    {        MessageBox(NULL,"你挂了,游戏重新开始","糟糕!",MB_OK);        init();        return;    }    p=tou;    while(p->next)    {        if(wei->x==p->x&&wei->y==p->y)        {            MessageBox(NULL,"你挂了,游戏重新开始","糟糕!",MB_OK);            init();            return;        }        p=p->next;    }}void game(){    init();    while(1)    {        Sleep(200);        fang();        move();    }}int main(){    system("color 12");    game();}

1 0