Node 应用程序通过暂停当前执行以交互方式从 React 前端获取用户输入

IT技术 javascript node.js reactjs express node-modules
2021-04-28 05:09:26

我将一个用python编写的旧游戏转换为javascript(节点)。游戏只是在 while 循环中运行,直到完成一定数量的迭代。

runUntil(steps = 100000) {
var x = 0;
while (x < steps) {
  this.conversation();
  x++;
}

}

conversation() {
const roundPicture = this.getRandomPicture();
const conversationers = this.utils.getRandomTwo(this.network, this.Graph);

const chosen1 = conversationers[0];
const chosen2 = conversationers[1];


if (chosen1.name == "Player 0" && !chosen1.v.hasOwnProperty(roundPicture)) {
  //Wait for user input
  //..
  //..
  //..
  //Use the given input in order to continue game

}

if (chosen2.name == "Player 0" && !chosen2.v.hasOwnProperty(roundPicture)) {
    //Wait for user input
    //..
    //..
    //..
    //Use the given input in order to continue game

} else {
  //do sth else
}

}

在某些情况下,游戏会暂停以获取所需的用户输入并影响游戏结果。在我的 javascript 实现中,我使用 readline-sync 来暂停游戏并通过命令提示符获取用户输入。现在我构建了一个 React 前端应用程序,以便在带有 UI 的浏览器中为游戏提供服务,并且我使用 express 构建了一个服务器来处理 API 并在用户按下开始时运行游戏。

const express = require("express");
const http = require("http");
const socketIO = require("socket.io");
const Game = require("./Game");
const port = 4000;
const app = express();
const server = http.createServer(app);
//Create socket usin server instance
const io = socketIO(server);

io.on("connection", socket => {

  console.log("user connected!");
  socket.on("startGame", data => {
    const nI = data.nI;
    const pI = data.pI;
    const noOfAgents = 20;
    const noOfPlayers = 1;

    const g = new Game(nI, pI, noOfAgents, noOfPlayers);
    g.runUntil(1000);
    });

  socket.on("disconnect", () => console.log("user has disconnected"));
});




server.listen(port, () => console.log("Listenint on port " + port));

但是,我目前被困在这一点上。我不确定如何暂停游戏以从前端获取数据并相应地使用它。到目前为止,我所做的所有尝试都没有运气。我尝试使用 Promise 但这没有帮助,因为它没有暂停游戏流程的过程以等待用户输入。

1个回答

Node有一个名为promise-do- while的方便包(我确信围绕 Promise 组织的传统循环结构还有其他类似的类比。假设您有如下所示的顺序同步代码(其中 fn 是一个简单的同步函数) :

  do {
    fn();
  } while( condition === true)

... 将其改写为 ...

  var promiseDoWhilst = require('promise-do-whilst')
  var condition = true;
  function fn() { // for example
    condition = Math.random() > 0.5; // flip a coin
    return new Promise(function(r, j){
      setTimeout(function(){ r(); }, 1000);
    }); 
  }
  promiseDoWhilst(function() {
    return fn(); with fn converted to a promise-returning function
  }, function() {
    return condition === true;
  })

如果您有几个并行线程必须等待才能在循环中“取得进展”,您可以让它们全部发生在返回Promise的函数中,将所有这些返回的Promise放入一个数组中arr,然后使用 fn return Promise.all(arr)a.then之后的函数在Promise.all保留位置顺序的数组中接收原始Promise的解析值。希望这可以帮助!