首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在MakeCode JS中有"repeat [function] until [property = true]“类型的循环吗?

在MakeCode JS中有"repeat [function] until [property = true]“类型的循环吗?
EN

Stack Overflow用户
提问于 2021-03-14 14:42:11
回答 1查看 47关注 0票数 1

我正在为一个学校项目在中做一个游戏,我想知道是否有像MakeCode中那样的“重复函数,直到属性=真”类型的循环。我想使用它,这样游戏就会等到我的玩家sprite在某个坐标上才能运行一些代码。我想出了一种不同的方法来做这件事,但我只想知道这一点,以备将来参考。

如果有人想知道,这就是我使用的替代方法。

代码语言:javascript
复制
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)
            }
        }
    }
})
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-14 16:35:54

您可以使用while循环或do...while循环

对于while循环,只要条件为真,下面的代码就会继续运行。

代码语言:javascript
复制
let x = 0

while (x < 3) {
  x++
}

console.log(x) // print 3

对于do...while循环,只要条件为真,下面的代码就会继续运行。这个循环至少会运行一次。

代码语言:javascript
复制
let result = '';
let x = 0;

do {
  x = x + 1;
  result = result + x;
} while (x < 5);

console.log(result); // print "12345"

回到你的例子,我相信你会在每个100ms (基于你的game.onUpdateInterval的第一个参数)运行循环。

您可以通过添加timer函数并将此循环包装为异步函数来轻松完成此操作。

代码语言:javascript
复制
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%确定您当前的解决方案的功能,但这是我的解释(希望它能工作)

代码语言:javascript
复制
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();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66621796

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档