【发布时间】:2020-05-13 18:23:05
【问题描述】:
我正在做一个蛇游戏,但尾巴运动有问题。我理解这部分的逻辑,即尾部的每一段都跟随上一段,从尾部的末端开始。我在看别人的代码,看起来是这样的
#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 eDirecton { Stop, Left, Right, Up, Down } 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()
{
for (int i = nTail - 1; i > 0; i--)
{
tailx[i] = tailx[i - 1];
taily[i] = taily[i - 1];
}
tailx[0] = x;
taily[0] = y;
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; 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)
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;
}
我理解其中的逻辑,但我不明白它为什么会起作用。当我们创建一个数组时,每个元素的值只是一个垃圾值,没有初始化每个元素。所以在上面的代码中,当做
tailx[i] = tailx[i-1];
taily[i] = taily[i-1];
为每个元素分配什么值? 显示蛇时,它有一个 for 循环遍历屏幕的每个坐标,并且在它内部还有另一个 for 循环将 tailx[i] 和 taily[i] 与每个坐标进行比较,以找出打印每个段的正确位置尾巴。由于 tailx 和 tialy 不存储尾部段的坐标,所以这段代码是怎么工作的?
非常感谢!!
【问题讨论】:
-
你有多确定它有效?
-
大概是在绘制蛇时,使用了
nTail的当前值,并且该值在代码的其他地方被初始化或更新(当蛇得到食物时)。 -
您粘贴的 sn-p 声明了三个变量,没有初始化它们,并立即使用所有三个变量。您确定 sn-p 中没有缺少代码吗?
-
我很抱歉造成混乱!我已经更新了帖子并添加了整个程序。
标签: c++