贪吃蛇是一款经典的游戏,玩家通过控制一条蛇在屏幕上移动,吃掉食物来增长身体长度,并避免碰到自己的身体或者屏幕边缘。本文将为你提供一个基于 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 << "#";
co