我正在尝试学习JavaScript,我正在尝试创建一个基本的比较游戏,我将卡号放在一个数组中,我随机调用其中的两个,我想比较其中的哪两个随机通话有更高的价值?请帮我。我已经设法编写程序来随机处理2张卡片,我只需要一个如何比较2张卡片的指导。
谢谢。
{
// This is my attempt to create a basic game for a simplified version of ta siau
//where players choose a card, and compares it with dealer's card. Bigger card wins the round
var cards = [2,3,4,5,6,7,8,9,10,"jack","queen","king","ace"]; //available cards in the deck
confirm("start game now?");
var playerCard = cards[Math.floor(Math.random() * cards.length)]; //choose a random card for player
console.log(playerCard);
var dealerCard = cards[Math.floor(Math.random() * cards.length)]; //choose a random card for dealer
console.log(dealerCard);
}
答案 0 :(得分:4)
试试这个:
if (cards.indexOf(playerCard) > cards.indexOf(dealerCard)) {
alert("Player wins!");
}
else {
alert("Dealer wins");
}
答案 1 :(得分:2)
有什么问题?
var playerVal=Math.floor(Math.random() * cards.length);
var playerCard = cards[playerVal];
var dealerVal=Math.floor(Math.random() * cards.length);
var dealerCard = cards[dealerVal];
if(playerVal>dealerVal){
//player wins
}
卡被隔离。
答案 2 :(得分:0)
您应该努力提高接受率,但是根据其他值检查值的主要方法是使用if
if(playerCard === dealerCard){
console.log('cards are the same');
} else {
console.log('cards are different');
}
请注意===
。在大多数编程语言中,您使用==
测试条件。在JavaScript中,你可以这样做,但像[] == false
这样的奇怪的东西会评估为真。 ===
要求严格遵守,因此[] === false
确实是错误的。
答案 3 :(得分:0)
您应该操作卡片索引
var playerCardIndex = Math.floor(Math.random() * cards.length)
var playerCard = cards[playerCardIndex];
var dealerCardIndex = Math.floor(Math.random() * cards.length)
var dealerCard = cards[dealerCardIndex]
if (playerCardIndex > dealerCardIndex) {...}