Card class
unknown
javascript
3 years ago
3.0 kB
9
Indexable
class Card { /* id format: "suit-number" suit = h | s | c | d (hearts, spades, clubs and diamonds respectively) number = 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13 Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen and King respectively */ static possibleIDs = [ "h-01", "h-02", "h-03", "h-04", "h-05", "h-06", "h-07", "h-08", "h-09", "h-10", "h-11", "h-12", "h-13", "s-01", "s-02", "s-03", "s-04", "s-05", "s-06", "s-07", "s-08", "s-09", "s-10", "s-11", "s-12", "s-13", "c-01", "c-02", "c-03", "c-04", "c-05", "c-06", "c-07", "c-08", "c-09", "c-10", "c-11", "c-12", "c-13", "d-01", "d-02", "d-03", "d-04", "d-05", "d-06", "d-07", "d-08", "d-09", "d-10", "d-11", "d-12", "d-13", ]; #getRank(id) { if ([1, 11, 12, 13].includes(parseInt(id.slice(2)))) { switch (parseInt(id.slice(2))) { case 1: return "ace"; case 11: return "jack"; case 12: return "queen"; case 13: return "king"; default: throw new Error("Unknown error."); } } switch (parseInt(id.slice(2))) { case 2: return "two"; case 3: return "three"; case 4: return "four"; case 5: return "five"; case 6: return "six"; case 7: return "seven"; case 8: return "eight"; case 9: return "nine"; case 10: return "ten"; default: throw new Error("Unknown error."); } } #getSuit(id) { switch (id.charAt(0)) { case "h": return "hearts"; case "s": return "spades"; case "c": return "clubs"; case "d": return "diamonds"; default: throw new Error("Unknown error."); } } #cap(s) { return s.charAt(0).toUpperCase() + s.slice(1); } constructor(id = "h-01", nice = true) { Object.freeze(Card.possibleIDs); if (typeof nice != "boolean") throw new Error('"nice" must be a boolean!'); this.id = id.toLowerCase(); if (!Card.possibleIDs.includes(this.id)) throw new Error(`Invalid card ID! Possible IDs are: ${Card.possibleIDs.join(', ')}`); this.suit = nice ? this.#cap(this.#getSuit(this.id)) : this.#getSuit(this.id); this.color = ['h', 'd'].includes(this.id.charAt(0)) ? `${nice ? 'Red' : 'red'}` : `${nice ? 'Black' : 'black'}`; this.rank = nice ? this.#cap(this.#getRank(this.id)) : this.#getRank(this.id); this.name = `${this.rank} of ${this.suit}`; } toString() { const r = `${['a', 'j', 'q', 'k'].includes(this.rank.charAt(0).toLowerCase()) ? this.rank.charAt(0) : parseInt(this.id.slice(2))}`; const s = `${this.id.charAt(0) === "h" ? "♥️" : this.id.charAt(0) === "s" ? "♠️" : this.id.charAt(0) === "c" ? "♣️" : "♦️"}`; return `${r}${s}`; } } module.exports = Card;
Editor is loading...