簡體   English   中英

如何創建一個輸出類的各種實例的“ x”數量的函數?

[英]How can I create a function that outputs 'x' amount of various instances of a class?

我正在創建一個經典的記憶游戲。 我有一個卡片原型,並且有好卡片和壞卡片的實例。 我想創建一個函數,處理每張卡的特定數量。 例如,我要分發16張牌:4xammo,4xbeers,2x雪茄,2xsnakes,2enemigos和2x蠍子。

我不確定是否首先創建實例是執行此操作的正確方法,還是不確定是否必須使它們在deal函數中起作用。

 <section class="memory-game">

 </section>

      class Card {
        constructor(name, image, health, ammo) {
          this.name = name
          this.image = image
          this.health = health
          this.ammo = ammo
        }
      }

      // Good Cards
      const ammo = new Card('ammunition', null, 1, null),
            beer = new Card('beer', null, 1, null),
            cigar = new Card('cigar', null, 1, null)

      // Bad Cards
      const enemigo = new Card('enemigo', null, -1, null),
            bandito = new Card('bandito', null, null, -1),
            snake = new Card('snake', null, -1, null),
            scorpion = new Card('scorpion', null, -1, null)

      function dealCards() {

      }

預期的結果是將發行16張卡,每張卡都從卡原型中提取並具有自己的屬性。

我建議將實例存儲在Array

像這樣:

// good cards
const ammoCards = [...Array(4)].map(i => new Card('ammunition', null, 1, null));
const beerCards = [...Array(4)].map(i => new Card('beer', null, 1, null));
// all other good cards
...
const goodCards = [...ammoCards, ...beerCards];

// repeat for bad cards

// and then

const allCards = [...goodCards, ...badCards];

沒錯,您應該在Deal函數內部實例化。

我要做的是寫一些清單,列出要處理的每張卡的卡數量以及卡的規格。

然后,我將遍歷列表中的每個項目,然后再次迭代要處理的卡的數量,同時在給定適當規格的情況下實例化Card類。 我為規格使用數組,因此我可以輕松地使用rest參數實例化Card類。

我使Deal函數成為類中的一種方法,目的只是為了保持一致。 我制作的Dealer類可以進行修改,以接受{specs: [], amount: 0} 但是現在,我將使其保持靜態以使事情簡單。

 class Card { constructor(name, image, health, ammo) { this.name = name this.image = image this.health = health this.ammo = ammo } } class Dealer { constructor() { this.cards = {}; this.cards.ammo = { specs: ['ammunition', null, 1, null], amount: 4 }; this.cards.beer = { specs: ['beer', null, 1, null], amount: 4 }; this.cards.cigar = { specs: ['cigar', null, 1, null], amount: 2 }; this.cards.enemigo = { specs: ['enemigo', null, -1, null], amount: 2 }; this.cards.bandito = { specs: ['bandito', null, null, -1], amount: 2 }; this.cards.snake = { specs: ['snake', null, -1, null], amount: 2 }; this.cards.scorpion = { specs: ['scorpion', null, -1, null], amount: 2 }; } deal() { const outputCards = []; Object.keys(this.cards).forEach(d => { for (let i = 0; i < this.cards[d].amount; i++) { let c = new Card(...this.cards[d].specs); outputCards.push(c); } }); return outputCards } } console.log(new Dealer().deal()); 

暫無
暫無

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

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