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