掷5骰子的方法

时间:2019-01-12 10:17:21

标签: 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;
}
}

谢谢! :)

2 个答案:

答案 0 :(得分:1)

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

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

编辑:您可以在点击处理程序中使用其他功能,例如:

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

btnHandler()中,您可以将 rollDie() 5次调用5个变量,以后可以使用这些骰子进行任何操作。

答案 1 :(得分:0)

谢谢您的回答。 最后,我创建类似的内容:

paths = ['/assets/img/die-one.png',
'/assets/img/die-two.png',
'/assets/img/die-three.png',
'/assets/img/die-four.png',
'/assets/img/die-five.png',
'/assets/img/die-six.png'];
path = [];

rollDie() {
this.path = Array.from({length: 6}, () => Math.floor(Math.random() * 6));
}



  <img [src]="paths[path[0]]" alt="die-one" class="img-fluid">
  <img [src]="paths[path[1]]" alt="die-two" class="img-fluid">
  <img [src]="paths[path[2]]" alt="die-three" class="img-fluid">
  <img [src]="paths[path[3]]" alt="die-four" class="img-fluid">
  <img [src]="paths[path[4]]" alt="die-five" class="img-fluid">
  <img [src]="paths[path[5]]" alt="die-six" class="img-fluid">