#include <iostream>
#include <vector>
#include <windows.h>
#include <conio.h>
#include <ctime>
using namespace std;
void gotoxy(int x, int y);
class Food
{
private:
int m_x;
int m_y;
public:
void randfood()
{
srand((int)time(NULL));
L1:
m_x = rand() % (85) + 2;
m_y = rand() % (25) + 2;
if (m_x % 2)
goto L1;
gotoxy(m_x, m_y);
cout << "★";
}
int getFoodm_x()
{
return m_x;
}
int getFoodm_y()
{
return m_y;
}
};
class Snake
{
private:
struct Snakecoor
{
int x;
int y;
};
vector<Snakecoor> snakecoor;
void degdir(Snakecoor& nexthead)
{
static char key = 'd';
if (_kbhit())
{
char temp = _getch();
switch (temp)
{
default:
break;
case 'w':
case 'a':
case 's':
case 'd':
if ((key == 'w' && temp != 's') || (key == 's' && temp != 'w') || \
(key == 'a' && temp != 'd') || (key == 'd' && temp != 'a'))
key = temp;
}
}
switch (key)
{
case 'd':
nexthead.x = snakecoor.front().x + 2;
nexthead.y = snakecoor.front().y;
break;
case 'a':
nexthead.x = snakecoor.front().x - 2;
nexthead.y = snakecoor.front().y;
break;
case 'w':
nexthead.x = snakecoor.front().x;
nexthead.y = snakecoor.front().y - 1;
break;
case 's':
nexthead.x = snakecoor.front().x;
nexthead.y = snakecoor.front().y + 1;
}
}
void finmatt(const int score)
{
system("cls");
gotoxy(40, 14);
cout <<
gotoxy(40, 16);
cout << "得分:" << score;
gotoxy(0, 26);
exit(0);
}
void finishgame(const int score)
{
if (snakecoor[0].x >= 88 || snakecoor[0].x < 0 || snakecoor[0].y >= 28 || snakecoor[0].y < 0)
finmatt(score);
for (int i = 1; i < snakecoor.size(); i++)
if (snakecoor[0].x == snakecoor[i].x && snakecoor[0].y == snakecoor[i].y)
finmatt(score);
}
public:
Snake()
{
Snakecoor temp;
for (int i = 5; i >= 0; i--)
{
temp.x = 16 + (i << 1);
temp.y = 8;
snakecoor.push_back(temp);
}
}
void move(Food& food, int& score)
{
Snakecoor nexthead;
degdir(nexthead);
snakecoor.insert(snakecoor.begin(), nexthead);
gotoxy(0, 0);
cout << "得分:" << score;
finishgame(score);
if (snakecoor[0].x == food.getFoodm_x() && snakecoor[0].y == food.getFoodm_y())
{
gotoxy(snakecoor[0].x, snakecoor[0].y);
cout << "●";
gotoxy(snakecoor[1].x, snakecoor[1].y);
cout << "■";
score++;
food.randfood();
return;
}
for (int i = 0; i < snakecoor.size(); i++)
{
gotoxy(snakecoor[i].x, snakecoor[i].y);
if (!i)
cout << "●";
else
cout << "■";
if (snakecoor[i].x == food.getFoodm_x() && snakecoor[i].y == food.getFoodm_y())
food.randfood();
}
gotoxy(snakecoor.back().x, snakecoor.back().y);
cout << " ";
snakecoor.pop_back();
}
};
void HideCursor()
{
CONSOLE_CURSOR_INFO cursor_info = { 1, 0 };
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
void gotoxy(int x, int y)
{
COORD pos = { x,y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
int main()
{
system("mode con cols=88 lines=28");
system("title C++ 贪吃蛇");
HideCursor();
int score = 0;
Food food;
food.randfood();
Snake snake;
while (true)
{
snake.move(food, score);
Sleep(150);
}
return 0;
}
c++小游戏 贪吃蛇
于 2023-08-12 19:45:42 首次发布