我去 好不容易写了个贪吃蛇 将就看吧
#include<bits/stdc++.h>
#include<conio.h>
using namespace std;
//-|表示墙,@表示蛇,?表示食物,空格表示空地
const int H=21,L=41;
int sx=10,sy=20,fx,fy,score=0;
queue<pair<int,int> > snack;
//定义地图
char m[H][L];
// 函数声明;
void gen_food();
void SetTextColor(int color) {
const char* esc_seq_color[] = { "\033[30m", // Black
"\033[31m", // Red
"\033[32m", // Green
"\033[33m", // Yellow
"\033[34m", // Blue
"\033[35m", // Magenta
"\033[36m", // Cyan
"\033[37m", // White
"\033[38m" // Gray
};
if (color >= 0 && color <= 8) {
std::cout << esc_seq_color[color];
}
}
void init_m(){
//初始化地图
for(int i=0;i<H;i++){
for(int j=0;j<L;j++){
m[i][j]=' ';
}
}
for(int i=0;i<L;i++){
m[0][i]='-';
m[H-1][i]='-';
}
for(int i=0;i<H;i++){
m[i][0]='|';
m[i][L-1]='|';
}
//渲染蛇头
m[sx][sy]='@';
m[sx][sy-1]='@';
m[sx][sy-2]='@';
snack.push({sx,sy-2});
snack.push({sx,sy-1});
snack.push({sx,sy});
//渲染食物
gen_food();
}
string my_to_string(int n){
string s="";
if(n==0){
s+='0';
}
while(n>0){
s+=(n%10)+'0';
n/=10;
}
reverse(s.begin(),s.end());
return s;
}
void print_m(){
system("cls");
// string s="";
// for(int i=0;i<H;i++){
// for(int j=0;j<L;j++){
// s+=m[i][j];
// }
// if(i==0){
// s+=" 分数:"+my_to_string(score)+" 分";
// }
// s+="\n";
// }
// cout<<s;
for(int i=0;i<H;i++){
for(int j=0;j<L;j++){
if(m[i][j]=='?'){
SetTextColor(6);
cout<<m[i][j];
SetTextColor(7);
}else if(m[i][j]=='@'){
if(i==sx&&j==sy){
SetTextColor(1);
cout<<m[i][j];
SetTextColor(7);
}else{
SetTextColor(3);
cout<<m[i][j];
SetTextColor(7);
}
}else{
cout<<m[i][j];
}
}
if(i==0){
cout<<" 分数:"+my_to_string(score)+" 分\n";
continue;
}
cout<<"\n";
}
}
void gen_food(){
//x:1-19,y:1-39
int fxt=rand()%(H-2)+1,fyt=rand()%(L-2)+1;
while(fxt==sx&&fyt==sy){
fxt=rand()%(H-2)+1,fyt=rand()%(L-2)+1;
}
fx=fxt;fy=fyt;
//保存并绘制
m[fx][fy]='?';
print_m();
}
bool is_end(){
//撞墙没有
if(sx==0||sx==H-1||sy==0||sy==L-1){
return 1;
}else{
return 0;
}
//撞到自己没有
}
int main(){
//设置随机数种子
srand(time(NULL));
init_m();
print_m();
char c;
//cin>>c;
bool food_exist=1;//1:存在,0:不存在
int f=0;//默认没有方向
while(1){
if(food_exist==0){
gen_food();
food_exist=1;
print_m();
}
c=_getch();
//m[sx][sy]=' ';
if(c=='w'){
if(f==3){
continue;
}
sx-=1;
f=1;
}else if(c=='a'){
if(f==4){
continue;
}
sy-=1;
f=2;
}else if(c=='s'){
if(f==1){
continue;
}
sx+=1;
f=3;
}else if(c=='d'){
if(f==2){
continue;
}
sy+=1;
f=4;
}else{
continue;
}
//m[sx][sy]='@';
snack.push({sx,sy});
m[sx][sy]='@';
if(sx==fx&&sy==fy){
food_exist=0;
score+=5;
continue;
}
pair<int,int> snack_back=snack.front();
m[snack_back.first][snack_back.second]=' ';
snack.pop();
print_m();
if(is_end()){
cout<<"游戏结束!";
break;
}
}
return 0;
}
可以直接复制粘贴
最后 点个赞再走吧!