c++ - 如何让我的蛇在 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 n_Tail;
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+1; i++)
{
cout << "#"; //for Upper wall
}
cout << "\n";
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width ; j++)
{
if (j==0)
{
cout <<"#";
}
if (i == y && j == x)
{
cout <<"0";
}
else if (i == fruitY && j == fruitX)
{
cout <<"f";
width - 1;
}
else if (j== width -1)
{
cout << "#";
}
else
{
bool print = false;
for (int k = 0; k <n_Tail; k++)
{
if (tailX[k] == j && tailY[k] == i )
{
cout << "o";
print = true;
}
}
if (!print)
{
cout <<" ";
}
}
}
cout << "\n";
}
for (int i = 0; i < width+1; i++)
{
cout << "#"; //for lower wall
}
cout <<"\n";
cout << "Score = " << score;
}
void input()
{
switch (_getch())
{
case 'a': dir = LEFT;
break;
case 'w': dir = UP;
break;
case 's': dir = DOWN;
break;
case 'd': dir = RIGHT;
break;
}
}
void logics()
{
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x;
tailY[0] = y;
for (int i = 1; i < n_Tail; 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:
y--;
}
for (int i = 0; i < n_Tail; i++)
{
if (tailX[i] == x && tailY[i] == y)
{
gameOver = true;
}
}
//if (x> width||x<0||y>height||y<0)
//{
//gameOver = true;
//}
if (x > width-2)x = 0; else if (x < 0)x = width - 2;
if (y > height-1)y = 0; else if (y < 0)y = height - 1;
{
}
if (x == fruitX && y == fruitY)
{
score = score + 10;
fruitX = rand() % width;
fruitY = rand() % height;
n_Tail++;
}
}
int main()
{
setup();
while (!gameOver)
{
draw();
input();
logics();
Sleep(10);
}
}
有人请帮助我,这样我就可以继续平静地学习 C++。
解决方案
推荐阅读
- python - 使用 rpy2 在 Python 中引入 Rlist
- html - 为什么我的粘性导航仅在我的标题设置为内联时才有效?
- python - 如何在 mac catalina 上的 Visual Studio 代码上从 python 2.7 切换到 3.8?
- r - 使用正则表达式捕获物种名称(二项式名称)
- c# - C# 控制台应用程序无法使用 AccessToken 访问 Web Api 总是出现 401 错误
- youtube-api - 审核成功后 API 访问仍然被禁用
- ios - iOS 从 Crashlytics 迁移到 FirebaseCrashlytics
- python - 当df包含字符串获取错误时计算pandas pct_change:TypeError:不支持/:'float'和'str'的操作数类型
- c# - Azure 媒体服务 V3 元数据
- xpath - 有没有办法从部分搜索中获取完整的属性名称,并将其保存为变量?