javascript - 如何创建一个输出 'x' 个类的各种实例的函数?

标签 javascript

我正在创建一个带有扭曲的经典内存游戏。我有一个卡牌原型(prototype),还有好卡牌和坏卡牌的实例。我想创建一个函数来处理每张卡的指定数量。例如,我想发 16 张牌:4x 弹药、4x 啤酒、2x 雪茄、2x 蛇、2x 敌人、2x 蝎子。

我不确定首先创建实例是否是解决此问题的正确方法,或者是否必须在交易函数中创建它们。

 <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 张牌,每张牌均取自牌牌原型(prototype)并具有自己的属性。

最佳答案

我建议将实例存储在数组

像这样:

// 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];

关于javascript - 如何创建一个输出 'x' 个类的各种实例的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55860247/

相关文章:

javascript - 输入类型 "Text"会出现模糊文本,焦点消失?

JavaScript : how to know which tab is active

c# - 如何使用对话框/提要 javascript 在 Facebook 的描述字段中添加 URL?

javascript - jQuery 合并过多的 if/else 条件

javascript - 使用 d3js 将标签添加到 map

javascript - 如何用 Jest 模拟 DataTransfer

javascript - 如何防止所有表行同时切换

javascript - 在我将其 CSS 从右更改为左后,Jquery 面板 slider 不会关闭

javascript - 选择选项后重定向

javascript - 在不阻止组合框打开的情况下停止窃取焦点