簡體   English   中英

擲5骰子的方法

[英]Method for roll 5 dice

我想用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()內部,您可以將rollDie()調用5次到5個變量中,以后可以使用這些骰子進行所需的操作。

謝謝您的回答。 最后,我創建類似的內容:

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">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM