javascript 扑克牌发牌员

ttvkxqim  于 2023-02-07  发布在  Java
关注(0)|答案(2)|浏览(152)

我正试图创建一个卡经销商,处理5卡时,一个按钮是在网页上点击。
基本上,我想创建一个有2个属性的卡片对象,"花色"和"值",一旦完成,我想创建一个有52个卡片对象的数组,这些卡片对象具有随机的花色和值,但理想情况下它们应该是唯一的。我希望在单击按钮时选择并显示5。我没有从我的按钮调用的函数中得到任何输出,我真的不明白为什么。
我真的是一个新的Javascript和教授教介绍类我现在是不是很有帮助,不幸的是。
下面是我目前的代码:

<head>
    <script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
  </head>
  <body>
    <h1>Robo Dealer</h1>

    <button onclick="dealHand();">Deal Hand</button>

    <hr />
    <div id="card_hand"></div>

    <script>
      // Declaring arrays for suits and values
      const suits = ["Hearts", "Spades", "Clubs", "Diamonds"];
      const values = [
        "Ace",
        2,
        3,
        4,
        5,
        6,
        7,
        8,
        9,
        10,
        "Jack",
        "Queen",
        "King",
      ];
      // Creating the card object
      function cards(value, suit) {
        this.value = value;
        this.suit = suit;
      }
      // Creating array of 52 card objects
      var deck = new Array();
      function getDeck() {
        for (i = 0; i < 52; i++) {
          let cardObject = new cards(
            values[Math.random()],
            suits[Math.random()]
          );
          deck.push(cardObject);
        }
        return deck;
      }
      //  Dealing hand of 5 card objects / outputting it to HTML
      const dealHand = () => {
        for (i = 0; i < 6; i++) {
          $("#card_hand").html(getDeck());
        }

        return false; // prevent page reload
      };
    </script>
  </body>
mftmpeh8

mftmpeh81#

下面是一个整理过的脚本,它包含一个Durstenfeld Shuffle 和一个包含52张牌的简单数组。 Shuffle 后的前5张牌将被分发:

function shfl(a){ // Durstenfeld shuffle
 for(let j,i=a.length;i>1;){
  j=Math.floor(Math.random()*i--);
  if (i!=j) [a[i],a[j]]=[a[j],a[i]]
 }
 return a
}
const suits = ["Hearts", "Spades", "Clubs", "Diamonds"],
  values = ["Ace",2,3,4,5,6,7,8,9,10,"Jack","Queen","King"],
  deck=[];
suits.forEach(s=>values.forEach(v=>
   deck.push(s+"-"+v)));

console.log(shfl(deck).slice(0,5));
ogq8wdun

ogq8wdun2#

好的,让我们看看如何使用对象来实现这一点。目前,您只是迭代了52次,并随机选择花色/值。您可能应该做的是,首先通过迭代花色和值来创建一副牌,对它们进行 Shuffle ,然后返回前五张牌(就像赌场所做的那样)。
这里有一些代码,你们可能不熟悉,但我会在最后加上一些注解和一些文档链接,我确实有点忘乎所以,但我希望其中一些是有用的。

// Cache the element that will hold the hand,
// and the button, and add a listener to the button
const cardHand = document.querySelector('#card_hand');
const button = document.querySelector('button');
button.addEventListener('click', play);

// Set up the suits and values
const suits = ['♥', '♠', '♣', '♦'];
const values=["Ace",2,3,4,5,6,7,8,9,10,"Jack","Queen","King"];

// https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
function shuffle(array) {
  let currentIndex = array.length,  randomIndex;
  while (currentIndex != 0) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;
    [array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
  }
  return array;
}

// Create a new deck of cards. Iterate over the suits first
// and have an inner loop that iterates over the values. That
// way you'll return a complete deck of 52 card objects. Each object
// is `{ value, suit }`. You may want to shuffle the deck at some point
// and you can use the Fisher/Yates algorithm for that (see above)
function createDeck() {
  const deck = [];
  for (i = 0; i < suits.length; i++) {
    for (j = 0; j < values.length; j++) {
      const card = { value: values[j], suit: suits[i] };
      deck.push(card);      
    }
  }
  return shuffle(deck);
}

// Create some cards HTML - `map` over the `hand` array
// and then, using a template string, create some HTML for
// each card. `map` returns an array so we need to join it up
// into a single string after the iteration is complete
function createHTML(hand) {
  return hand.map(card => {
    return (
      `<div class="card ${card.suit}">
        ${card.value} ${card.suit}
       </div>`
    );
  }).join('');
}

// Create the deck
const deck = createDeck();

function play() {

  // If there are enough cards in the deck
  // take off the first 5 and display them
  if (deck.length >= 5) {
    const hand = deck.splice(0, 5);
    cardHand.innerHTML = createHTML(hand);
  } else {
    cardHand.textContent = 'No cards remaining';
  }
}
#card_hand { display: grid; grid-template-columns: repeat(auto-fit, minmax(80px, 1fr)); gap: 0.5em;  }
.card { height: 100px; width: 70px; border: 1px solid #555; display: flex; justify-content: center; align-items: center; }
.♥, .♦ { color: red; }
<button type="button">Deal Hand</button>
<hr />
<div id="card_hand"></div>

其他文件

相关问题