#include <iostream>#include <ctime>#include <deque>#include <utility>//类型pair#include <conio.h>#include <stdlib.h>using namespace std;const int n=10;pair<int ,int > food_ok;///食物的位置int a[n][n]={{9,9,9,9,9,9,9,9,9,9},{9,0,0,0,0,0,0,0,0,9},{9,0,0,0,0,0,0,0,0,9},{9,0,0,0,0,0,0,0,0,9},{9,0,0,0,0,0,0,0,0,9},{9,0,0,0,0,0,0,0,0,9},{9,0,0,0,0,0,0,0,0,9},{9,0,0,0,0,0,0,0,0,9},{9,0,0,0,0,0,0,0,0,9},{9,9,9,9,9,9,9,9,9,9}};void huatu();////画图class snakelei{public:void move(int x,int y);//移动void knock_wall_self(int x,int y);//撞墙或撞自身pair<int ,int> food();//食物int no_way(int x,int y);//不能移动的方向deque< pair<int ,int> > s;};void snakelei::move(int x,int y){ if(no_way(x,y))return;//选择了不能移动的方向则返回重来 int head_x=s[0].first + x; int head_y=s[0].second + y; knock_wall_self(head_x,head_y); if (head_x==food_ok.first && head_y==food_ok.second)//吃到食物 { s.push_front(food_ok); a[head_x][head_y]=2;////////////新头 a[head_x - x][head_y - y]=1;///旧头 //////////////////////调用food函数 food_ok=food(); a[food_ok.first][food_ok.second]=3; } else///////////////////////////////////没吃到食物仅仅是向前移动 { deque< pair<int ,int> >::iterator head=s.begin(),tail=s.end(),item; tail=tail-1; a[(*tail).first][(*tail).second]=0;///////原尾为0 for (item=tail;item!=head;--item)///////////////////这里错得好严重啊 { (*item).first=(*(item-1)).first; (*item).second=(*(item-1)).second;////既然要加括号???? } // a[s[0].first][s[0].second]=1;///////原头为1,,和下面一句的效果一样,因为此时s【0】==s【1】 a[s[1].first][s[1].second]=1;///////原头为1 s[0].first=s[0].first+x; s[0].second=s[0].second+y; a[s[0].first][s[0].second]=2;///////新头为2 }}void snakelei::knock_wall_self(int x,int y){//if (x==0||x==9||y==0||y==9) if (a[x][y]==9) { cout<<"撞墙了"<<endl; _sleep(300); exit(1); } if (a[x][y]==1) { cout<<"撞自身了"<<endl; _sleep(300); exit(1); }}pair<int ,int> snakelei::food(){int x,y;srand((unsigned int) time(NULL)); //做种子(程序运行时间); do{x= rand()%8+1; y= rand()%8+1; }while(a[x][y]==1 || a[x][y]==2);///食物必须出现在空位置 return make_pair(x,y);}int snakelei::no_way(int x,int y){ if (s[0].second==s[1].second ) { if (s[0].first<s[1].first && x==1 && y==0)return 1;//下 if (s[0].first>s[1].first && x==-1 && y==0)return 1; //上 } if (s[0].first==s[1].first ) { if (s[0].second<s[1].second && x==0 && y==1)return 1;//右 if (s[0].second>s[1].second && x==0 && y==-1)return 1;//左 } return 0;}int main(void){snakelei snake;snake.s.push_front(make_pair(2,1));snake.s.push_front(make_pair(1,1)); snake.s.push_front(make_pair(1,2));a[1][2]=2;a[1][1]=1;a[2][1]=1; int ch; food_ok=snake.food(); a[food_ok.first][food_ok.second]=3; do { huatu(); ch=getch(); switch(ch) { case 72: snake.move(-1,0);break; case 80: snake.move(1,0);break; case 75: snake.move(0,-1);break; case 77: snake.move(0,1);break; };system("cls"); }while(1); return 0;}void huatu(){ int i,j; for(i=0;i<n;i++) { for(j=0;j<n;j++) { switch (a[i][j]) {case 9:printf("■");break; case 0:printf(" ");break; case 1:printf("⊙");break;case 2:printf("㊣");break;case 3:printf("☆");break; default: printf("?");}} printf("\n"); } printf("\n\n按上下左右");}