在Javascript中动态命名对象

时间:2017-10-10 20:51:50

标签: javascript arrays

我正在尝试创建一个二十一点游戏,并且在分手时遇到问题。最后,我想创建一个associative array,其中包含每个拆分的总计和状态,将每个拆分视为自己的hand object。我遇到的问题之一是我正在尝试动态执行命名功能,因此每次调用Split Function时,它都会根据手被分割的次数创建名称。

关于我迄今为止所创造的内容的一些背景知识;卡片对象包含名称,套装和价值(即女王,俱乐部,10)。我有一个名为cardsInDeck的数组,它将所有卡片对象保存在一个洗牌的卡片中,这样每张卡片都可以随机拉出。从卡片中取出卡片时,会将值推入数组以计算值,并将名称和套装连接起来并添加到字符串中以填充HTML以显示页面上的卡片。

function drawOne() {
    let card = cardsInDeck.pop();
    return card;
}

var handNumber = 0;
var playerHand01 = [];
var p1, p2, d1;

function initialDealOut() {
    ++handNumber;
    p1 = drawOne();
    playerHand01.push(p1.value);
    ++playerCount;
    let p1n = p1.name + p1.suit;
    let p1c = "images/" + p1n + ".png";
    let p1Image = document.getElementById('player01');
    p1Image.src = p1c;
}

对于经销商第一张牌(d1)和玩家的第二张牌(p2)重复此操作并且效果良好。我想要做的是让playerHand01成为Hand Player array中Hand对象的一部分,该对象包含所有人,并关联状态(" action",& #34;站在","胸围")到每个Hand对象。

我试图通过以下代码完成此任务:

var player = new Array();

function Hand(total, status) {
  this.total = total;
  this.status = status;
}

function Split() {
  ++handNumber;
  let handName = "playerHand0" + handNumber;
  let handTotal = "playerHandTotal0" + handNumber;
  handName = new Hand {
      handTotal: 0,
      status: "action"
    }
}

我是编程新手,我知道可以做到,只要知道我接近它的方式是不对的。

任何建议都将受到赞赏。

3 个答案:

答案 0 :(得分:1)

我可能只是使用一个数组来存储手。他们的索引可以访问它们。如果你想给他们一个名字,那可能是手对象的一部分。

let playerHands = [];
function Split() {
   ++handNumber;
   let newHand = new Hand ({
     handName: 'playerHand' + handNumber
     handTotal: 0, 
     status: 'action'
   });
   playerHands.push(newHand);
}

或者,如果您想使用某个对象(可能是因为我误解了您的要求),则可以动态地为对象提供属性。有两种不同的语法可用于对象属性。以下两个都有相同的结果:

let myObject = {};
myObject.test = 'hi';

let myObject = {};
myObject['test'] = 'hi';

您通常会使用前者,但如果您在运行时之前不知道名称,后者会为您提供更大的灵活性,因为您可以使用任何字符串进行访问。例如,以下内容完全有效:

let player = {};
let handName = 'playerHand0' + handnumber;
player[handName] = new Hand();

答案 1 :(得分:0)

阅读时有点令人困惑,我不认为您已经充分考虑了需要存储的信息。

由于这个问题的焦点实际上是如何分割手IMO,我将告诉你,希望它会指向你正确的方向。

首先是手对象。我将使用es6,但你可以使用你在那里的构造函数方法做类似的事情。

class Hand {
  constructor(total, status){
    this.total = total;
    this.status = action;
    this.cards = [];
  }

  drawCard(){
    this.addCard(drawOne());
  }

  addCard(card){
    this.cards.push(card);
    this.updateScore();
  }

  updateScore(){
     // loop through and update the score and status
  }

  // this is the one you've been waiting for
  split(player){
    // can only split in certain conditions
    if(this.cards.length !== 2 || this.cards[0] !== this.cards[1]){
      console.log('cannot split this (?)');
      return null;
    }

    // create the new hand
    let additionalHand = new Hand(0, 'active');
    additionalHand.addCard(this.cards.pop());
    player.hands.push(additionalHand);

    // need to draw a new card for each hand
    this.drawCard();
    additionalHand.drawCard()

    //return the new hand in case you want to do something with that.
    return additionalHand;
  }
}

这可能不是您想要的,但它应该是一个很好的帮助初始指南。

答案 2 :(得分:0)

我会建议每个概念(玩家,卡片,甲板,手,游戏)的课程,并且在游戏关卡中你会保留一系列活动的手,这些(在拆分后)可以有不同的编号而不是球员的数量。

以下是它的外观:

class Card {
    constructor(name, suit, value) {
        this.name = name+'';
        this.suit = suit;
        this.value = typeof name === 'number' ? name 
            : 10 + (name === 'Ace');
    }
}

class Player {
    constructor(name) {
        this.name = name;
    }
}

class Hand {
    constructor(player, total, status) {
        this.player = player; // a back reference to the owning player
        this.total = total;
        this.status = status;
    }
    addCard(card) {
        this.total += card.value;
    }
    copy() {
        return new Hand(this.player, this.total, this.status);
    }
}

class Deck {
    constructor() {
        this.cards = [];
        for (let suit of ['Clubs', 'Hearts', 'Spades', 'Diamonds']) {
            for (let name of ['Ace',2,3,4,5,6,7,8,9,10,'Jack','Queen','King']) {
                this.cards.push(new Card(name, suit));
            }
        }
    }
    shuffle() {
        for (let i = this.cards.length; i; i--) {
            let j = Math.floor(Math.random() * i);
            [this.cards[i - 1], this.cards[j]] = [this.cards[j], this.cards[i - 1]];
        }
        return this;
    }
    drawOne() {
        return this.cards.pop();
    }
}

class Game {
    constructor() {
        this.players = [];
        this.activeHands = [];
        this.currentHandId = 0;
        this.deck = new Deck().shuffle();
    }
    addPlayer(player) {
        this.players.push(player);
        // Create a hand for this player:
        this.activeHands.push(new Hand(player, 0, "active"));
    }
    deal() {
        // Draw card and assign to current hand
        this.activeHands[this.currentHandId].addCard(this.deck.drawOne());
    }
    nextHand() {
        this.currentHandId = (this.currentHandId + 1) % this.activeHands.length;
    }
    split() {
        // Insert the new, copied hand just after the current one:
        this.activeHands.splice(this.currentHandId+1, 0, 
            this.activeHands[this.currentHandId].copy());
    }
    bust() {
        // remove hand from active hands:
        this.activeHands[this.currentHandId].status = "busted";
        this.activeHands.splice(this.currentHandId, 1);
    }
}

// Start a game
var game = new Game();
game.addPlayer(new Player('Helen'));
game.addPlayer(new Player('John'));

// Deal a card to the first active hand
game.deal();
game.nextHand(); // move to second player
game.deal();
// ...etc.
// When you need to split the current hand
game.split();
// Then deal a card to both hands:
game.deal();
game.nextHand(); // move to second hand of same player
game.deal();
// ..etc.

您当然需要添加更多游戏逻辑和规则。但这可以成为满足您需求的模板。