用C++写一个有颜色的贪吃蛇
时间: 2023-12-27 10:46:09 浏览: 40
好的,下面是一个简单的贪吃蛇游戏,用C++实现,并且包含了颜色。
```c++
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
const int width = 20; // 游戏区宽度
const int height = 20; // 游戏区高度
int x, y; // 蛇头坐标
int fruitX, fruitY; // 水果坐标
int score; // 得分
int tailX[100], tailY[100]; // 记录蛇身坐标
int nTail; // 蛇身长度
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN }; // 方向枚举
eDirection dir; // 当前方向
void Setup()
{
dir = STOP; // 初始方向为停止
x = width / 2; // 初始坐标为中心点
y = height / 2;
fruitX = rand() % width; // 随机生成水果坐标
fruitY = rand() % height;
score = 0;
}
void Draw()
{
system("cls"); // 清空屏幕
for (int i = 0; i < width + 2; i++)
cout << "#"; // 上边界
cout << endl;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
if (j == 0)
cout << "#"; // 左边界
if (i == y && j == x)
cout << "O"; // 蛇头
else if (i == fruitY && j == fruitX)
cout << "F"; // 水果
else
{
bool print = false;
for (int k = 0; k < nTail; k++) // 蛇身
{
if (tailX[k] == j && tailY[k] == i)
{
cout << "o";
print = true;
}
}
if (!print)
cout << " ";
}
if (j == width - 1)
cout << "#"; // 右边界
}
cout << endl;
}
for (int i = 0; i < width + 2; i++)
cout << "#"; // 下边界
cout << endl;
cout << "Score:" << score << endl; // 显示得分
}
void Input()
{
if (_kbhit()) // 判断是否有输入
{
switch (_getch()) // 获取输入键位
{
case 'a':
dir = LEFT;
break;
case 'd':
dir = RIGHT;
break;
case 'w':
dir = UP;
break;
case 's':
dir = DOWN;
break;
case 'x': // 退出游戏
exit(0);
break;
}
}
}
void Logic()
{
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x;
tailY[0] = y;
for (int i = 1; i < nTail; i++) // 更新蛇身坐标
{
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (dir) // 根据方向移动蛇头坐标
{
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
}
if (x >= width) // 判断蛇是否越界
x = 0;
else if (x < 0)
x = width - 1;
if (y >= height)
y = 0;
else if (y < 0)
y = height - 1;
for (int i = 0; i < nTail; i++) // 判断蛇是否吃到自己
{
if (tailX[i] == x && tailY[i] == y)
exit(0);
}
if (x == fruitX && y == fruitY) // 判断是否吃到水果
{
score += 10;
fruitX = rand() % width;
fruitY = rand() % height;
nTail++;
}
}
int main()
{
Setup();
while (true)
{
Draw();
Input();
Logic();
Sleep(80); // 控制帧率
}
return 0;
}
```
在Windows下,可以使用Windows API提供的SetConsoleTextAttribute函数实现颜色。例如,将水果设为红色:
```c++
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, 12); // 红色
cout << "F";
SetConsoleTextAttribute(hConsole, 7); // 还原为白色
```
在Draw函数中加入这段代码即可。其他颜色的值可以参考Windows API文档。