贪吃蛇代码不用图形库
时间: 2024-06-19 19:04:42 浏览: 12
贪吃蛇是一种非常经典的小游戏,它的实现需要掌握基本的编程知识和数据结构。下面是一个简单的贪吃蛇代码示例:
```
#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 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;
nTail = 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;
}
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':
dir = STOP;
break;
}
}
}
void Logic()
{
int prevX = tailX;
int prevY = tailY;
int prev2X, prev2Y;
tailX = x;
tailY = 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 > width || x < 0 || y > height || y < 0)
{
cout << "Game Over!" << endl;
exit(0);
}
for (int i = 0; i < nTail; i++)
if (tailX[i] == x && tailY[i] == y)
{
cout << "Game Over!" << endl;
exit(0);
}
if (x == fruitX && y == fruitY)
{
nTail++;
fruitX = rand() % width;
fruitY = rand() % height;
}
}
int main()
{
Setup();
while (true)
{
Draw();
Input();
Logic();
Sleep(100); // 控制速度
}
return 0;
}
```
这个代码使用了命令行窗口来显示地图和贪吃蛇,没有使用任何图形库。具体实现过程是:先定义了地图大小、贪吃蛇的位置、食物的位置、贪吃蛇的长度等变量;然后在 Setup 函数中初始化这些变量;在 Draw 函数中绘制地图、贪吃蛇和食物;在 Input 函数中获取用户输入的方向;在 Logic 函数中根据用户输入的方向计算贪吃蛇的新位置,并判断是否撞墙或者吃到了食物等情况。最后在 main 函数中不断循环 Draw、Input 和 Logic 函数,从而实现了贪吃蛇游戏。