#include<bits/stdc++.h>
#include <conio.h>
#include <windows.h>
using namespace std;
void gotoxy(int x,int y) //将输出位置改到 y行x列
{
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
HANDLE hConsoleOut;
hConsoleOut = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hConsoleOut,&csbiInfo);
csbiInfo.dwCursorPosition.X = x;
csbiInfo.dwCursorPosition.Y = y;
SetConsoleCursorPosition(hConsoleOut,csbiInfo.dwCursorPosition);
}
pair<int,int> operator + (pair<int,int> a,pair<int,int> b)
{
return make_pair(a.first+b.first,a.second+b.second);
}
struct _
{
vector<pair<int,int>> v; //蛇身坐标
pair<int,int> p,food,cur;//方向,食物,当前方向坐标
int len,dif = 100; //长度,刷新速度
void init() //初始化
{
p = make_pair(1,0);
v.clear();
for(int i = 2; i >= 0; i--)
v.push_back(make_pair(i,0));
L1:int x = rand()%80, y = rand()%20;
food = make_pair(x,y);
if(find(v.begin(),v.end(),food)!=v.end()) goto L1;
}
void print() //将蛇身,食物输入到屏幕
{
gotoxy(v[0].first,v[0].second);
putchar('@');
for(int i = 1; i < (int)v.size(); i++){
gotoxy(v[i].first,v[i].second);
putchar('O');
}
gotoxy(food.first,food.second);
putchar('#');
getkey();
}
void getkey() // 输入方向
{
long long t = clock();
cur = p;
while(clock()-t < dif){
if(_kbhit()) pd(_getch());
}
Move();
system("cls");
print();
}
void Move() // 移动
{
pair<int,int> t = v[0];
v[0] = v[0]+p;
v[0].first = (v[0].first+80)%80;v[0].second = (v[0].second+20)%20;
if(find(v.begin()+1,v.end(),v[0]) != v.end()){
gotoxy(32,10);puts("Game Over");
gotoxy(30,11);puts("1、按 ESC 退出");
gotoxy(30,12);puts("2、按任意键复活");
if(_getch() == 27) exit(0);
else {
init();
print();
}
}
if(v[0] == food) {
v.resize(v.size()+5);
L1:int x = rand()%80, y = rand()%20;
food = make_pair(x,y);
if(find(v.begin(),v.end(),food)!=v.end()) goto L1;
}
for(int i = 1; i < (int)v.size(); i++){
pair<int,int> tmp = v[i];
v[i] = t;
t = tmp;
}
}
bool pd(int t) // 判断方向是否与当前方向相反
{
pair<int,int> x;
if(t == 77) x = make_pair(-1,0);
if(t == 75) x = make_pair(1,0);
if(t == 72) x = make_pair(0,1);
if(t == 80) x = make_pair(0,-1);
if(cur != x){
if(t == 77) p = make_pair(1,0);
if(t == 75) p = make_pair(-1,0);
if(t == 72) p = make_pair(0,-1);
if(t == 80) p =make_pair(0,1);
return true;
}
return false;
}
}tcs;
int main()
{
system("mode con: cols=80 lines=20");
system("title 贪吃蛇");
gotoxy(30,10);puts("按任意键开始...");_getch();
tcs.init();
tcs.print();
return 0;
}
贪吃蛇 C++
最新推荐文章于 2025-04-18 22:40:30 发布