#include<iostream>
#include<windows.h>
#include<conio.h>
#include<deque>
#include<ctime>
#include<stdexcept>
usingnamespacestd;
structSnake{//蛇类结构体
charimage;
shortx,y;//坐标
};
classsnakeGame{
public:
snakeGame();
voidprintMap();
//控制光标移动
voidgotoxy(shortx,shorty){
hOut=GetStdHandle(STD_OUTPUT_HANDLE);//获取句柄
pos={x,y};
SetConsoleCursorPosition(hOut,pos);//移动光标
}
//隐藏光标
voidHideCursor()
{
HANDLEhandle=GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFOCursorInfo;
GetConsoleCursorInfo(handle,&CursorInfo);//获取控制台光标信息
网页链接=false;//隐藏控制台光标
SetConsoleCursorInfo(handle,&CursorInfo);//设置控制台光标状态
}
//初始化蛇身,可根据需要更改初始长度
voidinitSnake(){
snake.push_front({'@',width/2,height/2});
for(inti=0;i<2;++i)
snake.push_back({'+',width/2,static_cast<short>(height/2+i+1)});
}
//判断是否食物产生位置与蛇身冲突
intWrongLocation(){
for(Snakebody:snake)
if(body.x==food_x&&body.y==food_y)return0;
return1;
}
//产生食物,并打印
voidcreateFood(){
do{
food_x=rand()%(width-4)+2;
food_y=rand()%(height-2)+1;
}while(!WrongLocation());//处理冲突
gotoxy(food_x,food_y);cout<<'*'<<endl;//打印食物
}
voidprintSnake();
//清除蛇尾
inlinevoidclearSnake(Snake&tail){
gotoxy(tail.x,tail.y);cout<<'';//覆盖蛇尾,不使用清屏函数,避免了闪烁
}
voidjudgeCrash();
voidfoodEaten();
//监控用户键盘输入
voiduserInput(){
charch;
switch(ch=getch()){
case'w':if(dir!='s')dir=ch;break;
case'a':if(dir!='d')dir=ch;break;
case's':if(dir!='w')dir=ch;break;
case'd':if(dir!='a')dir=ch;break;
case'v':speed*=0.8;break;case'b':speed*=1.5;break;
case'':gotoxy(width/2,heig
#include<windows.h>
#include<conio.h>
#include<deque>
#include<ctime>
#include<stdexcept>
usingnamespacestd;
structSnake{//蛇类结构体
charimage;
shortx,y;//坐标
};
classsnakeGame{
public:
snakeGame();
voidprintMap();
//控制光标移动
voidgotoxy(shortx,shorty){
hOut=GetStdHandle(STD_OUTPUT_HANDLE);//获取句柄
pos={x,y};
SetConsoleCursorPosition(hOut,pos);//移动光标
}
//隐藏光标
voidHideCursor()
{
HANDLEhandle=GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFOCursorInfo;
GetConsoleCursorInfo(handle,&CursorInfo);//获取控制台光标信息
网页链接=false;//隐藏控制台光标
SetConsoleCursorInfo(handle,&CursorInfo);//设置控制台光标状态
}
//初始化蛇身,可根据需要更改初始长度
voidinitSnake(){
snake.push_front({'@',width/2,height/2});
for(inti=0;i<2;++i)
snake.push_back({'+',width/2,static_cast<short>(height/2+i+1)});
}
//判断是否食物产生位置与蛇身冲突
intWrongLocation(){
for(Snakebody:snake)
if(body.x==food_x&&body.y==food_y)return0;
return1;
}
//产生食物,并打印
voidcreateFood(){
do{
food_x=rand()%(width-4)+2;
food_y=rand()%(height-2)+1;
}while(!WrongLocation());//处理冲突
gotoxy(food_x,food_y);cout<<'*'<<endl;//打印食物
}
voidprintSnake();
//清除蛇尾
inlinevoidclearSnake(Snake&tail){
gotoxy(tail.x,tail.y);cout<<'';//覆盖蛇尾,不使用清屏函数,避免了闪烁
}
voidjudgeCrash();
voidfoodEaten();
//监控用户键盘输入
voiduserInput(){
charch;
switch(ch=getch()){
case'w':if(dir!='s')dir=ch;break;
case'a':if(dir!='d')dir=ch;break;
case's':if(dir!='w')dir=ch;break;
case'd':if(dir!='a')dir=ch;break;
case'v':speed*=0.8;break;case'b':speed*=1.5;break;
case'':gotoxy(width/2,heig