英文:
Javascript poker card dealer
问题
我正在尝试创建一个卡牌发牌程序,当网页上的按钮被点击时,会发出5张卡牌。
基本上,我想创建一个具有两个属性“花色”和“点数”的卡牌对象,一旦完成这个操作,我想创建一个包含52个具有随机花色和点数的卡牌对象的数组,但理想情况下它们应该都是唯一的。
在这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>
// 声明花色和点数的数组
const suits = ["Hearts", "Spades", "Clubs", "Diamonds"];
const values = [
"Ace",
2,
3,
4,
5,
6,
7,
8,
9,
10,
"Jack",
"Queen",
"King",
];
// 创建卡牌对象
function Card(value, suit) {
this.value = value;
this.suit = suit;
}
// 创建包含52个卡牌对象的数组
var deck = new Array();
function getDeck() {
for (i = 0; i < 52; i++) {
let cardObject = new Card(
values[Math.floor(Math.random() * values.length)],
suits[Math.floor(Math.random() * suits.length)]
);
deck.push(cardObject);
}
return deck;
}
// 发牌,显示到HTML
const dealHand = () => {
for (i = 0; i < 5; i++) {
$("#card_hand").append(getDeck()[i].value + " of " + getDeck()[i].suit + "<br>");
}
return false; // 防止页面重新加载
};
</script>
</body>
希望这对你有所帮助。
英文:
I am trying to create a card dealer that deals 5 cards when a button is clicked on the web page.
Basically, I want to create a card object with 2 attributes, 'suit' and 'value', once that is done I want to create an array of 52 card objects with random suits and values but ideally they should all be unique.
Out of those 52 card objects, I would like 5 to be selected and displayed when the button is clicked.
I am not getting any output from my function that is invoked from my button and I don't really understand why.
I am really new to Javascript and the professor teaching the intro class I am taking right now isn't very helpful, unfortunately.
Here is my current code:
<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>
答案1
得分: 1
以下是您脚本的整理版本,其中包括了Durstenfeld洗牌算法和一个包含52张牌的简单数组。洗牌后的前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));
英文:
Here is a tidied up version of your script, involving a Durstenfeld shuffle and a simple array containing the 52 cards deck. The first 5 cards of the shuffled deck are being dealt:
<!-- begin snippet:js console:true -->
<!-- language:lang-js -->
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));
<!-- end snippet -->
答案2
得分: 1
好的,以下是已翻译的部分:
OK, lets take a look at how you might approach this using objects.
(好的,让我们看看如何使用对象来处理这个。)
At the moment you're just iterating 52 times and selecting suits/values at random. What you probably should do is create the deck first by iterating over the suits and values, shuffle them, and then return the top five cards (like a casino would do).
(目前,您只是随机地迭代了52次并选择了花色和数值。您可能应该首先通过迭代花色和数值来创建牌组,然后洗牌,然后返回前五张牌(就像赌场会做的那样)。
There's a couple of bits of code here that you might not be familiar with but I'll include some notes, and some links to documentation at the end.
(这里有一些代码片段,您可能不太熟悉,但我会在末尾附上一些说明和一些文档链接。)
// 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 cardHand = document.querySelector('#card_hand');)
const button = document.querySelector('button');
(const button = document.querySelector('button');)
button.addEventListener('click', play);
(button.addEventListener('click', play);)
// Set up the suits and values
(// 设置花色和数值)
const suits = ['♥', '♠', '♣', '♦'];
(const suits = ['♥', '♠', '♣', '♦'];)
const values=["Ace",2,3,4,5,6,7,8,9,10,"Jack","Queen","King"];
(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
(// https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array)
function shuffle(array) {
(function shuffle(array) {)
let currentIndex = array.length, randomIndex;
(let currentIndex = array.length, randomIndex;)
while (currentIndex != 0) {
(while (currentIndex != 0) {)
randomIndex = Math.floor(Math.random() * currentIndex);
(randomIndex = Math.floor(Math.random() * currentIndex);)
currentIndex--;
(currentIndex--;)
[array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
([array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex];)
}
return array;
(}
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)
(// 创建一副新的牌组。首先迭代花色
// 然后有一个内部循环来迭代数值。这样
// 你将返回一副完整的52张卡牌。每个对象
// 是{ value, suit }
。您可能希望在某个时候洗牌
// 你可以使用Fisher/Yates算法来洗牌(见上文)
function createDeck() {
(function createDeck() {)
const deck = [];
(const deck = [];)
for (i = 0; i < suits.length; i++) {
(for (i = 0; i < suits.length; i++) {)
for (j = 0; j < values.length; j++) {
(for (j = 0; j < values.length; j++) {)
const card = { value: values[j], suit: suits[i] };
(const card = { value: values[j], suit: suits[i] };)
deck.push(card);
(deck.push(card);)
}
}
return shuffle(deck);
(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
(// 创建一些卡牌的HTML - 在hand
数组上使用map
// 然后,使用模板字符串,为每张卡片创建一些HTML
// map
返回一个数组,所以我们需要在迭代完成后将其连接起来
// 成一个单一的字符串
function createHTML(hand) {
(function createHTML(hand) {)
return hand.map(card => {
(return hand.map(card => {)
return (
`<div class="card ${card.suit}">
${card.value} ${card.suit}
</div>`
);
(return (
`<div class="card ${card.suit}">
${card.value} ${card.suit}
</div>`
);)
}).join('');
(}).join('');)
}
// Create the deck
(// 创建牌组)
const deck = createDeck();
(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) {
(if (deck.length >= 5) {)
const hand = deck.splice(0, 5);
(const hand = deck.splice(0, 5);)
cardHand.innerHTML = createHTML(hand);
(cardHand.innerHTML = createHTML(hand);)
} else {
cardHand.textContent = 'No cards remaining';
(else {
cardHand.textContent = 'No cards remaining';)
}
}
(}
// CSS部分未包括在内,因为它主要是样式信息。
// 附加文档链接也未包括在内,因为它们是链接到文档的引用。
英文:
OK, lets take a look at how you might approach this using objects.
At the moment you're just iterating 52 times and selecting suits/values at random. What you probably should do is create the deck first by iterating over the suits and values, shuffle them, and then return the top five cards (like a casino would do).
There's a couple of bits of code here that you might not be familiar with but I'll include some notes, and some links to documentation at the end. I did get a little carried away with this but I hope that some of it is useful.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
// 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';
}
}
<!-- language: lang-css -->
#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; }
<!-- language: lang-html -->
<button type="button">Deal Hand</button>
<hr />
<div id="card_hand"></div>
<!-- end snippet -->
Additional documentation
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论