Reputation: 39
I'm trying to learn about JavaScript, and I'm trying to create a basic comparison game, where I place card numbers in an array, I call 2 of them randomly, and I want to compare which one of the 2 random calls has higher value? Please help me. I've managed to code the program to deal 2 cards at random, I just need a guidance on how to compare the 2 cards drawn.
Thank you.
{
// 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);
}
Upvotes: 0
Views: 151
Reputation: 823
You should operate the card indexes
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) {...}
Upvotes: 0
Reputation: 6457
Try this:
if (cards.indexOf(playerCard) > cards.indexOf(dealerCard)) {
alert("Player wins!");
}
else {
alert("Dealer wins");
}
Upvotes: 4
Reputation: 3440
What's the problem?
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
}
cards is segregated.
Upvotes: 2
Reputation: 22728
You should work on improving your accept rate, but the primary way you check values against other values is with if
if(playerCard === dealerCard){
console.log('cards are the same');
} else {
console.log('cards are different');
}
Note the ===
. In most programming languages you test conditionals using ==
. In JavaScript, you can do that, but odd things like [] == false
will evaluate to true. ===
requires strict-compliance so [] === false
is, indeed, false.
Upvotes: 0