节点应用交互获取用户输入可以通过暂停当前执行反应前端
我转换被写在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(thiswork, 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同步暂停游戏,并通过命令提示符获取用户输入。现在,我建,以服务于游戏与用户界面浏览器中的反应前端应用,以及我建立明确的处理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-do-whilst为节点(我敢肯定有周边的承诺举办传统的循环结构其他类似的比喻可以说,你有连续的同步代码如下所示(其中,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;
})
如果你有一对夫妇,你必须等待“进步”在你的循环并行线程,你可以让他们全部返回承诺的功能发生,把所有这些返回的承诺到一个数组arr
,然后有FN return Promise.all(arr)
。一个.then
后甲Promise.all
函数接收在阵列中保存位置顺序原始承诺的解析值。希望这可以帮助!