首页 > 解决方案 > 如何在 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;
}

标签: c++

解决方案


我不确定你的游戏是如何运作的。我猜这是从键盘/控制器读取玩家输入、计算 AI、碰撞检测并将某些内容渲染到屏幕的“循环”。如果是这样的话...

而不是Sleeping,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++;
    }
  }

推荐阅读