Javascript游戏:如何;“暂停”;while循环以等待用户输入
Javascript Game: How to "suspend" a while loop to wait for a user input
我正在用javascript编写一个基于文本的游戏,其中一个主要的"功能"是一个输入框,它接受用户输入,并通过按钮标签提交输入。在我的主游戏循环中,点击按钮:
var game_u = new game_util();
function Game_Main(){
while(active){
input = game_u.getText();
//p = new player();
active = false;
}
}
function game_util(){
this.getText = function(){
//The Submit button
confirm_plr.onclick = function(){
//Input value
return player_in.value;
}
}
}
然而,这种方式的问题在于while循环不会"等待"点击提交按钮以从`game_u.getText();函数,并继续循环。
有没有更好的方法让我做到这一点,这是我第一次玩基于文本的游戏?我不想使用提示法,因为它打破了游戏的沉浸感。
我也来自Java,一种面向对象的编程语言,所以这就是我使用while循环的原因。
感谢您的帮助。
如果您想暂停用户输入,一个简单的prompt()
框就可以了。
试试这个:
var input = prompt("Enter data here", "");
这将等待输入并将其存储到变量input
中。
请参阅JSFiddle.net上的工作示例。
AFAIK,同步JS是不可能的,根据这个SO帖子:
JavaScript是异步的,不能"暂停"执行。此外,当javascript运行时,整个用户界面会冻结,因此用户无法单击按钮。
关于你的问题,
如果我不应该使用while循环,用什么来代替它?
因为JS是事件驱动的,并且每次单击按钮(并输入输入)时都要运行代码,所以只需使用onclick
处理程序。
因此,与其这样:
while(active) {
input = game_u.getText();
p = new player();
active = false;
}
你可以做:
document.getElementById("button").addEventListener("click", function() {
input = game_u.getText();
p = new player();
active = false;
});
这将在每次单击按钮时运行代码,与您尝试执行的操作基本相同
一种方法是将游戏的不同阶段分解为与不同阶段(房间、关卡等)相对应的功能,这些功能根据用户的输入进行调用;您还需要一个保存游戏当前状态的变量(以下示例中的room
)。
(function Game() {
var room = 1;
document.getElementById('playerSubmit').addEventListener('click', function() {
var playerInput = document.getElementById('playerInput').value;
if (playerInput == "Go to room 2") {
room = 2;
}
if (playerInput == "Go to room 1") {
room = 1;
}
if (room == 1) {
room1(playerInput);
} else if (room == 2) {
room2(playerInput);
}
document.getElementById('playerInput').value = '';
});
function room1(playerInput) {
output('You are in the first room and entered the command ' + playerInput);
}
function room2(playerInput) {
output("Now you're in room 2. Your command was " + playerInput);
}
function output(text) {
document.getElementById('output').innerHTML += '<p>' + text + '</p>';
}
})();
#output {
border: solid 1px blue;
width: 500px;
height: 400px;
overflow: scroll;
}
label {
display: block; margin-top: 1em;
}
<div id="output"></div>
<label for="playerInput">Player input</label>
<input id="playerInput" type="text" size=50 />
<input id="playerSubmit" type="button" value="Submit" />
http://jsfiddle.net/spjs8spp/2/
您在评论中获得了一些很棒的信息。事件模型可能是理想的,但您可以执行持久循环。我对它不太熟悉,但HTML5 Canvas就是这样。也许可以去看看,因为还没有其他人提到它。
- 如何让foreach循环等待$http.get完成后再继续
- 如何使for循环等待回调返回值
- foreach循环等待,直到每个步骤中的每个函数都完成
- Javascript 循环 - 等待值
- 如何使循环等待到ajax响应
- 让循环等待,直到上一次传递完成
- JavaScript循环等待一些函数返回,然后执行下一个循环
- Javascript 延迟函数,但让循环等待它
- 在JavaScript或Jquery中,让循环等待按钮按下后再继续
- 同步forEach循环(等待它结束)
- 如何在最里面的循环等待响应时延迟嵌套迭代
- 异步for循环:如何让for循环等待函数完成
- 我如何使for循环等待db承诺完成之前,它继续下一个迭代
- 如何强制循环等待,直到用户按下提交按钮
- 节点承诺循环等待结果
- 如何让for循环等待一个函数在javascript中执行
- 让循环等待ajax调用
- jQuery如何使for循环等待加载()完成
- 让 for 循环等待代码完成执行 javascript
- 如何使循环等待回调成功