我想创建一个有 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/