johnsmith1 johnsmith1 - 10 months ago 106
Javascript Question

JavaScript Card Game

I am trying to create my first JavaScript and having understood the basics I am trying to make a card game, player 1 and player 2 are given a random card and the person with the highest card wins. Below is a simple array for a suit of cards (spades) I have saved the image file for the cards in a folder called images as seen below, my question is how do I get this array to display the cards, and to randomly assign a card to 2 players, and the highest card wins. I understand an If/else/else if statement may be needed to determine the winner, but how do I go about distributing my array of cards to 2 players. Would it be some sort of function, as I have been reading about these, anyway below is the array I have created, any code ideas would be appreciated thank you.

var cards = []; //variable for cards

cards [0] = 'images/aceofspades.jpg';
cards [1] = 'images/twoofspades.jpg';
cards [2] = 'images/threeofspades.jpg';
cards [3] = 'images/fourofspades.jpg';
cards [4] = 'images/fiveofspades.jpg';
cards [5] = 'images/sixofspades.jpg';
cards [6] = 'images/sevenofspades.jpg';
cards [7] = 'images/eightofspades.jpg';
cards [8] = 'images/nineofspades.jpg';
cards [9] = 'images/tenofspades.jpg';
cards [10] = 'images/jackofspades.jpg';
cards [11] = 'images/queenofspades.jpg';
cards [12] = 'images/kingofspades.jpg';

This bit of code below is my idea of what to do next but I am not so sure if this is correct? thanks

function choose (cards);
document.image [cards].src = cardsimage [cards];


You set the src using document.getElementById(id).src = cards[0];.

function startRound() {
 var p1_card_index = Math.floor(Math.random() * 13);// random bt 0-13
 var p2_card_index = p1_card_index;
 // make sure same card isn't drawn again
 while (p2_card_index == p1_card_index) {
  p2_card_index = Math.floor(Math.random() * 13);
 // set the src and the alt of the <img/>
 document.getElementById('c1').src = cards[p1_card_index];
 document.getElementById('c1').alt = cards[p1_card_index];
 document.getElementById('c2').src = cards[p2_card_index];
 document.getElementById('c2').alt = cards[p2_card_index];

 // determine who won and give them points
 if (p1_card_index > p2_card_index) {
  document.getElementById('w1').innerHTML = p1_wins;
 } else {
  document.getElementById('w2').innerHTML = p2_wins;