【问题标题】:Entity color as an if statement condition实体颜色作为 if 语句条件
【发布时间】:2013-11-12 13:53:35
【问题描述】:

我对 JavaScript 很陌生。我正在做的任务是一个使用 boxbox 作为物理模拟器的简单游戏。 无论如何,当玩家实体触摸它们时,我有 3 个会改变颜色的方块。我想显示一个简单的结果消息(“只有一个?再试一次!”之类的东西)。但是,我不知道颜色值是否可以用作条件。这是我想出的:

function score() {
if (gold1.color == "gold" || gold2.color == "gold" || gold3.color == "gold") {world.createEntity(result, {
        shape: "square",
        x:9,
        y:4,
        width: 3,
        height: 2,
        image: "only1.png",
        imageStretchToFit: true, }
        }
else if (gold1.color == "gold" && gold2.color == "gold" || gold2.color == "gold" && gold3.color == "gold" || gold1.color == "gold" && gold3.color == "gold") {world.createEntity(result, {
        shape: "square",
        width: 3,
        height: 2,
        x:9,
        y:4,
        image: "only2.png",
        imageStretchToFit: true, }
        }
else (gold1.color == "gold" && gold2.color == "gold" && gold3.color == "gold") {world.createEntity(result, {
        shape: "square",
        width: 3,
        height: 2,
        x:9,
        y:4,
        image: "only3.png",
        imageStretchToFit: true, }
        }
}

我不确定这是完全错误的方法还是只是语法错误。请帮忙。

谢谢。

【问题讨论】:

  • 你遇到了什么错误?
  • 我没有收到任何错误。游戏加载到画布中,当我添加这个函数时,它根本加载不出来。
  • gold1、gold2、gold3分别是什么对象?
  • 它们都是同一个变量的实例:var block2 = { name: "block2", shape: "square", color: "orange", width: 1, height: 1, density: 20, onImpact: function (entity, force) { if (entity.name() === "player") { this.color("gold"); } } };
  • 你是说你的控制台没有任何错误?

标签: javascript if-statement colors conditional-statements


【解决方案1】:

您应该在浏览器中使用调试器(如果您使用的是 chrome,只需按 f12)。在您发布的代码执行之前放置一个断点。您在 gold1.color、gold2.color 中看到什么值?

根据您给我们的描述,我发现您发布的代码令人困惑。你为什么要做所有这些检查?

一旦有更多信息,我将编辑我的答案..

另外一件事,看起来你的第一个代码块会执行,如果其他两个会执行,那么你为什么还要有“else if”语句呢?如果任何一种颜色为金色,则第一个代码块将执行,而其他代码块将永远不会执行,因为它们都需要一种或多种颜色为金色。

【讨论】:

  • 不,因为&&precedence|| 更高,它按此顺序进行评估,不需要括号。
【解决方案2】:

怎么样:

function score() {
    var nrGold = 0;

    if (gold1.color == "gold") {
        nrGold++;
    }
    if (gold2.color == "gold") {
        nrGold++;
    }
    if (gold3.color == "gold") {
        nrGold++;
    }

    if (nrGold!==0) {
        world.createEntity(result, {
            shape: "square",
            width: 3,
            height: 2,
            x:9,
            y:4,
            image: "only"+nrGold+".png",
            imageStretchToFit: true
        });
     }
}

注意 1:json 中的最后一个属性不应以逗号结尾(请参阅代码中的 imageStretchToFit: true,

注意 2:您缺少 world.createEntity 函数的右括号

【讨论】:

  • 这并没有使游戏崩溃,它加载得很好,但没有使“结果”实体出现。感谢您的笔记,我现在会更加注意!
猜你喜欢
  • 2015-05-27
  • 1970-01-01
  • 1970-01-01
  • 2012-11-02
  • 2019-03-01
  • 2016-09-07
  • 2017-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多