Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 05-17-2011, 02:30 PM   PM User | #1
jekernin
New to the CF scene

 
Join Date: May 2011
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
jekernin is an unknown quantity at this point
Macintosh help with cardgame

hello internet!

I'm trying to make a card game using javascript, and because my skills are... non existent.. i'm having a little trouble

i have a full deck of cards, and i'm looking for a code that'll allow me to click a "deal" button, and have one card dealt to the computer, and three cards to the player.

I have an array consisting of all my cards (and i have the images for each one), i have a shuffle function that i got working from a different project that i did in class. But from here I really have no idea.. i've been trying to hours and hours to do this and any help would be appreciated..

thanks in advance
jekernin is offline   Reply With Quote
Old 05-17-2011, 02:45 PM   PM User | #2
bullant
Banned

 
Join Date: Feb 2011
Posts: 2,699
Thanks: 13
Thanked 395 Times in 395 Posts
bullant is on a distinguished road
If you want to adopt an object oriented approach you could create a javascript deck of cards object with a property being an array of the cards and then object methods to deal and shuffle the cards. The method to deal the cards would generate a random number from 0 to the number of cards left in the deck -1 and then remove the card at that random number index in the cards array as it is "dealt" to a player.

Using an object oriented approach then allows you to use that deck of cards object in other javascript applications very easily.
bullant is offline   Reply With Quote
Old 05-17-2011, 03:36 PM   PM User | #3
Sciliano
Regular Coder

 
Join Date: Nov 2009
Posts: 247
Thanks: 4
Thanked 22 Times in 22 Posts
Sciliano is an unknown quantity at this point
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Poker Fun - Basic Version</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">

/* Copyright 2008, Michael J. Hill. www.javascript-demos.com All rights reserved. You may USE this code and markup AS IS. */
/* This entire notice must be kept intact, and is your license to USE this document for free. */

	var nHands = 5;  // number of players;
	var perHand = 7;  // 1 to 7 cards; 
	var nDecks = 3;  // you may use a "shoe" of several decks; 
	var dealPace = .1   // a new card is dealt every n seconds; 
	var toEndOfDeck = true;  // continue to deal hands until not enough cards remain, then start a new deck / shoe;

/* Do NOT edit below this line */

	var card = ["2","3","4","5","6","7","8","9","10","J","Q","K","A"];
	var deck = [];	
	var dealOrder = [];
	var newDeckMsgBox = "";
	var nAnimate = "";
	var currDealer = "";
	var nextHand = "";
	var leftPadding = "";
	var toHand = 1;
	var nProgress = 0;	
	var nCards = 0;	
	var haveDeck = true;
	
	function deal(nHand){

		var nextCard = "";		
		if (deck[0] < 14) 
			{
			 nextCard = "<span class='red'>" + card[deck[0]-1] + "&hearts;" +  "<\/span>";			 	 	
			}
		else if (deck[0] > 13 && deck[0] < 27)  
			{
			 nextCard = "<span class='black'>" + card[deck[0]-14] + "&clubs;" + "<\/span>";			 		 			 
			}
		else if (deck[0] > 26 && deck[0] < 40)  
			{
			 nextCard = "<span class='red'>" + card[deck[0]-27] + "&diams;" + "<\/span>";			 							 
			}
		else if (deck[0] > 39) 
			{
			 nextCard = "<span class='black'>" + card[deck[0]-40] + "&spades;" + "<\/span>";			 					 			 
			}						
		document.getElementById('hand'+nHand).innerHTML += nextCard;	
		deck.shift();	
		nCards++;			
	}

	function dealNextCard(nCard){

		if (toHand > nHands)
			{
			 toHand = 1;
			}	
		deal(dealOrder[toHand-1]);
		toHand++;	
		animateDeal();	
	}

	function animateDeal(){

		if (nCards != nHands * perHand)
			{
			 setTimeout("dealNextCard()", dealPace * 1000);	
			}			
		if (nCards == nHands * perHand)
			{
			 for (i=1; i<nHands+1; i++)
				{
				 document.getElementById('hand'+i).onclick = function()
					{
			 	 	 setDealer(this);
					}
				}								
			}		
	}

	function cutTheDeck(){		
		
		var cutAt = parseInt(Math.random() * deck.length / 2);
		var temp = [];
		temp[0] = [];
		temp[1] = [];		
		for (i=0; i<(deck.length / 2) - cutAt; i++)
			{
			 temp[0][temp[0].length] = deck[i];
			}		
		for (i = (deck.length / 2) - cutAt; i<deck.length; i++)
			{
			 temp[1][temp[1].length] = deck[i];			 
			}		
		deck = (temp[1].join() + "," + temp[0].join()).split(",");			
	}

	function shuffle(){

		for (i=0; i<deck.length; i++)
			{
			 var tmp1 = parseInt(Math.random()*deck.length);
			 var tmp2 = parseInt(Math.random()*deck.length);
			 var tmp3 = deck[tmp1];
			 deck[tmp1] = deck[tmp2];
			 deck[tmp2] = tmp3;
			}
	}

	function shuffleDeck(){
		
		shuffle();
		deck.reverse();
		cutTheDeck();
		shuffle();	
		cutTheDeck()
		shuffle();
		deck.reverse();		
	}

	function dealHands(){		

		for (i=1; i<nHands+1; i++)
			{
			 document.getElementById('hand'+i).onclick = function(){}
			 document.getElementById('hand'+i).innerHTML = "";								
			}
		toHands = 1;
		nCards = 0;
		if (toEndOfDeck)
			{
			 if (deck.length < nHands * perHand)
				{
				 initDeck();
				 newDeckMsgBox.style.display = "";
				 setTimeout("newDeckMsgBox.style.display = 'none'", 1250);
				 setTimeout("shuffleDeck(); animateDeal()", 1250);				 			 
				}
			 else 	{
				 animateDeal();
				}
			}
		else	{
			 if (!haveDeck)
				{
				 initDeck();	
			 	 newDeckMsgBox.style.display = "";
			 	 setTimeout("newDeckMsgBox.style.display = 'none'", 1250);
				 setTimeout("shuffleDeck(); animateDeal()", 1250);					 	 		 	
				}
			 else	{				 		
			 	 animateDeal();	
				}
			 haveDeck = false;		 
			}				
	}	

	function initDeck(){

		deck.length = 0;
		for (i=0; i<nDecks; i++)
			{
			 for (n=1; n<=52; n++)
				{
				 deck[deck.length] = n;
				}
			}			
	}

	function setDealer(nPlayer){

		var n = nPlayer.id.replace("hand","");
		var t = currDealer.replace("hand","");
		if (currDealer != "")
			{
			 document.getElementById(currDealer).className = "playerDisplay";			 
			 document.getElementById('player'+t).innerHTML = t;
			 document.getElementById('player'+t).style.paddingLeft = leftPadding +"px";
			}
		document.getElementById(nPlayer.id).className = "dealerDisplay";		
		document.getElementById('player'+n).innerHTML = "Dealer";
		document.getElementById('player'+n).style.paddingLeft = (leftPadding - 40) + "px";
		document.getElementById('dealBtn').disabled = false;
		currDealer = nPlayer.id;	
		toHand = currDealer.replace(/hand/,"");	
		toHand++;
		toHand > nHands	? toHand = 1 : null;		
	}

	function init(){

		var syntax = "deck";
		nDecks < 1 ? nDecks = 1 : null;
		nDecks > 1 ? syntax = "shoe" : null;
		var root = document.getElementsByTagName('body')[0];
		var nCeiling = document.getElementById('handContainer');
		newDeckMsgBox = document.createElement('div');
		newDeckMsgBox.id = "nMsg";
		newDeckMsgBox.className = "newDeck";
		newDeckMsgBox.style.left = ((screen.width / 2) - 125) + "px";
		newDeckMsgBox.style.display = "none";
		newDeckMsgBox.innerHTML = "Shuffling a new " + syntax + "..."
		root.insertBefore(newDeckMsgBox,nCeiling);	
		var nContainer = document.getElementById('handContainer');	
		perHand > 7 ? perHand = 7 : null;
		perHand < 1 ? perHand = 1 : null;	
		if (nHands * perHand <= nDecks * 52)
			{
			 for (i=1; i<nHands+1; i++)
				{
				 var playerIndex = document.createElement('div');
				 playerIndex.className = "playerNumber";
				 playerIndex.id = "player"+i;
				 playerIndex.innerHTML = i;
			 	 nextHand =  document.createElement('div');
			 	 nextHand.id = "hand"+i;
				 nextHand.className = "playerDisplay";
				 nContainer.appendChild(playerIndex);
				 nContainer.appendChild(nextHand);	
				 nextHand.onclick = function()
					{
					 setDealer(this);
					}			
				}
			 leftPadding = document.getElementById('hand1').offsetLeft - 35;
			 for (i=1; i<nHands+1; i++)
				{
				 document.getElementById('player'+i).style.paddingLeft = leftPadding +"px";				 
				}
			}
		else 	{
			 alert('Too many players \nor cards per hand');
			 return;
			}
		for (i=1; i<nHands+1; i++)
			{
			 dealOrder[dealOrder.length] = i;
			}	
		if (nHands == 1)
			{
			 document.getElementById('dealBtn').disabled = false;
			 document.getElementById('dealerMsg').style.visibility = "hidden";
			 document.getElementById('hand1').onclick = function(){}
			}
		else	{
			 document.getElementById('dealBtn').disabled = true;
			}
		initDeck();
		shuffleDeck();	
	}

	navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);

</script>
<style type="text/css">

	 body {margin-top: 65px; background-color: #f5f5f5;}
	 h3 {font-family: tahoma; text-align: center;}
	.playerDisplay {margin-top: -30px; width: 325px; height: 25px; margin-left: auto; margin-right: auto; margin-bottom: 35px; font-size: 16pt; background-color: #f6eabc; padding: 5px; border: 1px solid black; text-align: center; cursor: default;}
	.dealerDisplay {margin-top: -30px; width: 325px; height: 25px; margin-left: auto; margin-right: auto; margin-bottom: 35px; font-size: 16pt; background-color: #87ceeb; padding: 5px; border: 1px solid black; text-align: center; cursor: default;}
	.playerNumber {font-size: 14pt;}
	.newDeck {width: 220px; font-family: arial; font-size: 14pt; background-color: #ff69b4; text-align: center; border: 1px solid black; position: absolute; top: 25px; padding: 5px;}
	.dealBtn {background-color: #ffffff; border: 1px solid black; font-family: arial; font-size: 10pt; font-weight: bold; cursor: pointer; display: block; margin-left: auto; margin-right: auto; margin-top: 35px; margin-bottom: 0px; padding-left: 5px; padding-right: 5px; }
	.red {font-family: arial; color: #ff0000; margin-left: 8px; margin-right: 8px;}
	.black {font-family: arial; color: #000000; margin-left: 8px; margin-right: 8px;}

</style>
</head>
<body>
	<h3 id="dealerMsg">Choose a Dealer by Clicking a Player</h3>

	<div id="handContainer"></div>
	
	<form action = "">
		<input type="button" value="Deal" class="dealBtn" id="dealBtn" onclick="dealHands()" disabled>
	</form>

</body>
</html>
Sciliano is offline   Reply With Quote
Old 05-18-2011, 11:39 AM   PM User | #4
bullant
Banned

 
Join Date: Feb 2011
Posts: 2,699
Thanks: 13
Thanked 395 Times in 395 Posts
bullant is on a distinguished road
Quote:
i have a full deck of cards, and i'm looking for a code that'll allow me to click a "deal" button, and have one card dealt to the computer, and three cards to the player.
Maybe use this demo deck of cards object as a starting point.

The object constructor is

Code:
function cardStack(cardPicsO,numDecks)
where

cardPicsO = array of preloaded card images and the nominal value of each card. Face cards are worth 10 points.

numDecks = the number of 52 card decks you want in your stack of cards.

cardPics (see demo) is a 53 element 2D array where each row contains the path to the image for the card and the nominal value of the card. The first row is the back of the card image.

The cardStack object has a method to shuffle the cards in the stack and a method to deal however many you want at a time either face up or face down.

this.dealCards=function(num,faceDown) is the method to call when you want to deal some cards.

num = the number of cards you want to deal

faceDown is a boolean (true or false) for whether you want the cards dealt face up or face down.

When you click "New game", 3 cards are dealt face up to to the "player" and 1 card is dealt face down to the "computer".

For testing purposes the total of each player's hand is displayed above their cards.

If you use this object, you will need to write your own code to handle the reshuffling of the cardstack when the last card in the stack is dealt and any other functionality you need.

This cardStack object can be used on other card game applications as well if required.

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <title></title>
        <style type="text/css">
            #tabletop {
                width: 900px;
                border: 3px solid black;
                background-color: green;
                margin: 20px auto 0px auto;
                padding: 0px 0px 0px 0px;
                overflow: hidden;
            }
            #computerBox {
                width: 40%;
                border: 1px solid red;
                margin: 20px 0px 20px 20px;
                padding: 10px 10px 10px 10px;
                min-height: 150px;
                float: left;
            }
            #playerBox {
                width: 40%;
                border: 1px solid red;
                margin: 20px 20px 20px 0px;
                padding: 10px 10px 10px 10px;
                min-height: 150px;
                float: right;
            }
            #controlsContainer {
                clear: both;
            }
        </style>
        <script type="text/javascript">
            var cardPics = [
                ['back-blue-150-1.png',0],['clubs-a-150.png',1],['clubs-2-150.png',2],['clubs-3-150.png',3],['clubs-4-150.png',4],['clubs-5-150.png',5],['clubs-6-150.png',6],['clubs-7-150.png',7],['clubs-8-150.png',8],['clubs-9-150.png',9],['clubs-10-150.png',10],['clubs-j-150.png',10],['clubs-q-150.png',10],['clubs-k-150.png',10],['diamonds-a-150.png',1],['diamonds-2-150.png',2],['diamonds-3-150.png',3],['diamonds-4-150.png',4],['diamonds-5-150.png',5],['diamonds-6-150.png',6],['diamonds-7-150.png',7],['diamonds-8-150.png',8],['diamonds-9-150.png',9],['diamonds-10-150.png',10],['diamonds-j-150.png',10],['diamonds-q-150.png',10],['diamonds-k-150.png',10],['hearts-a-150.png',1],['hearts-2-150.png',2],['hearts-3-150.png',3],['hearts-4-150.png',4],['hearts-5-150.png',5],['hearts-6-150.png',6],['hearts-7-150.png',7],['hearts-8-150.png',8],['hearts-9-150.png',9],['hearts-10-150.png',10],['hearts-j-150.png',10],['hearts-q-150.png',10],['hearts-k-150.png',10],['spades-a-150.png',1],['spades-2-150.png',2],['spades-3-150.png',3],['spades-4-150.png',4],['spades-5-150.png',5],['spades-6-150.png',6],['spades-7-150.png',7],['spades-8-150.png',8],['spades-9-150.png',9],['spades-10-150.png',10],['spades-j-150.png',10],['spades-q-150.png',10],['spades-k-150.png',10]
            ];
            var cardPicsO = new Array();
            for(i=0; i < cardPics.length; i++){
                cardPicsO[i] = new Image();
                cardPicsO[i].src = cardPics[i][0];
                cardPicsO[i].value = cardPics[i][1];
            }
            function cardStack(cardPicsO,numDecks){
                this.cardPics = cardPicsO;
                this.numDecks = numDecks;
                this.shuffledIndxs = [];
                this.curCardIndx = 1;
                this.shuffle=function(){
                    this.curCard = 1;
                    var s = [];
                    while (this.shuffledIndxs.length) s.push(this.shuffledIndxs.splice(Math.random() * this.shuffledIndxs.length, 1));
                    while (s.length) this.shuffledIndxs.push(s.pop());
                }
                this.init=function(){
                    for(i=1; i <= this.numDecks*52; i++){
                        this.shuffledIndxs.push(i);
                        if(i > 52){ //extend this.cardPics if more than 1 deck in the stack
                            this.cardPics.push(this.cardPics[i-52]);
                        }
                    }
                    this.shuffle();    
                }
                this.init();
                this.dealCards=function(num,faceDown){
                    var cards = new Array();
                    for(i=0; i < num; i++){
                        if(this.curCardIndx > this.shuffledIndxs.length){
                            this.shuffle();
                        }  else {
                            if(faceDown){
                                this.cardPics[this.shuffledIndxs[this.curCardIndx]].src = this.cardPics[0].src;
                            }
                            cards.push(this.cardPics[this.shuffledIndxs[this.curCardIndx]]);
                        }
                        ++this.curCardIndx;
                    }
                    return cards;
                }
            }
            //-----------------------------------------------------
            function startGame(){
                clearPlayerCards(computerBoxO);
                clearPlayerCards(playerBoxO);
                //deal 3 cards face up to the player
                var total = 0;
                var newCards = deck.dealCards(3,false);
                for(i=0; i < newCards.length; i++){
                    var newImg = document.createElement('img');
                    newImg.src = newCards[i].src;
                    playerBoxO.appendChild(newImg);
                    total += newCards[i].value;
                }
                document.getElementById('playerHandTotal').innerHTML = 'Total = '+total;
                //deal 1 card face down to the computer
                var total = 0;
                var newCards = deck.dealCards(1,true);
                for(i=0; i < newCards.length; i++){
                    var newImg = document.createElement('img');
                    newImg.src = newCards[i].src;
                    computerBoxO.appendChild(newImg);
                    total += newCards[i].value;
                }
                document.getElementById('computerHandTotal').innerHTML = 'Total = '+total;

            }
            function clearPlayerCards(obj){
                var imgsO = obj.getElementsByTagName('img');
                while(imgsO.length > 0){
                    imgsO[0].parentNode.removeChild(imgsO[0]); 
                    imgsO = obj.getElementsByTagName('img');
                }
            }
            window.onload=function(){
                computerBoxO = document.getElementById('computerBox');
                playerBoxO = document.getElementById('playerBox');
                document.getElementById('btnNewGame').onclick=startGame;
                deck = new cardStack(cardPicsO,1);
            }
        </script>
    </head>
    <body>
        <div id="tabletop">
            <fieldset id="computerBox">
                <legend>Computer</legend>
                <div id="computerHandTotal"></div>
            </fieldset>
            <fieldset id="playerBox">
                <legend>Player</legend>
                <div id="playerHandTotal"></div>
            </fieldset>
            <div id="controlsContainer">
                <button id="btnNewGame">New game</button>
            </div>
        </div>
    </body>
</html>

Last edited by bullant; 05-18-2011 at 12:55 PM..
bullant is offline   Reply With Quote
Old 05-19-2011, 06:07 AM   PM User | #5
bullant
Banned

 
Join Date: Feb 2011
Posts: 2,699
Thanks: 13
Thanked 395 Times in 395 Posts
bullant is on a distinguished road
oooops ....the earlier demo had an undesirable "feature" in it .

This demo is now ok.
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <title></title>
        <style type="text/css">
            #tabletop {
                width: 900px;
                border: 3px solid black;
                background-color: green;
                margin: 20px auto 0px auto;
                padding: 0px 0px 0px 0px;
                overflow: hidden;
            }
            #computerBox {
                width: 40%;
                border: 1px solid red;
                margin: 20px 0px 20px 20px;
                padding: 10px 10px 10px 10px;
                min-height: 150px;
                float: left;
            }
            #playerBox {
                width: 40%;
                border: 1px solid red;
                margin: 20px 20px 20px 0px;
                padding: 10px 10px 10px 10px;
                min-height: 150px;
                float: right;
            }
            #controlsContainer {
                clear: both;
            }
            legend {
                font-family: tahoma, verdana, arial, sans-serif;
                font-size: 0.8em;
                color: burlywood;
                margin: 0px 0px 0px 0px;
                padding: 0px 10px 0px 10px;
            }
            .totals {
                font-family: tahoma, verdana, arial, sans-serif;
                font-size: 0.9em;
                color: burlywood;
                font-weight: bold;
                margin: 0px 0px 20px 0px;
                padding: 0px 0px 0px 0px;
            }
        </style>
        <script type="text/javascript">
            var cardPics = [
                ['clubs-a-150.png',1],['clubs-2-150.png',2],['clubs-3-150.png',3],['clubs-4-150.png',4],['clubs-5-150.png',5],['clubs-6-150.png',6],['clubs-7-150.png',7],['clubs-8-150.png',8],['clubs-9-150.png',9],['clubs-10-150.png',10],['clubs-j-150.png',10],['clubs-q-150.png',10],['clubs-k-150.png',10],['diamonds-a-150.png',1],['diamonds-2-150.png',2],['diamonds-3-150.png',3],['diamonds-4-150.png',4],['diamonds-5-150.png',5],['diamonds-6-150.png',6],['diamonds-7-150.png',7],['diamonds-8-150.png',8],['diamonds-9-150.png',9],['diamonds-10-150.png',10],['diamonds-j-150.png',10],['diamonds-q-150.png',10],['diamonds-k-150.png',10],['hearts-a-150.png',1],['hearts-2-150.png',2],['hearts-3-150.png',3],['hearts-4-150.png',4],['hearts-5-150.png',5],['hearts-6-150.png',6],['hearts-7-150.png',7],['hearts-8-150.png',8],['hearts-9-150.png',9],['hearts-10-150.png',10],['hearts-j-150.png',10],['hearts-q-150.png',10],['hearts-k-150.png',10],['spades-a-150.png',1],['spades-2-150.png',2],['spades-3-150.png',3],['spades-4-150.png',4],['spades-5-150.png',5],['spades-6-150.png',6],['spades-7-150.png',7],['spades-8-150.png',8],['spades-9-150.png',9],['spades-10-150.png',10],['spades-j-150.png',10],['spades-q-150.png',10],['spades-k-150.png',10]
            ];
            //preload face up card images (52)
            var cardPicsO = new Array();
            for(i=0; i < cardPics.length; i++){
                cardPicsO[i] = new Image();
                cardPicsO[i].src = './cards/cardImages/150/'+cardPics[i][0];
                cardPicsO[i].value = cardPics[i][1];
            }
            //preload the face down image
            var backCardO = new Image();
            backCardO.src = './cards/cardImages/150/back-blue-150-1.png';
            // ** Start of Object
            function cardStack(cardPicsO,backCardO,numDecks){
                this.cardPics = cardPicsO;
                this.backCard = backCardO;
                this.numDecks = numDecks;
                this.shuffledIndxs = [];
                this.curCardIndx = 0;
                this.shuffle=function(){
                    this.curCardIndx = 0;
                    var s = [];
                    while (this.shuffledIndxs.length) s.push(this.shuffledIndxs.splice(Math.random() * this.shuffledIndxs.length, 1));
                    while (s.length) this.shuffledIndxs.push(s.pop());
                }
                this.init=function(){
                    for(i=0; i < this.numDecks*52; i++){
                        this.shuffledIndxs.push(i);
                        if(i > 51){ //extend this.cardPics if more than 1 deck in the stack
                            this.cardPics.push(this.cardPics[i-52]);
                        }
                    }
                    this.shuffle();
                }
                this.init();
                this.getCards=function(num,faceDown){
                    var cards = [];
                    for(i=0; i < num; i++){
                        if(this.curCardIndx > (this.shuffledIndxs.length-1)){ //reached end of stack
                            this.shuffle();
                            this.curCardIndx = -1;
                            --i;
                        }  else { //deal the cards
                            if(faceDown) {
                                var dealtBackCard = new Image();
                                dealtBackCard.src =  this.backCard.src;
                                dealtBackCard.value = this.cardPics[this.shuffledIndxs[this.curCardIndx]].value;
                                dealtBackCard.facedown = true;
                                dealtBackCard.cardSrc = this.cardPics[this.shuffledIndxs[this.curCardIndx]].src;
                                cards.push(dealtBackCard);
                            } else {
                                cards.push(this.cardPics[this.shuffledIndxs[this.curCardIndx]]);
                                cards[cards.length-1].facedown = false;
                            }
                        }
                        ++this.curCardIndx;
                    }
                    return cards;
                }
            }
            //End of Object
            //-----------------------------------------------------
            function startGame(){
                clearPlayerCards(computerBoxO);
                clearPlayerCards(playerBoxO);
                //deal 3 cards face up to the player            
                dealCards(3,false,'player');
                //deal 1 card face down to the computer
                dealCards(1,true,'computer');
            }
            function clearPlayerCards(obj){
                var imgsO = obj.getElementsByTagName('img');
                while(imgsO.length > 0){
                    imgsO[0].parentNode.removeChild(imgsO[0]); 
                    imgsO = obj.getElementsByTagName('img');
                }
            }
            function turnComputersCards(player){
                obj = (player == 'player')? playerBoxO : computerBoxO;
                var imgsO = obj.getElementsByTagName('img');
                for(i=0; i < imgsO.length; i++){
                    if(imgsO[i].facedown){
                        imgsO[i].src = imgsO[i].cardSrc;
                    }
                }
            }
            function dealCards(numCards,faceDown,player){
                switch (faceDown){
                    case true : //deal cards face down
                        total = 0;
                        var newCards = deck.getCards(numCards,true);
                        for(i=0; i < newCards.length; i++){
                            var newImg = document.createElement('img');
                            newImg.src = newCards[i].src;
                            newImg.facedown = newCards[i].facedown;
                            newImg.cardSrc = newCards[i].cardSrc;
                            if(player == 'player'){
                                playerBoxO.appendChild(newImg);
                            } else {
                                computerBoxO.appendChild(newImg);
                            }
                            total += newCards[i].value;
                        }
                        break;
                    case false : //deal cards face up
                        var total = 0;
                        var newCards = deck.getCards(numCards,false);
                        for(i=0; i < newCards.length; i++){
                            var newImg = document.createElement('img');
                            newImg.src = newCards[i].src;
                            newImg.facedown = newCards[i].facedown;
                            if(player == 'player'){
                                playerBoxO.appendChild(newImg);
                            } else {
                                computerBoxO.appendChild(newImg);
                            }
                            total += newCards[i].value;
                        }
                        break;
                }
                var totalsDivId = (player == 'player')? 'playerHandTotal' : 'computerHandTotal';
                document.getElementById(totalsDivId).innerHTML = 'Total = '+total;
            }
            window.onload=function(){
                computerBoxO = document.getElementById('computerBox');
                playerBoxO = document.getElementById('playerBox');
                document.getElementById('btnNewGame').onclick=startGame;
                document.getElementById('btnTurnComputerCards').onclick=function(){turnComputersCards('computer');}
                document.getElementById('btnTurnPlayerCards').onclick=function(){turnComputersCards('player');}
                deck = new cardStack(cardPicsO,backCardO,2);
            }
        </script>
    </head>
    <body>
        <div id="tabletop">
            <fieldset id="computerBox">
                <legend>Computer</legend>
                <div class="totals" id="computerHandTotal"></div>
            </fieldset>
            <fieldset id="playerBox">
                <legend>Player</legend>
                <div class="totals" id="playerHandTotal"></div>
            </fieldset>
            <div id="controlsContainer">
                <button id="btnNewGame">New game</button>
                <button id="btnTurnComputerCards">Turn computer's cards<br />face up</button>
                <button id="btnTurnPlayerCards">Turn players's cards<br />face up</button>
            </div>
        </div>
    </body>
</html>

Last edited by bullant; 05-19-2011 at 02:02 PM..
bullant is offline   Reply With Quote
Reply

Bookmarks

Tags
card, game, javascript

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 07:04 AM.


Advertisement
Log in to turn off these ads.