如何解决MakeCode JS 中是否有“重复 [函数] 直到 [property = true]”类型的循环?
我正在 Microsoft MakeCode Arcade 中为学校项目制作游戏,我想知道是否有“重复 [函数] 直到 [属性 = 真]”类型的循环,就像在 Luau 中那样。我想使用它,以便游戏等到我的玩家精灵在某个坐标处运行一些代码。我想出了一种以不同方式执行此操作的方法,但我想知道仅供将来参考。
如果有人想知道,这就是我使用的替代方式。
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)
}
}
}
})
解决方法
您可以使用 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();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。