我正在创建一个带有扭曲的经典内存游戏。我有一个卡牌原型(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/