javascript - 掷5个骰子的方法

标签 javascript angular typescript

我想创建一个有 5 个骰子的游戏。我创建了一个用随机方法掷骰子的函数,但我不知道如何将其扩展到其他四个骰子。我不想为每个骰子创建一个方法。

dice.component.html

 <button type="button" (click)="rollDie()">Roll the dice</button>

  <img [src]="path" alt="die-one" class="img-fluid">
  <img [src]="path" alt="die-two" class="img-fluid">
  <img [src]="path" alt="die-three" class="img-fluid">
  <img [src]="path" alt="die-four" class="img-fluid">
  <img [src]="path" alt="die-five" class="img-fluid">
  <img [src]="path" alt="die-six" class="img-fluid">


dice.component.ts

path = '/assets/img/die-one.png';
path1 = '/assets/img/die-one.png';
path2 = '/assets/img/die-two.png';
path3 = '/assets/img/die-three.png';
path4 = '/assets/img/die-four.png';
path5 = '/assets/img/die-five.png';
path6 = '/assets/img/die-six.png';


rollDie() {

let number = Math.floor(Math.random() * 7);

switch (number) {
  case 1:
    this.path = this.path1;
    break;
  case 2:
    this.path = this.path2;
        break;
  case 3:
    this.path = this.path3;
    break;
  case 4:
    this.path = this.path4;
    break;
  case 5:
    this.path = this.path5;
    break;
  case 6:
    this.path = this.path6;
}
}

谢谢! :)

最佳答案

您可以将函数设置为返回它生成的数字,然后在 5 个不同的变量中调用它 5 次,例如:

var die1 = rollDie(), die2 = rollDie(), //etc..

编辑:您可以在点击处理程序中使用另一个函数,例如:

<button type="button" (click)="btnHandler()">Roll the dice</button>

btnHandler() 中,您可以在 5 个变量中调用 rollDie() 5 次,然后您可以使用这些骰子执行以后需要的任何操作。

关于javascript - 掷5个骰子的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54158625/

相关文章:

angular -/node_modules/moment-timezone/index.d.ts (47,77) : ';' expected. 中出现错误如何修复

Angular - 对所有组件导入使用桶文件

html - 实时数据 Angular

angular - Google API 回调更改后 View 未更新

javascript - Angular 2 : oauth2 with token headers

unit-testing - Angular 2 : "TypeError: Cannot read property ' createAsync' of undefined"

javascript - AngularJS中 Controller 和指令之间的通信

javascript - 适用于 Firefox OS 的 Phonegap 存储 API(索引数据库)

javascript - 仅将样式应用于可编辑内容中的选定文本 <p>

javascript - 滚动到 div,防止第二次点击