Kevin W
Kevin W

Reputation: 39

Javascript - How to compare if 2 indexes from an array?

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

Answers (4)

CruorVult
CruorVult

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

jalynn2
jalynn2

Reputation: 6457

Try this:

if (cards.indexOf(playerCard) > cards.indexOf(dealerCard)) {
   alert("Player wins!");
}
else {
   alert("Dealer wins");
}

Upvotes: 4

Norbert Pisz
Norbert Pisz

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

tkone
tkone

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

Related Questions