如何显示二十一点卡洗牌结果?

时间:2019-01-09 03:58:44

标签: javascript dom blackjack

我正在制作一个简单的二十一点游戏。现在,我进行了洗牌功能。为什么单击新游戏按钮后,卡片摇动的结果没有出现在innerText中?

我已经阅读并重复了该代码,并更正了变量和分号的位置,但没有效果。

/*
  Blackjack Game
*/

//Card Variables
let suits = ['Hearts', 'Clubs', 'Diamonds', 'Spades'],
  values = ['Ace', 'King', 'Queen', 'Jack',
    'Ten', 'Nine', 'Eight', 'Seven', 'Six',
    'Five', 'Four', 'Three', 'Two'
  ];

//DOM Variables
let textArea = document.getElementById('text-area'),
  newGameButton = document.getElementById('new-game-button'),
  hitButton = document.getElementById('hit-button'),
  stayButton = document.getElementById('stay-button');

//Game Variables
let gameStarted = false,
  gameOver = false,
  playerWon = false,
  dealerCard = [],
  playerCard = [],
  dealerScore = 0,
  playerScore = 0,
  deck = [];

hitButton.style.display = 'none';
stayButton.style.display = 'none';
showStatus();

newGameButton.addEventListener('click', function() {
  gameStarted = true;
  gameOver = false;
  playerWon = false;

  deck = createDeck();
  shuffleDeck(deck);
  dealerCards = [getNextCard(), getNextCard()];
  playerCards = [getNextCard(), getNextCard()];

  newGameButton.style.display = 'none';
  hitButton.style.display = 'inline';
  stayButton.style.display = 'inline';
  showStatus();
});

function createDeck() { //Membuat deck dari 52 kartu
  let deck = [];
  for (let suitIdx = 0; suitIdx < suits.length; suitIdx++) {
    for (let valueIdx = 0; valueIdx < values.length; valueIdx++) {
      let card = {
        suit: suits[suitIdx],
        value: values[valueIdx]
      }
      deck.push(card);
    }
  }
  return deck;
}

function shuffleDeck(deck) {
  for (let i = 0; i < deck.length; i++) {
    let swapIdx = Math.trunc(Math.random() * deck.length);
    let tmp = deck[swapIdx];
    deck[swapIdx] = deck[i];
    deck[i] = tmp;
  }
}

function getCardString(card) {
  return card.value + ' of ' + card.suit;
}

function getNextCard() {
  return deck.shift();
}

function showStatus() {
  if (!gameStarted) {
    textArea.innerText = 'Welcome to Blackjack!';
    return;
  }
}

for (var i = 0; i < deck.length; i++) {
  textArea.innerText = "\n" + getCardString(deck[i]);
}
<h1 id="title">Welcome to Blackjack!</h1>
<h4>by Andrean Hendy</h4>

<p id="text-area">Welcome to Blackjack!</p>
<button id="new-game-button">New Game!</button>
<button id="hit-button">Hit!</button>
<button id="stay-button">Stay</button>

在此处检查代码@plunk:http://embed.plnkr.co/rAzcbmTyH8vIRBI3appX/

我期望的是在改组后显示52张套牌的结果。

2 个答案:

答案 0 :(得分:0)

在“新游戏按钮”按钮单击事件侦听器中,您永远不会更改“文本区域” innerText。唯一可以实现此目的的子方法是showStatus,但是在这种情况下,if(!gameStarted)条件可以防止我们更改innerText。

不确定我是否正确理解了您的逻辑,但是单击“新游戏”按钮后,更新后的结果将向您显示。

newGameButton.addEventListener('click', function(){
  // ...
  setDeckText();
});

// ...

function setDeckText() {
  for(var i = 0; i < deck.length; i++){
    textArea.innerText = "\n" + getCardString(deck[i]);
  }
}

答案 1 :(得分:0)

问题已解决。循环的最后一行应该放在showStatus()函数块中。但是我以前没有。