繁体   English   中英

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

[英]Node application interactively get user input from react front end by pausing the current execution

我将用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,但这没有帮助,因为它没有暂停游戏流程以等待用户输入。

有一个方便的Node包,称为Promise-do-whilst (我确信围绕Promises组织的传统循环构造还有其他类似的类比。假设您有如下所示的顺序同步代码(其中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) .then一后函数Promise.all接收在阵列中保存位置顺序原始承诺的解析值。 希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM