贪吃蛇 c++代码
时间: 2023-07-09 13:14:25 浏览: 60
以下是一个简单的贪吃蛇 C++ 代码示例,使用了基本的控制台输入输出:
```c++
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
bool GameOver;
const int Width = 20;
const int Height = 20;
int x, y, fruitX, fruitY, score;
int tailX[100], tailY[100];
int nTail;
enum eDirection
{
STOP = 0,
LEFT,
RIGHT,
UP,
DOWN
};
eDirection dir;
void Setup()
{
GameOver = false;
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':
GameOver = true;
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;
default:
break;
}
if (x < 0 || x >= Width || y < 0 || y >= Height)
GameOver = true;
for (int i = 0; i < nTail; i++)
if (tailX[i] == x && tailY[i] == y)
GameOver = true;
if (x == fruitX && y == fruitY)
{
score += 10;
fruitX = rand() % Width;
fruitY = rand() % Height;
nTail++;
}
}
int main()
{
Setup();
while (!GameOver)
{
Draw();
Input();
Logic();
Sleep(50);
}
return 0;
}
```
使用了 `_kbhit()` 和 `_getch()` 函数来检测键盘输入,利用了 Windows.h 库的 `Sleep()` 函数来控制游戏帧率。此外,还使用了两个数组来存储蛇的每一节身体的坐标,来实现蛇的移动。