#include<bits/stdc++.h>
#include<windows.h>
#include<conio.h>
using namespace std;
const int n=10;
double t=20000;
struct node{
int x,y;
}head={n/2,n/2},apple;
list<node>body;
int mab[n+5][n+5];//0空1身体2头3苹果
char dir='d';
void set_color(int c){
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),c);
}
void gotoxy(int x,int y){
COORD pos;
pos.X=x;
pos.Y=y;
HANDLE handle=GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(handle,pos);
}
void out(){
gotoxy(0,0);
for(int i=0;i<=n+1;i++){
for(int j=0;j<=n+1;j++){
if(i==0||j==0||i==n+1||j==n+1){
set_color(6);
cout<<"■";
}
else if(mab[i][j]==1){
set_color(10);
cout<<"□";
}
else if(mab[i][j]==2){
set_color(10);
cout<<"■";
}
else if(mab[i][j]==3){
set_color(12);
cout<<"●";
}
else{
cout<<" ";
}
cout<<" ";
}
cout<<"\n";
}
cout<<"目前得分:"<<body.size()+1;
}
int main(){
system("title 贪吃蛇---游戏说明");
CONSOLE_CURSOR_INFO curInfo;
curInfo.dwSize=1;
curInfo.bVisible=FALSE;
HANDLE handle=GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorInfo(handle,&curInfo);
srand(time(0));
apple.x=rand()%(n-2)+2;
apple.y=rand()%(n-2)+2;
mab[apple.x][apple.y]=3;
cout<<"游戏说明:\n";
cout<<"①、按“w,a,s,d”或“↑ ↓ ← →”移动蛇身体\n";
cout<<"②、蛇头碰到●蛇的长度加大\n";
cout<<"③、如果你不按键盘,蛇将会以上一按键的移动方向移动(默认是往右走)\n";
cout<<"④、碰到边缘会结束游戏\n";
cout<<"⑤、碰到自己会结束游戏\n";
cout<<"⑥、按空格键暂停游戏,按任意键继续\n";
cout<<"⑦、没有 7 了\n";
cout<<"请按任意键开始游戏···";
getch();
system("cls");
system("title 贪吃蛇");
while(1){
memset(mab,0,sizeof(mab));
mab[apple.x][apple.y]=3;
for(int i=0;i<(int)body.size();i++){
mab[body.front().x][body.front().y]=1;
body.push_back(body.front());
body.pop_front();
}
mab[head.x][head.y]=2;
out();
for(int i=1;i<=t;i++){
if(_kbhit()!=0){
char x=getch();
if(x=='w'||x=='W'||x==72||x=='a'||x=='A'||x==75||x=='s'||x=='S'||x==80||x=='d'||x=='D'||x==77||x==' '){
dir=x;
break;
}
}
}
body.push_front(head);
switch(dir){
case 'w':
case 'W':
case 72:
head.x--;
break;
case 'a':
case 'A':
case 75:
head.y--;
break;
case 's':
case 'S':
case 80:
head.x++;
break;
case 'd':
case 'D':
case 77:
head.y++;
break;
case ' ':
getch();
break;
}
if(mab[head.x][head.y]==3){
srand(time(0));
while((apple.x==head.x&&apple.y==head.y)||mab[apple.x][apple.y]!=0){
apple.x=rand()%(n-2)+2;
apple.y=rand()%(n-2)+2;
}
body.push_back(body.back());
// t*=0.9;
}
body.pop_back();
if(head.x==0||head.y==0||head.x==n+1||head.y==n+1){
MessageBox(NULL,TEXT("碰到了墙壁"),TEXT("You Lose"),MB_OK);
break;
}
if(mab[head.x][head.y]==1){
MessageBox(NULL,TEXT("你咬到了自己"),TEXT("You Lose"),MB_OK);
break;
}
}
set_color(15);
system("cls");
freopen("coin.txt","r",stdin);
int x;
cin>>x;
cout<<"历史最高分:"<<x;
if(body.size()+1>x){
cout<<",恭喜你,突破了最高分!";
freopen("coin.txt","w",stdout);
cout<<body.size()+1;
}
return 0;
}