javascript - 在基于 polymer 的游戏中 : how to display an image depending on the total score

标签 javascript html web-applications polymer

我正在使用 JavaScript 和 HTML 以及 Polymer 框架构建游戏。目前,用户在完成任务时可以获得积分。当回合结束时,屏幕会显示总得分。

我想做的是根据总分向用户显示一个图像作为“徽章”。

例如:

如果总分等于或高于 50 分(但低于 100 分),则显示 Badge1.png
如果总分等于或大于 100(但小于 200),则显示 Badge2.png
等等

以下代码处理评分系统。我有一个 div,可以在回合结束时显示所有这些信息。我需要添加什么才能根据总分显示图像?我有点困惑,谢谢。

loadScores: function() {
  var pts = 0;
  try {
    this.allScores = JSON.parse(localStorage.getItem('game-scores'));
    if (!this.allScores) {
      this.resetScores();
    } else {
      for (var n in this.allScores) {
        pts += this.sumPts(this.allScores[n]);
      }
      this.user.score = pts;
    }
  } catch (e) {
    this.resetScores();
  }
},

computeScore: function() {
  if (this.user) {
    var pts = 0;
    for (var n in this.allScores) {
      pts += this.sumPts(this.allScores[n]);
    }
    this.user.score = pts;
    localStorage.setItem('game-scores', JSON.stringify(this.allScores));
  }
},

resetScores: function() {
  localStorage.removeItem('game-scores');
  if (this.user) {
    this.user.score = 0;
  }
  this.allScores = {};
},

sumPts: function(s) {
  var pts = 0;
  for (var i = 0; i < s.length; i++) {
    pts += (s[i] || 0);
  }
  return pts;
},

最佳答案

非常简单。为此使用隐藏表达式。首先创建一个处理显示的徽章组件,例如

<polymer-element name="badge" attributes="score">
 <image src="/images/badge1.png" hidden?="{{ score < 50 || score > 100 }}" />
 <image src="/images/badge2.png" hidden?="{{ score < 100 || score > 200 }} " />
</polymer-element>

然后包含您的徽章组件,如下所示:

<badge id="badge" />

要更新徽章,您只需为其分配用户分数即可:

this.$.badge.score = this.user.score;

或者,如果您将其保留在数据绑定(bind)中,那么您也可以这样做:

<badge score="{{ score }}" />

组件中的主要代码如下所示:

this.score = 163;

希望有帮助。

关于javascript - 在基于 polymer 的游戏中 : how to display an image depending on the total score,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28888884/

相关文章:

java - AppEngine 中的服务和前端分离导致延迟

javascript - 这是什么功能模式?如果有的话?

javascript - 在动态创建的元素上实现 jQuery

javascript - 为什么我得到的是 [object object ] 而不是 JSON?

javascript - 使用文件加载器将 Webpack 多入口点打包到一个文件中

html - 使用 CSS3 的水平幻灯片

css - HTML <a> 标签定位和高度

javascript - D3.js 更新 onclick 其他元素

java - 编译并升级到JDK 1.7

azure - 由于 'Percent Memory' 限制,VC 管理员 + Azure Web 应用程序 + Hangfire 作业 + 工作进程请求回收