#include<bits/stdc++.h>
#include <conio.h>
#include <windows.h>
using namespace std;
const int WIDTH=40;
const int HEIGHT=20;
int snakeX[200];
int snakeY[200];
int snakeLen;
int foodX, foodY;
int dirX, dirY;
bool gameOver;
int score;
void InitGame(){
gameOver=false;
dirX=1;
dirY=0;
snakeLen=3;
score=0;
snakeX[0]=WIDTH/2;
snakeY[0]=HEIGHT/2;
snakeX[1]=WIDTH/2-1;
snakeY[1]=HEIGHT/2;
snakeX[2]=WIDTH/2-2;
snakeY[2]=HEIGHT/2;
foodX=rand()%(WIDTH-2)+1;
foodY=rand()%(HEIGHT-2)+1;
}
void Draw(){
system("cls");
for(int i=0;i<WIDTH+2;i++)
cout <<"#";
cout <<endl;
for(int y=0;y<HEIGHT;y++){
for(int x=0;x<WIDTH;x++){
if(x == 0)
cout <<"#";
bool printBody=false;
if(xsnakeX[0] && ysnakeY[0]){
cout <<"@";
printBody=true;
}
else{
for(int i = 1; i < snakeLen; i++){
if(snakeX[i] == x && snakeY[i] == y){
cout <<"*";
printBody=true;
break;
}
}
}
if(!printBody){
if(xfoodX && yfoodY)
cout <<"O";
else
cout << " ";
}
}
void Input(){
if(_kbhit()){
char ch=_getch();
if(ch=='a' && dirX!=1){
dirX=-1;
dirY=0;
}
else if(ch=='d' && dirX!=-1){
dirX=1;
dirY=0;
}
else if(ch=='w' && dirY!=1){
dirX=0;
dirY=-1;
}
else if(ch=='s' && dirY!=-1){
dirX=0;
dirY=1;
}
else if(ch=='x'){
gameOver=true;
}
}
}
void Logic(){
int prevX=snakeX[0];
int prevY=snakeY[0];
snakeX[0]+=dirX;
snakeY[0]+=dirY;
for(int i=1;i<snakeLen;i++){
int tempX=snakeX[i];
int tempY=snakeY[i];
snakeX[i]=prevX;
snakeY[i]=prevY;
prevX=tempX;
prevY=tempY;
}
if(snakeX[0]<=0 || snakeX[0]>=WIDTH-1 || snakeY[0]<=0 || snakeY[0]>=HEIGHT-1){
gameOver=true;
}
for(int i=1;i<snakeLen;i++){
if(snakeX[0]snakeX[i] && snakeY[0]snakeY[i]){
gameOver=true;
}
}
if(snakeX[0]foodX && snakeY[0]foodY){
score+=15;
snakeLen++;
bool foodOnSnake;
do{
foodOnSnake=false;
foodX=rand()%(WIDTH-2)+1;
foodY=rand()%(HEIGHT-2)+1;
for(int i=0;i<snakeLen;i++){
if(snakeX[i]foodX && snakeY[i]foodY){
foodOnSnake=true;
break;
}
}
}while(foodOnSnake);
}
}
int main(){
srand((unsigned)time(NULL));
InitGame();
while(!gameOver){
Draw();
Input();
Logic();
Sleep(90);
}
cout <<"\n游戏结束!===="<<endl;
cout <<"你的最终得分:"<<score<<endl;
return 0;
}