c++ - 如何在 C++ 中私下延迟命令?
问题描述
我正在尝试为我正在制作的一个小游戏制作一个非常基本的 AI。我有一个妖精,我想在需要时改变它的位置,但是延迟 500 毫秒以使其更容易避免。
我试过这个:
#include <iostream>
#include <windows.h>
using namespace std;
int gX = 18, gY = 12;
int goblinAI() {
if(gX - x > 0) {
Sleep(500);
cMap[gY][gX] = '.';
gX--;
} else if(gX - x < 0) {
Sleep(500);
cMap[gY][gX] = '.';
gX++;
}
return 0;
}
我认为这段代码会起作用,但事实证明我忽略了一些东西。现在它将为程序的其余部分休眠,因为它是用 goblinAI(); 调用的。我怎样才能“私下”调用 Sleep(); 为了让它只在自己里面睡觉而不是“感染”整个程序?
游戏.cpp代码:
#include <iostream>
#include <windows.h>
using namespace std;
char cMap[21][34] = {
"#################################",
"#@..............................#",
"#...............................#",
"#...............................#",
"#...............................#",
"#...............................#",
"#...............................#",
"#...............................#",
"#...............................#",
"#...............................#",
"#...............................#",
"#...............................#",
"#...............................#",
"#...............................#",
"#...............................#",
"#...............................#",
"#...............................#",
"#...............................#",
"#################################"
};
bool running = true;
bool alive = true;
int x = 1, y = 1;
int health = 100;
int eX, eY; // exit x and y
#include "controls.cpp" // includes the controls file after the instantation of the variables in which it uses
#include "goblinAI.cpp"
int main() {
while (running) {
controls();
goblinAI();
//cMap[eX][eY] = 'E';
cMap[y][x] = '@';
cMap[gY][gX] = 'G';
system("cls");
for (int i = 0; i < 20; i++) {
cout << cMap[i] << endl;
}
for(int i = 0; i < 1; i++) {
cout << "HP: " << health << endl;
}
if(cMap[y][x] == cMap[gY][gX]) {
health--;
}
if(health == 0) {
alive = true;
running = false;
}
system("pause>nul");
}
return 0;
}
解决方案
我不确定你的游戏是如何运作的。我猜这是从键盘/控制器读取玩家输入、计算 AI、碰撞检测并将某些内容渲染到屏幕的“循环”。如果是这样的话...
而不是Sleep
ing,GoblinAI
尽可能频繁地调用(每帧一次)并使用时间戳来决定是否是“移动”对象的合适时机。
DWORD lastGoblinMoveTime = 0;
int goblinAI() {
DWORD dwTime = GetTickCount();
DWORD elapsed = dwTime - lastGoblinMoveTime;
if (elapsed > 500) {
lastGoblinMoveTime = dwTime;
if(gX - x > 0) {
cMap[gY][gX] = '.';
gX--;
} else if(gX - x < 0) {
cMap[gY][gX] = '.';
gX++;
}
}
推荐阅读
- r - write.table() 附加参数
- python - 如何检查 numpy 数组中的字母是否在高级拼贴中?
- python - 是否可以在不更改源代码的情况下使用 pylint 忽略单个特定行?
- angularjs - 如何使用 ng-repeat 以角度自动选择第一个元素?
- python - 收到有关 fork 与 MPI 不兼容的警告。什么情况下可以忽略?
- excel - runtime error -2147024809 (80070057): Resizing shape
- php - 连续加入不同的值mysql
- react-native - 如何仅在一个屏幕上包含底部标签
- sql - 创建将参数显示为列的查询 - BigQuery
- git - 在 gitignore 上取消跟踪文件,但仍保留原始文件