#include <easyx.h> #include <conio.h> #include <list> using namespace std; int sx = 25; int sy = 25; int x; int y; char ch = 'd'; char score[12]; int m = (rand()%64)*10+5; int n = (rand()%46)*10+35; int length=3; list<char> lc; list<char>::iterator lci; int main() { initgraph(640,480); outtextxy(180, 200, "set of key: 'w':up 's':down 'a':left 'd':right"); outtextxy(200, 230, "press any key to start the game"); settextstyle(30,20,_T("微软雅黑")); outtextxy(150,150,"Greedy Snake 1.0"); getch(); settextstyle(20,10,_T("΢ÈíÑźÚ")); lc.push_back(ch); lc.push_back(ch); while(true) { //draw the snake fillcircle(sx,sy,5); x=sx; y=sy; for(int i=0; i<length-1 ;++i) { if(i==0) lci=--lc.end(); else --lci; switch(*lci) { case 'w': fillcircle(x,y+=10,5); break; case 'a': fillcircle(x+=10,y,5); break; case 's': fillcircle(x,y-=10,5); break; case 'd': fillcircle(x-=10,y,5); break; } } //draw random circle fillcircle(m,n,5); //detect keybord input if(kbhit()) ch=getch(); switch(ch) { case 'w': if(lc.back()!='s') sy-=10; else { ch='s'; sy+=10; } break; case 'a': if(lc.back()!='d') sx-=10; else { ch='d'; sx+=10; } break; case 's': if(lc.back()!='w') sy+=10; else { ch='w'; sy-=10; } break; case 'd': if(lc.back()!='a') sx+=10; else { ch='a'; sx-=10; } break; default: getch(); ch=lc.back(); break; } //put direction into the list lc.push_back(ch); //dectect collision if(sy<25 || sx<0 || sy>475 || sx>635) { settextstyle(50,30,_T("微软雅黑")); outtextxy(130,200,"GAME OVER"); break; } //detect eat or not if(sx==m&&sy==n) { length+=1; m = (rand()%64)*10+5; n = (rand()%47)*10+15; fillcircle(m,n,5); } else lc.pop_front(); //display the picture Sleep(100); cleardevice(); //draw the score sprintf(score,"score: %04d",length-3); outtextxy(270,0,score); line(0,20,640,20); } getch(); closegraph(); return 0; }