我正在为一个学校项目在中做一个游戏,我想知道是否有像MakeCode中那样的“重复函数,直到属性=真”类型的循环。我想使用它,这样游戏就会等到我的玩家sprite在某个坐标上才能运行一些代码。我想出了一种不同的方法来做这件事,但我只想知道这一点,以备将来参考。
如果有人想知道,这就是我使用的替代方法。
game.onUpdateInterval(100, function () {
if (level == 1) {
if (myPlayer.x == 950 && myPlayer.y == 140) {
myPlayer.y = 100
myPlayer.x = 10
if (game.ask("Does " + level_1 + " + " + level1_2 + " = " + level1CorrectAns + "?")) {
console.log("Level 1 Completed successfully")
level += 1
LevelChange()
} else {
game.over(false)
}
}
}
})发布于 2021-03-14 16:35:54
您可以使用while循环或do...while循环
对于while循环,只要条件为真,下面的代码就会继续运行。
let x = 0
while (x < 3) {
x++
}
console.log(x) // print 3对于do...while循环,只要条件为真,下面的代码就会继续运行。这个循环至少会运行一次。
let result = '';
let x = 0;
do {
x = x + 1;
result = result + x;
} while (x < 5);
console.log(result); // print "12345"回到你的例子,我相信你会在每个100ms (基于你的game.onUpdateInterval的第一个参数)运行循环。
您可以通过添加timer函数并将此循环包装为异步函数来轻松完成此操作。
const timer = ms => new Promise(res => setTimeout(res, ms))
async function updateInterval() {
while () {
// Your logic here
await timer(100) // You can change the timeout to your desired ms
}
}
updateInterval();虽然我不能100%确定您当前的解决方案的功能,但这是我的解释(希望它能工作)
const timer = (ms) => new Promise((res) => setTimeout(res, ms));
async function updateInterval() {
let state = true; // This is just a condition if the loop should continue
while (state) {
if (level == 1) {
if (myPlayer.x == 950 && myPlayer.y == 140) {
myPlayer.y = 100;
myPlayer.x = 10;
if (
game.ask(
'Does ' +
level_1 +
' + ' +
level1_2 +
' = ' +
level1CorrectAns +
'?'
)
) {
console.log('Level 1 Completed successfully');
level += 1;
LevelChange();
state = false; // Update the state to false, so it will exit the while loop
} else {
game.over(false);
}
}
}
await timer(100); // You can change the timeout to your desired ms
}
}
updateInterval();https://stackoverflow.com/questions/66621796
复制相似问题