我该如何修改这段代码来使每张卡片都变成一个对象呢?

How would I fix this code to make each card into an object?

本文关键字:张卡片 一个对象 何修改 修改 段代码 代码      更新时间:2023-09-26

我有这个程序,创建不同的牌(从9到a)在每个花色(红心,方块,梅花,黑桃),但我希望每张牌成为一个对象,以便我可以访问每张牌花色和值。

    //This part of the code creates the card, this is what I will need to change.
    function card (name , suit) { 
        window.cardsuit = suit;
        window.cardname = name;
    }
    //This is the deck object it contains the code for making the deck
var deck = {
    //The list of suits
    suit: suits = ["Diamond", "Heart", "Club", "Spade"],
    //The list of card names
    name: names = ["Nine", "Ten", "Jack", "Queen", "King", "Ace"],
    //Array of cards
    cards: cards = [],
    //This function repeats to create each card
    createcards: function(){
            for (var i = 0; i < suits.length; i++){
                for (var j = 0; j < names.length; j++){
                    card(names[j], suits[i]);
                    deck.cards.push(window.cardname + window.cardsuit);

            }
        }
    },
    //This function is used later on to draw a card randomly from the deck
    draw: function (player){
        var randnumber = Math.floor((Math.random() * deck.cards.length));
        player.push(deck.cards[randnumber]);
        deck.cards.splice(randnumber, 1);
    }
};
    //Object of the player hands
    var hand = {
        //This deals out the players hands
        dealhands: function dealhands(amount) {
        t = 0;
        var player_one = [];
        var player_two = [];
        var player_three = [];
        var player_four = [];
        var kitty = [];
        //Deals it however many times I would like the cards dealt
        while (t < amount){
            deck.draw(player_one);
            deck.draw(player_two);
            deck.draw(player_three);
            deck.draw(player_four);
            deck.draw(kitty);
            alert(player_one[0]);
            t ++;
        }
    }
    };

我相信我需要使用"this"关键字,但我不知道如何在这种情况下使用它。谢谢。

定义一个"类" (javascript没有类,它是原型,但"类"是一个有用的词来描述它):

function Card (rank , suit) { 
    this.suit = suit;
    this.rank = rank;
}
var ace_of_spades = new Card('A','♠');
deck.cards.push(ace_of_spades);

否则你在这里看起来不错。在卡片中,术语"名称"在技术上被称为"等级",所以我更改了这些变量的名称。

你在这里创建了全局变量,这是不好的:

suit: suits = ["Diamond", "Heart", "Club", "Spade"],
//The list of card names
name: names = ["Nine", "Ten", "Jack", "Queen", "King", "Ace"],
//Array of cards
cards: cards = [],

保留为:

suit: ["Diamond", "Heart", "Club", "Spade"],
//The list of card names
ranks: ["Nine", "Ten", "Jack", "Queen", "King", "Ace"],
//Array of cards
cards: [],