JavaScript - Help Creating A Javascript Dice Game.
Create a game where 6 dice are 'rolled' by you and 6 dice are 'rolled' by the player (simulated by the click of a button). Add up both rolls. The goal is to come as close to a score of 100 as possible, without passing 100. Have a STOP button to signify when you are ready to stop rolling and compute the winner. The highest score under 100 wins. Display the number of times you win and the number of times the computer wins using javascript. So far I have the following code, however, my dice images are not working(they display as little broken symbols when I run the game). The game itself is running just fine but I can't figure out how to get the game to do the "Add up both rolls" step and beyond. If anyone can help it would be much appreciated. Thanks.
Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Dice Game</title> <link href="Dicegame.css" type="text/css" rel="stylesheet" /> </head> <body> <div id='human' class='playerArea'> <h3>Human</h3> <div id='humanDice'> </div> <p id='humanTotal' class='total'></p> </div> <div id='computer' class='playerArea'> <h3>Computer</h3> <div id='computerDice'> </div> <p id='computerTotal' class='total'></p> </div> <div id='roll'> <a href='#' onclick='play(); return false;'>Roll</a> </div> <script type='text/javascript' src='lib.js'></script> <script type='text/javascript' src='dicegame.js'></script> </body> </html> *the external links are as follows* *Dicegame.css* body { background-color: #004400; } div.playerArea { position: absolute; top: 100px; bottom: 200px; width: 300px; background-color: #0996FF; border: 3px solid #0027C6; padding: 0 1em; } div#human { left: 100px; } div#computer { right: 100px; } div#roll { position: absolute; bottom: 50px; left: 100px; right: 100px; height: 100px; background-color: #FFFF00; border: 3px solid #FFBE00; } div#roll:hover { background-color: #FFFF99; } div#roll a { display: block; position: absolute; top: 0px; bottom: 0px; width: 100%; color: #004400; text-align: center; font-size: 90px; text-decoration: none; } div#roll a:hover { color: #FF0000; } p.total { margin: 10px; font-weight: bold; font-size: 8em; text-align: center; } p.winner { color: #00CC00; } p.loser { color: #CC0000; }[/CODE] *dicegame.js* Code: window.onload=function(){ Nifty("div.playerArea", "big"); } function roll() { var result = 0; result = Math.floor((Math.random() * 6) + 1); return result; } function play() { // create dice array var humanDice = new Array(); var computerDice = new Array(); // totals var humanTotal = 0; var computerTotal = 0; // output var out = ""; // roll the dice for (var i = 0; i < 6; i++) { humanDice[i] = roll(); humanTotal += humanDice[i]; computerDice[i] = roll(); computerTotal += computerDice[i]; } // display human dice out = displayDice(humanDice); document.getElementById('humanDice').innerHTML = out; // display computer dice out = displayDice(computerDice); document.getElementById('computerDice').innerHTML = out; document.getElementById('humanTotal').innerHTML = humanTotal; document.getElementById('computerTotal').innerHTML = computerTotal; if (humanTotal > computerTotal) { document.getElementById('humanTotal').className = 'total winner'; document.getElementById('computerTotal').className = 'total loser'; } else if (computerTotal > humanTotal) { document.getElementById('humanTotal').className = 'total loser'; document.getElementById('computerTotal').className = 'total winner'; } else { document.getElementById('humanTotal').className = 'total'; document.getElementById('computerTotal').className = 'total'; } } function displayDice(dice) { var out = ""; for (var i = 0; i < dice.length; i++) { out += "<img src='die" + dice[i] + ".png'/>"; } return out; } *lib.js* Code: function output(text, tag) { document.write("<" + tag + ">" + text + "</" + tag + ">"); } Similar Tutorialsguys im trying to make a dice game and i don't know nothing so can you guys help me with the code? This is what i am trying to do. i need help how to get started n stuff Something that will create a random number b/w 1 n 6 and decide if the user is a winner. He will win only if the #s are equal so i want a text box for the first number and text box for the second. a button to click to play the game(roll the dice) button to start over and reset all values textbox to display the # of tries(rolls) textbox 2 display the # of wins. Also i want toKeep track of the number of times the user rolls the dice and display this in the appropriate textbox and the number of times the user wins the game and display this in the appropriate textbox. Well my friend helped me with this but he made 2 player i only want one player and i want the number of tries and win the user wins if the #s are equal and i want a start over button that resets everything. Also the max number i want is 6 and only one roll the dice button but 2 textboxes so if you get same # you win it should appear in alert and text box for tries and wins. Also, i am gonna have 2 pics one for the first textbox the other for the second both of the pics are gonna be dice and i am gonna have 12 pics but only 2 appear at a time so if a guy gets 5 the dice with the #5 appears and the other text gets 4 the dice with the # 4 appears Code: <html> <HEAD> <SCRIPT LANGUAGE="JavaScript"> var die = 6; var dice = 2; var ary=[]; function dice_roll(die, dice,nu) { var txt=document.form.text; for (var roll=0,loop=0; loop < dice; loop++) { roll = roll + Math.round(Math.random() * die) % die + 1; } if (ary.length==0&&nu==0){ txt[0].value =ary[0]= roll; txt[1].value = 0; } if (ary.length==1&&nu==1){ txt[1].value = ary[1]= roll; if (ary[0]==ary[1]){ alert('Draw'); } else if (ary[0]>ary[1]){ alert('Player 1 Wins'); } else { alert('Player 2 Wins'); } ary=[]; } } // End --> </script> <body> <form name=form> <table border=2 cellpadding=5> <tr> <td colspan=2 align=middle>No. of sides/dice</td> </tr> <tr> <td valign=top align=middle> <p><input type=radio checked name=sides onClick="die = 6">6 Sided </td> <td valign=top align=middle> <p><input name=number type=radio onClick="dice = 2" checked> 2 </td> </tr> <tr> <td colspan=2 > Player 1 </td> </tr> <tr> <td align=middle colspan=4> <input type=button value="Roll Dice" name=button onClick="dice_roll(die, dice,0)"> <input type=text size=10 name=text value="0" disabled="disabled" > </td> </tr> <tr> <td colspan=2 > Player 2 </td> </tr> <tr> <td align=middle colspan=4> <input type=button value="Roll Dice" name=button onClick="dice_roll(die, dice,1)"> <input type=text size=10 name=text value="0" disabled="disabled" > </td> </tr> </table> </form> </center> </body> </html Hi! I am studying webdesign and we also go through a chapter of javascript-programming. Our first assignment is to create a dice game. I have written a code and in the beginning it worked, except that all the dices showed the same random number. I tried to fix that and now I do not know what I have done! In the game, you shall click on a link and the three dices will show random numbers. Here is my code: Code: <?xml version="1.0" encoding="UTF-8"?> <!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" xml:lang="en" lang="en"> <head> <title>Tärningsspel</title> <script type="text/javascript" language="javascript"> function showDice(imgNr) { if (imgNr == 1) var imgUrl = "1.gif"; else if (imgNr == 2) var imgUrl = "2.gif"; else if (imgNr == 3) var imgUrl = "3.gif"; else if (imgNr == 4) var imgUrl = "4.gif"; else if (imgNr == 5) var imgUrl = "5.gif"; else if (imgNr == 6) var imgUrl = "6.gif"; document.tarning1.src = imgUrl; document.tarning2.src = imgUrl; document.tarning3.src = imgUrl; } function randomInteger() { var randNumber = Math.random(); var randNumber = Math.floor(5*randNumber)+2; return randNumber; } function showRandomPict() { var imgNr = randomInteger(6); showDice(imgNr); var imgName = "tarning1" + imgNr; var imgName = "tarning2" + imgNr; var imgName = "tarning3" + imgNr; } function PlayAll(){ diceSwitch('tarning1', 'text1'); diceSwitch('tarning2', 'text2'); diceSwitch('tarning3', 'text3'); } function diceSwitch(randNumber,textRuta){ var randNumber = randomInteger(); } </script> </head> <body> <p><b>Tärning 1:</b><br /><span id="text1">1</span></p> <p><b>Tärning 2:</b><br /><span id="text2">2</span></p> <p><b>Tärning 3:</b><br /><span id="text3">3</span></p> <img src="1.gif" name="tarning1" onclick="javascript:diceSwitch('tarning1', 'text1')" /> <img src="2.gif" name="tarning2" onclick="javascript:diceSwitch('tarning2', 'text2')" /> <img src="3.gif" name="tarning3" onclick="javascript:diceSwitch('tarning3', 'text3')" /> <p><a href="javascript:PlayAll()">Spela alla!</a></p> </body> </html> Thank you! Hi, I'm trying to make a dice game, as well as making it two player. I need to be able to have a scoreboard displayed (eg. player 1 has won 7 times and player 2 has won 4) and I need to be able to prompt the user on if they want to play the game again. So far I have the following: Code: <html> <HEAD> <SCRIPT LANGUAGE="JavaScript"> <!-- Dice Game --> <!-- player 1 var die = 6; var dice = 2; var player1 = 0; var player2 = 0; function dice_roll(die, dice) { var roll = 0; for (loop=0; loop < dice; loop++) { roll = roll + Math.round(Math.random() * die) % die + 1; } document.form.text.value = roll; } player1 = roll; // End --> <!-- player 2 function dice_roll2(die, dice) { var roll = 0; for (loop=0; loop < dice; loop++) { roll = roll + Math.round(Math.random() * die) % die + 1; } document.form.text.value = roll; } player2 = roll; // End --> if player_1 = player_2 alert("DRAW!") else if player_1 > player_2 alert("Player 1 is the winner!") else if player_1 < player_2 alert("Player 2 is the winner!") </script> <body> <form name=form> <table border=2 cellpadding=5> <tr> <td colspan=2 align=middle>No. of sides/dice</td> </tr> <tr> <td valign=top align=middle> <p><input type=radio checked name=sides onClick="die = 6">6 Sided </td> <td valign=top align=middle> <p><input name=number type=radio onClick="dice = 2" checked> 2 </td> </tr> <tr> <td align=middle colspan=4> <input type=button value="Roll Dice" name=button onClick="dice_roll(die, dice)"> <input type=text size=10 name=text> </td> </tr> </table> </form> </center> </body> </html ^^ I basically just tried duplicating the original function that adds up the 'dice'. But it doesn't work, I've tried playing around with if/else statements etc to get it to display messages and so fourth, but I have failed. Any help would be appreciated. I only started javascript last week and my teacher isn't really helping explain lots of it. Thanks in advance. everything in this dice rolling game is fine until line 69 where i get TypeError:actuals[i] undefined. Any help would be appreciated. http://pastebin.com/bVmgMcbB Hi, I am working on a simple javascript craps game program. I need some advice since it won't display who the winner is, keep tally of who wins/loses, and the number of total games played. After using the error console there's an error with document.forms[0].thrower.value not being defined. Can anyone help me with this? PHP Code: <html> <head> <title> JavaScript Craps Game</title> <script type="text/javascript"> <!-- var n,die_1,die_2,total,h_won,c_won, flag, point,winner; function get_num() { var max = 6; var number=Math.random()*max + 1; var result=Math.floor(number); return result; } function roll_dice() { die_1 = get_num(); die_2 = get_num(); total= die_1 + die_2; // Insert the results of the dice into the appropriate fields document.getElementById("die1").innerHTML= die_1; document.getElementById("die2").innerHTML= die_2; document.getElementById("total").innerHTML= total; //document.forms[0].die1.value = die_1; //document.forms[0].die2.value = die_2; //document.forms[0].tot.value = total; //Subtracting 0 from these values forces them to be typed as numbers if (flag){ //This means we rolled something other than 2,3,7,11, or 12 so we have a point var th = document.forms[0].thrower.value; if (total == point) { //X wins winner = "x"; calculate_winnings(th,winner); flag = 0; //document.forms[0].flag.value="0"; game_count(); } else if (total == 7){ //Y wins winner = "y"; calculate_winnings(th,winner); flag = 0; //document.forms[0].flag.value="0"; game_count(); } } else{ var thwr = document.forms[0].thrower.value; if (total == 7 || total == 11) { //X wins document.getElementById("winner").innerHTML= "X Wins!"; //document.forms[0].winner.value= "X Wins!"; winner = "x"; calculate_winnings(thwr,winner); game_count(); } else if (total == 2 || total == 3 || total == 12){ //document.forms[0].winner.value= "Y Wins!"; document.getElementById("winner").innerHTML= "Y Wins!"; winner = "y"; calculate_winnings(thwr,winner); game_count(); } else { point = total; document.getElementById("winner").innerHTML= "Waiting for a 7 or a " + point; // document.forms[0].winner.value="Waiting for a 7 or a " + point; flag = 1; //document.forms[0].flag.value="1"; } } } function game_count() { //for keeping track of games if (n){ n = n + 1; } else { n = 1; } document.forms[0].totalgames.value = n; //return n; } function calculate_winnings(thrower,winner) { var button = document.forms[0].thrower.checked; if (button) { if (winner == 'x') { //computer was thrower and X won //document.forms[0].winner.value="Computer Wins!"; document.getElementById("winner").innerHTML= "Computer Wins."; add_to_computer_win(); } else { //computer was thrower and Y won //document.forms[0].winner.value="You win!"; document.getElementById("winner").innerHTML= "You win!"; add_to_human_win(); } } else { if (winner == 'x') { //human was thrower and X won //document.forms[0].winner.value="You Win!"; document.getElementById("winner").innerHTML= "You Win!"; add_to_human_win(); } else { //human was thrower and Y won //document.forms[0].winner.value="Computer Wins!"; document.getElementById("winner").innerHTML= "Computer Wins."; add_to_computer_win(); } } thrower = 0; } function add_to_human_win(){ if (h_won){ h_won = h_won + 1; } else { h_won = 1; } document.forms[0].human_won.value=h_won; } function add_to_computer_win(){ if (c_won){ c_won = c_won + 1; } else { c_won = 1; } document.forms[0].computer_won.value=c_won; } --> </script> </head> <body> <h1> <center> Craps Game </center></h1> <hr> <form> <table border="1"> <tr> <td width="45%" align="center"> <center><b><font size="4">Play!</font></b></center> <p><input type="button" name="roll" value="Roll Dice!" onclick="roll_dice()"></p> <table border="1"> <tr> <td>Die #1</td><td>Die #2</td><td>Total</td> </tr> <tr> <td><div id="die1"></div></td> <td><div id="die2"></div></td> <td><div id="total"></div></td> </tr> </table> <p>Result of roll: <div id="winner"></div></p> <!--<input type="text" size="30" name="winner" value=""></p>--> <p> </p> </td> <td width="35%"> <table border="1" cellspacing="7"> <tr> <th colspan="2" ><font size="4">Statistics:</font><br> <input type="text" size="2" name="totalgames" value="0"> total games played</th> </tr> <tr> <td align="center">Your wins</td><td>Computer wins</td> </tr> <tr> <td align="center"><input type="text" size="2" name="human_won" value="0"></td> <td align="center"><input type="text" size="2" name="computer_won" value="0"></td> </tr> </table> </td><td width="20%" align="center"> This will clear your statistics and start a new game<br> <input type="submit" name="startover" value="New Game"> </td></tr></table> <hr> <h3><a name="Help">Help</a></h3> <pre> The game of craps is a dice game played by two players, You and The House. First you toss the pair of dice. If the sum of the dice is 7 or 11, you win the game. If the sum is 2, 3, or 12, the house wins. Otherwise, the sum is designated as the "point," to be matched by another toss. So if neither player has won on the first toss, then the dice are tossed repeatedly until either the point or a 7 comes up. If a 7 comes up first, the house wins. Otherwise, you win when the point comes up. </body> </html> Hi there, basically i have created a simple card game, i have one html page with 6 decks of cards. The decks are just images that when clicked display 6 other cards on another html page. What i want to do is that when i click a card on the second page i want the card to be removed, so that when i go back the first page and select the same deck again, the second page opens and the card i had selected before is still removed? Is this possible with javascript please i am totally new to it. Please could someone give me some direction? Thanks
hello there im unsure if this is the correct place to post this so if its not im sorry what im trying to do is make a javascript pop-up message in real time alerting members who are online at that time to a game submitted i help run a fifa10 online league site and we are venturing into the 2v2 part of the site. now when a player goes to the 2v2 page they are presented with a submit button to submit a 2v2 game to the system. then this already shows up on the pagebut what we are after is a little pop up box which after the game button is pressed to submit the game the pop-up shows to the whole site that a 2v2 game has been submitted for playing. we want this so you dont have to sit on the 2v2 page to wait for a submitted game. does anybody have any ideas on how we would go about this?? thanks for your time and i hope some1 can help - even if its just in the slightest Ok so I'm in college and I'm taking my first web development class online. Unfortunate my teacher is awful. We have already "covered" html and some css and done a bit of java such as creating a prompt and a super simple calculator. However, for the final I have to make a 2 player game with at least 30 spaces and dice (random number generator). More importantly our "learn javascript in 24 hours" book doesn't cover this at all and my teacher is MIA like always. So, I have come to you all for help. I found a sample script that is almost exactly what I need for this project but it needs a bit of tweaking http://javascript.internet.com/games...ders-game.html I need to add 5 additional spaces and I wanted to add a ladder from space 24-27 and change the chute from 16-6 to 25-6. Unfortunately I'm kind of clueless on how to do this and make sure everything works properly.... Here is an image I made real quick of what I want it to look like And this is the requirements for the project. * Minimum Requirements for a C: o 2 players o 20 steps on the board o Random number generator o Game displays the location of each player on the board * Minimum Requirements for a B: o Everything above plus o Attractive user interface. o 30 steps on the board o Graphical random number generator (Example: Display the number as a dice image) * Minimum Requirements for an A: o Everything above plus o Educational game that shows facts as the players move around the game. Any help at all would be amazing and greatly appreciated This is a simple basic game i want to make. Its a "What Am I" Riddle... The questions is (In HTML which i already know): I'm as light as a feather but no man can hold me for long. What am I? the answer is: Your Breath. (This is where the JAVASCRIPT comes in) Lets say they guess a rock, have a pop up say: Wrong Answer. Please try again. Lets say they guess Your breath -OR- Breath, have a pop up say: Correct! I want a text field where you can enter your answer, and if they choose ANYTHING but the 2 correct answers above, it will display please try again. Can anyone code this please? Thanks for reading. Ok so i want to work on an EASY basic game. As simple as Guess what number... But there are some twist... Ok So here is my example... (HTML, i know this.)I'm Guessing a number 1-99. What is it? (java) Lets say its 66 and they guess 53, have the text rusult be in a pop up window be: Too low! (java) Lets say they guess 78, have the text rusult be in a pop up window be: Too high! (java) Lets say they guess 100+, have the text rusult be in a pop up window be: Out of range! (java)But lets say they guess 66, have a text result be in a pop up window be: You've won! (java) I want a text field where you can enter your answer, and it will do the actions above. Can anyone code this? Thanks for reading! A newbie here can you please help me with my javascript game. I cant seem to make it work. Quote: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Language" content="en-us" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Play</title> <script type='text/javascript'> function win(x, z){ if(x == z) return "It's a draw"; draw.value++; { if(x == "Fire")&&(z == "Air") return "You Lose, Fire beats Air!"; loss.value++; else if(x == "Fire")&&(z == "Earth") return "It's a draw!"; draw.value++; else if(x == "Fire")&&(z == "Water") return "You Win, Fire is beaten by Water!"; win.value++; } { if(x == "Air")&&(z == "Earth") return "You win, Air beats Earth"; win.value++; else if(x == "Air")&&(z == "Water") return "It's a draw!"; draw.value++; else if(x == "Air")&&(z == "Fire") return "You lose, Air is beaten by Fire!") loss.value++ } { if(x == "Earth")&&(z == "Air") return "You Lose, Earth is beaten by Air" loss.value++; else if(x == "Earth")&&(z == "Water") return "You Win, Earth beats Water"; win.value++; else if(x == "Earth")&&(z == "Fire") return "It's a draw!"; draw.value++; } { if(x == "Water")&&(z == "Fire") return "You win, Water beats Fire"; win.value++; else if(x == "Water")&&(z == "Air") return "It's a draw!"; draw.value++; else if(x == "Water")&&(z == "Earth") return "You lose, Water is beaten by Earth" loss.value++; } } function ran(){ var gen = Math.random(); if(gen <= 0.25) var com = "Fire"; if((gen > 0.25)&&(gen<= 0.50)) var com = "Earth"; if(gen > 0.50)&&(gen<= 0.75)) var com = "Water"; if(gen > 0.75) var com = "Air"; if(document.c.game[0].checked) var use = "Fire"; if(document.c.game[1].checked) var use = "Earth"; if(document.c.game[2].checked) var use = "Water"; if(document.c.game[3].checked) var use = "Air"; alert ("The computer played: " + com +". You played: " + use + ". " + win(com,use)); } </script> <style type="text/css"> body {background-color:#7f9527;} .style1 { color: #FFFFFF; } .style2 { font-family: "After Disaster"; } .style3 { font-family: "After Disaster"; font-size: 30pt; color: #FFFFFF; margin-left: 160px; } .style4 { font-size: xx-large; } .style5 { color: #FFFFFF; font-size: large; } .style6 { color: #FFFFFF; font-family: "After Disaster"; font-size: large; } .style7 { margin-top: 0px; } .style8 { color: #FFFFFF; font-family: "After Disaster"; font-size: xx-large; margin-left: 280px; } .style9 { font-size: large; } .style10 { margin-top: 12px; } </style> </head> <body> <p class="style3" style="width: 581px">Avatar The Last Air bender: Element Fight</p> <p class="style8" style="width: 340px"> <img alt="" src="Avatar_Aang_by_Shira_chan.jpg" width="339" height="244" class="style7" /></p> <p class="style6">Select Your Attack</p> <form name="c" method="post" class="style2"> <span class="style4"><span class="style9"> <input name="game" type="radio" value="Fire" /></span></span><span class="style5">Fire</span><span class="style9"><br /> </span><span class="style4"><span class="style9"> <input name="game" type="radio" value="Earth" /></span></span><span class="style5">Earth</span><span class="style9"><br /> </span><span class="style4"><span class="style9"> <input name="game" type="radio" value="Water" /></span></span><span class="style1"><span class="style9">Water<br /> <span class="style4"> <input name="game" type="radio" value="Air" /></span>Air</span><br /></span> <tr> <td colspan="4" align=center> <span class="style2"> <input type="text" name= "win" readonly="readonly" value="0" size="2"> Wins </input> <input type="text" name= "loss" readonly="readonly" value="0" size="2"> Losses</input> <input type="text" name= "draw" readonly="readonly" value="0" size="2"> Draws</input> </span> </td> </tr> </form> <form method="post"> <br /> <input name="Play" type="button" value="Play" onClick="ran()" style="width: 189px; height: 39px" /> <a href="Instructions.htm"> <input name="Button1" type="button" value="Instructions" style="width: 189px; height: 39px" class="style10" /></a></form> </body> </html> I am creating a guessing word game and when the user types in a guess a pop-up tells the user how many letters the user got right to the actual answer. My problem is I can't seem to display the number of letters the user guessed right. This is what the function looks like: Code: function guessing() { words = "album"; guess = document.getElementById("txt1").value; answer = document.getElementById("result").value = parseInt(); alert("You have " + answer + " matches"); used = false; for(i = 0; i<=guess.length; i++) { for(j = 0; j<=answer.length; j++) if(!used[j] && guess[i] == words) { alert("Congradulations! You got it!"); used[j] = true; count++; break; } else { count = 5; while(count > 5) { alert("Sorry, that's game over!"); count++; } } } } Hi guys I need some help with a 2d game that i am making. i am almost done i need only a loading screen but its not working i got this javascript file thats getting an error about : assetsloader is not defined. Maybe you guys can help me. Here is the code: Code: // awesome goblin game // assetLoader /** * Ensure all assets are loaded before using them * @param {number} dic - Dictionary name ('imgs', 'sounds', 'fonts') * @param {number} name - Asset name in the dictionary */ function assetLoaded(dic, name) { // don't count assets that have already loaded if (this[dic][name].status !== 'loading') { return; } this[dic][name].status = 'loaded'; assetsLoaded++; // progress callback if (typeof this.progress === 'function') { this.progress(assetsLoaded, this.totalAssest); } // finished callback if (assetsLoaded === this.totalAssest && typeof this.finished === 'function') { this.finished(); } } // before assetLoader.finished() /** * Show asset loading progress * @param {integer} progress - Number of assets loaded * @param {integer} total - Total number of assets */ assetLoader.progress = function(progress, total) { var pBar = document.getElementById('progress-bar'); pBar.value = progress / total; document.getElementById('p').innerHTML = Math.round(pBar.value * 100) + "%"; } /** * Show the main menu after loading all assets */ // Create the canvas var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); canvas.width = 512; canvas.height = 480; document.body.appendChild(canvas); function mainMenu() { $('#progress').hide(); $('#main').show(); $('#menu').addClass('main'); } // Background image var bgReady = false; var bgImage = new Image(); bgImage.onload = function () { bgReady = true; }; bgImage.src = "images/background.png"; // Hero image var heroReady = false; var heroImage = new Image(); heroImage.onload = function () { heroReady = true; }; heroImage.src = "images/hero_sheet.png"; // Treasure image var treasureReady = false; var treasureImage = new Image(); treasureImage.onload = function () { treasureReady = true; }; treasureImage.src = "images/treasure.png"; // Monster image var monsterReady = false; var monsterImage = new Image(); monsterImage.onload = function () { monsterReady = true; }; monsterImage.src = "images/monster.png"; // Game objects var backgrounder = { speed: 0, x: 0, y: 0 }; var hero = { speed: 256, // movement in pixels per second x: 0, y: 0 }; var monster = { speed: 256, x: 0, y: 0 }; var treasure = { x:0, y:0 }; var treasureCaught = 0; var treasureTimer= 0; var treasureTime= 50; var monstersCaught = 0; var delta = 0; var lives = 3; var directionMonster = 0; var directionDuration = 20; var goThisWay = 1; // Handle keyboard controls var keysDown = {}; addEventListener("keydown", function (e) { keysDown[e.keyCode] = true; }, false); addEventListener("keyup", function (e) { delete keysDown[e.keyCode]; }, false); // Reset the game when the player catches a monster var reset = function () { hero.x = canvas.width / 2; hero.y = canvas.height / 2; // Throw the monster somewhere on the screen randomly monster.x = 32 + (Math.random() * (canvas.width - 64)); monster.y = 32 + (Math.random() * (canvas.height - 64)); }; //restart the game var restartGame = function (){ //when you die screen turns black ctx.fillStyle="#000000";//color ctx.fillRect(32,32,canvas.width-64,canvas.height-64);//draw rectangle with the bushes still in place //show that you're dead ctx.fillStyle = "rgb(250, 250, 250)"; ctx.textAlign = "center"; ctx.fillText("GameOver Press R to reset",canvas.width/2, canvas.height/2); //R to reset pressed if (82 in keysDown){ //reset assets lives = 3; treasureCaught = 0; } }; // Update game objects var update = function (modifier) { if (38 in keysDown) { // Player holding up //check if hero walks from screen if (hero.y <= 32){ //if hero walks from screen top, stay at exact y axle hero.y = hero.y; } else{ //move hero up hero.y -= hero.speed * modifier; } // end of upmovement } if (40 in keysDown) { // Player holding down //check if hero walks from screen if (hero.y >= canvas.height -64){ //if hero walks from screen bottom, stay at exact y axle hero.y = hero.y; } else{ //move hero down hero.y += hero.speed * modifier; }// end of downmovement } if (37 in keysDown) { // Player holding left //check if hero walks from screen if (hero.x <= 32){ //if hero walks from screen left, stay at exact x axle hero.x = hero.x; } else{ //move hero left hero.x -= hero.speed * modifier; }//end of left movement } if (39 in keysDown) { // Player holding right //check if hero walks from screen if (hero.x >= canvas.width -64){ //if hero walks from screen right, stay at exact x axle hero.x=hero.x; } else{ //move hero right hero.x += hero.speed * modifier; }//end of right movement } // Are they touching? MONSTER if ( hero.x <= (monster.x + 32) && monster.x <= (hero.x + 32) && hero.y <= (monster.y + 32) && monster.y <= (hero.y + 32) ) { --lives; reset(); } // Are they touching? TREASURE if ( hero.x <= (treasure.x + 32) && treasure.x <= (hero.x + 32) && hero.y <= (treasure.y + 32) && treasure.y <= (hero.y + 32) ) { treasureTimer = treasureTime; ++treasureCaught; } }; //make our monster move :) var monsterMove = function (modifier){ ++directionMonster; if (directionMonster <= directionDuration){ //bewegingen //rechts => links if (goThisWay == 1) { monster.x = monster.x - (monster.speed * modifier); if (monster.x <= 32){ goThisWay = 2; } } //links => rechts if (goThisWay == 2) { monster.x = monster.x + (monster.speed * modifier); if (monster.x >= canvas.width-64){ goThisWay=1; } } //boven => onderen if (goThisWay == 3) { monster.y = monster.y + (monster.speed * modifier); if (monster.y >= canvas.height-64){ goThisWay=4; } } //onderen => boven if (goThisWay == 4) { monster.y = monster.y - (monster.speed * modifier); if (monster.y <= 32){ goThisWay=3; } } //bepalen welke richting if (directionMonster ==directionDuration){ directionMonster = 0; goThisWay = Math.floor((Math.random() * 4) + 1); //console.log (goThisWay); } } }; // Draw everything var render = function () { if (bgReady) { //backgrounder.x = backgrounder.x +1; backgrounder.x = 0; ctx.drawImage(bgImage, backgrounder.x, 0); } if (heroReady) { ctx.drawImage(heroImage, hero.x, hero.y); } if (monsterReady) { ctx.drawImage(monsterImage, monster.x, monster.y); } if (treasureReady) { ctx.drawImage(treasureImage, treasure.x, treasure.y); } // Score ctx.fillStyle = "rgb(250, 250, 250)"; ctx.font = "24px Helvetica"; ctx.textAlign = "left"; ctx.textBaseline = "top"; ctx.fillText("Treasure caught: " + treasureCaught, 32, canvas.height-64); ctx.fillText("Lives: " + lives, 32, 32); }; var spawnTreasure = function(){ if (treasureTimer >= treasureTime){ treasure.x = 32 + (Math.random() * (canvas.width - 64)); treasure.y = 32 + (Math.random() * (canvas.height - 64)); treasureTimer = 0; } ++treasureTimer; }; // The main game loop var main = function () { var now = Date.now(); delta = now - then; if (lives > 0){ update(delta / 1000); render(); monsterMove(delta / 1000); spawnTreasure(); } else { restartGame(); } then = now; // Request to do this again ASAP requestAnimationFrame(main); }; // Cross-browser support for requestAnimationFrame var w = window; requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame; // Let's play this game! var then = Date.now(); reset(); main(); Reply With Quote 01-14-2015, 10:11 PM #2 felgall View Profile View Forum Posts Visit Homepage Master Coder Join Date Sep 2005 Location Sydney, Australia Posts 6,745 Thanks 0 Thanked 666 Times in 655 Posts In the code you posted there are no references to assetsLoader at all. There is exactly one reference to assetLoader (without the 's') and that is to add a progress() function to every occurrence of the assetLoader object that you haven't defined (at least not in the code you posted). How hard would it be to make a 2d game similar to super smash bros? Basically I want to have a scrolling position (instead of a static image, where the background is always the same) where when the user moves his character object, the area of vision moves with him. Also, will it work with using keyboard keys? I have to integrate it into a database and I know quite a bit of javascript so I am hoping it is possible. Thanks! Max Hi everyone. Right now I'm doing a guessing game assignment for my class. I'm new to the forums so sorry if copy/pasting code into the thread here isn't the right thing to do. I have ran firebug a few times on this code and for some reason the variable "Football" is the only answer that is declared true. How can I fix this code so that all of the variables in the array display the true statement when typed in the box? Note: I have the questions looped to ask 3 times. Thanks! <html> <head> <h1>Welcome to the guessing game!</h1> <h2>Second Submission Attempt</h2> </head> <body> <script type = "text/javascript"> var sportsAry = new Array(6); sportsAry[0] = "Football"; sportsAry[1] = "Basketball"; sportsAry[2] = "Rollerblading"; sportsAry[3] = "Hiking"; sportsAry[4] = "Biking"; sportsAry[5] = "Swimming"; var firstName; var points = 0; var finalscore; var ask; do { firstName = prompt("Please enter your first name.",""); } while (firstName == "" || firstName == null || firstName == parseInt(firstName)); alert("Welcome to the Game, " + firstName + " !"); for (var count = 0; count < 3; count++){ ask = prompt("Please guess a sport : ",""); if (ask == null){ alert("You are chicken!!!"); } else if (ask == ""){ alert("You forgot to enter a game!"); count--; }else { for ( var i = 0; i < sportsAry.length; i++){ if (ask.toUpperCase() == sportsAry[i].toUpperCase()) { points +=5; alert("You have guessed correctly! You have gained 5 points"); break; }else if (ask.toUpperCase() !== sportsAry[i].toUpperCase()) { points -=5; alert("You have guessed incorrectly, you gain no points."); break; } } } } if (points == 15){ document.write(firstName + ", you are a mind reader!" + "<br>"); } else if (points < 15){ document.write(firstName + ", you are pretty good!"); }else { document.write(firstName + ", you do not display ESP tendencies at this time."); } </script> </body> </html> Hey guys I need help on making the images on this game show up. Im not sure how to get the card images to load when hitting the deal button. Code: <html> <head> <title> Blackjack </title> <script LANGUAGE="JavaScript1.1"> var dealer_hand = new Array(); var player_hand = new Array(); var game_over = false; function Card(num,suit) { this.num = num; this.suit = suit; this.fname = fname; } function fname() { return this.num + this.suit + ".gif"; } function Deck() { this.cards = new Array(52); this.next_card = 0; // fill the deck (in order, for now) for (i=1; i<14; i++) { this.cards[i-1] = new Card(i,"c"); this.cards[i+12] = new Card(i,"h"); this.cards[i+25] = new Card(i,"s"); this.cards[i+38] = new Card(i,"d"); } this.shuffle = shuffle; this.dealCard = dealCard; } function shuffle() { for (i=1; i<1000; i++) { // switch two randomly selected cards card1 = Math.floor( 52*Math.random() ); card2 = Math.floor( 52*Math.random() ); temp = this.cards[card2]; this.cards[card2] = this.cards[card1]; this.cards[card1] = temp; } this.next_card = 0; } function dealCard() { return this.cards[ this.next_card++ ]; } var deck = new Deck(); deck.shuffle(); function newGame() { if ( deck.next_card > 39 ) { deck.shuffle(); } dealer_hand = new Array(); player_hand = new Array(); dealer_hand[ 0 ] = deck.dealCard(); // This is the hole card. document.images[0].src = "http://www.litchzen.com/cardback.PNG"; // The hole card is not shown dealer_hand[ 1 ] = deck.dealCard(); document.images[ 1 ].src = dealer_hand[ 1 ].fname(); for ( i=2; i<6; i++) { document.images[i].src = "http://www.litchzen.com/cardback.PNG"; } num = i + 1; player_hand[ 0 ] = deck.dealCard(); document.images[ 6 ].src = player_hand[ 0 ].fname(); player_hand[ 1 ] = deck.dealCard(); document.images[ 7 ].src = player_hand[ 1 ].fname(); for (i=8; i<12; i++) { document.images[i].src = "http://www.litchzen.com/cardback.PNG"; } window.status = ""; document.form1.dealer.value = ""; document.form1.result.value = ""; document.form1.player.value = score( player_hand ); game_over = false; } // end function newGame() function hit() { var total = 0; var new_card = 0; // index for the new card position if ( game_over ) { window.status = "Game over. Click the Deal button to start a new hand." } else { new_card = player_hand.length; player_hand[ new_card ] = deck.dealCard(); document.images[ new_card + 6 ].src = player_hand[ new_card ].fname(); total = score( player_hand ); if ( total > 21 ) { // Busted, game over. document.form1.player.value = total + " busted"; document.images[ 0 ].src = dealer_hand[ 0 ].fname(); document.form1.dealer.value = score( dealer_hand ); winner(); game_over = true; } else { document.form1.player.value = total; } } } // end function hit() function stand() { var total = 0; var new_card = 0; if ( game_over ) { window.status = "Game over. Click the Deal button to start a new hand." } else { document.images[ 0 ].src = dealer_hand[ 0 ].fname(); while ( score( dealer_hand ) < 17 ) { new_card = dealer_hand.length; dealer_hand[ new_card ] = deck.dealCard(); document.images[ new_card ].src = dealer_hand[ new_card ].fname(); } total = score( dealer_hand ); if ( total > 21 ) { // Busted document.form1.dealer.value = total + " busted"; } else { document.form1.dealer.value = total; } } winner(); game_over = true; // The game ends after the player stands. } // end function stand() function score(hand) { var total = 0; var soft = 0; // This variable counts the number of aces in the hand. var pips = 0; // The trump pictures on a card used to be called pips. for ( i=0; i<hand.length; i++ ) { pips = hand[i].num; if ( pips == 1 ) { soft = soft + 1; total = total + 11; } else { if ( pips == 11 || pips == 12 || pips == 13 ) { total = total + 10; } else { total = total + pips; } } } while ( soft > 0 && total > 21 ) { // Count the aces as 1 instead total = total - 10; // of 11 if the total is over 21 soft = soft - 1; } return total; } // end function score function winner() { var player_total = score( player_hand ); var dealer_total = score( dealer_hand ); if ( player_total > 21 ) { // Busted document.form1.result.value = "Dealer wins"; } else { if ( dealer_total > 21 ) { // Busted document.form1.result.value = "Player wins"; } else { if ( player_total == dealer_total ) { document.form1.result.value = "Tie game"; } else { if ( player_total > dealer_total ) { document.form1.result.value = "Player wins"; } else { document.form1.result.value = "Dealer wins"; } } } } } </script> </head> <body> <h1>Blackjack Javascript Example</h1> <hr> <form NAME="form1"> <table> <tr> <td> <B>Dealer: </B> <td> <img border=0 src="http://www.litchzen.com/cardback.PNG" height=125 width=95> <td> <img border=0 src="http://www.litchzen.com/cardback.PNG" height=125 width=95> <td> <img border=0 src="http://www.litchzen.com/cardback.PNG" height=125 width=95> <td> <img border=0 src="http://www.litchzen.com/cardback.PNG" height=125 width=95> <td> <img border=0 src="http://www.litchzen.com/cardback.PNG" height=125 width=95> <td> <img border=0 src="http://www.litchzen.com/cardback.PNG" height=125 width=95> <td> </td> </tr> <tr> <td> <B>Player: <B> <td> <img border=0 src="http://www.litchzen.com/cardback.PNG" height=125 width=95> <td> <img border=0 src="http://www.litchzen.com/cardback.PNG" height=125 width=95> <td> <img border=0 src="http://www.litchzen.com/cardback.PNG" height=125 width=95> <td> <img border=0 src="http://www.litchzen.com/cardback.PNG" height=125 width=95> <td> <img border=0 src="http://www.litchzen.com/cardback.PNG" height=125 width=95> <td> <img border=0 src="http://www.litchzen.com/cardback.PNG" height=125 width=95> </tr> <tr> <td> <B>Dealer Sco </B><BR> <input TYPE="TEXT" SIZE=12 NAME="Dealer" VALUE="0"></td> <td> <B>Player Sco </B><BR> <input TYPE="TEXT" SIZE=12 NAME="You" VALUE="0"> <td> <input TYPE="BUTTON" VALUE=" Stay " onClick="stand();"> <td> <input TYPE="BUTTON" VALUE=" Hit " onClick="hit();"> <td> <a href="#" onClick="newGame();" onMouseOver = "window.status = 'Deal a new hand.'; return true; " onMouseOut = "window.status = '';"> <img border=0 src="http://us.cdn3.123rf.com/168nwm/fuzzbones/fuzzbones1105/fuzzbones110500782/9628185-deal-word-in-male-hand.jpg" height=50 width=106></a> <td> <B>Game Result:</B><BR> <input TYPE="TEXT" SIZE=10 NAME="result" VALUE=""</td> </tr> </table> </form> <P>Click the Deal button to start a new game.<BR> Click the Hit button to get another card.<BR> Click the Stay button to end your turn. Try and get as close to 21 as possible to win. Good luck!</P> </body> </html> Hello, this is my first post here, but I'm having some trouble figuring out what I messed up on my code I'm making a Javascript game of Hangman for one of my classes and I originally had the input as a text box where you physically type in the letter and if it was wrong, it would draw the next sequence of the hangman picture and place the letter in another text box as a "Used Letters," or if you're right, it would place the letter you chose in the box for the word you're guessing. However, I decided that instead of doing that, I wanted to make it more visually appealing and add buttons with the letters on them instead. As you can see in the code which is down-loadable here (the one with the _2 is the one I'm currently using, but the original is supplied as well), the buttons register for the picture changing, but do not register for the "Used Letters" field or for filling in the actual word. One of the button's values is also replaced by "undefined" after each click of another button and I'm not really sure why If anyone could take a look at my code and see if you can figure out what the deal is, that'd be awesome! can u like make games like pong wikth javascript? my friend said he did, but i dont think u can.
Ok basically i am making a blackjack game and so far i have a random generator for my cards, once i press deal 4 cards are dealt at random, but when i try to insert a new button for the player to press for another card "hit", the card comes down and is not random at all. I could really do with this help. Thank you. Code: <html> <HEAD> <SCRIPT LANGUAGE="JavaScript"> var deck=new Array; var hand=new Array(53); var hcrd=new Array(53); var hsut=new Array(53); var isPlaying=-1; var betn=1; var dpos=0; var crdts; var ncard=0; /* ----------------------------------------------------------------------------------------- */ function initdeck(){ crd=0; for(i=0;i<4;i++){ if(i==0){st="club";} else if(i==1){st="heart";} else if(i==2){st="diamond";}else{st="spade";} for(c=1;c<14;c++){ if(c==1){num="ace";}else if(c==11){num="jack";} else if(c==12){num="queen";}else if(c==13){num="king";}else{num=c;} deck[crd++]=st+"|"+num; } //for c } //for i } /* ----------------------------------------------------------------------------------------- */ function showcard(cnum) { p = hand[cnum].indexOf("|"); s = hand[cnum].substring(0,p); c = hand[cnum].substring(p+1,hand[cnum].length); if(cnum==0){document.images.card1.src="cards/"+s+c+".jpg";} else if(cnum==1){document.images.card2.src="cards/"+s+c+".jpg";} else if(cnum==2){document.images.card3.src="cards/"+s+c+".jpg";} else if(cnum==3){document.images.card4.src="cards/"+s+c+".jpg";} else{document.images.card11.src="cards/"+s+c+".jpg";} } function hit(ncard) { p = hand[ncard].indexOf("|"); s = hand[ncard].substring(0,p); c = hand[ncard].substring(p+1,hand[ncard].length); if(ncard==4){document.images.card5.src="cards/"+s+c+".jpg";} else if(ncard==5){document.images.card6.src="cards/"+s+c+".jpg";} else if(ncard==6){document.images.card7.src="cards/"+s+c+".jpg";} } function stand() { document.images.card8.src="cards/"+s+c+".jpg"; } function deal() { if(isPlaying < 0) { // new game dpos = 0; isPlaying=1; for(i=0;i<500;i++) { //shuffle the cards(mix up the deck) tmp = Math.round(Math.random()*51); tmp2= Math.round(Math.random()*51); stmp = deck[tmp]; deck[tmp] = deck[tmp2]; deck[tmp2] = stmp; } for(i=0;i<53;i++) { hand[i]=deck[dpos++];showcard(i); hand[i]=deck[dpos++];hit(i); } } } function quit(){window.close();} /* ----------------------------------------------------------------------------------------- */ initdeck(); // End --> </script> </HEAD> <BODY> <table> <tr><form name="drwcrd"> <td width=590></td> <td><b>Computer</b></td> </tr><tr></form> <table> <tr><form name="drwcrd"> <td width=500></td> <td width=30 align=center><img name="card1" src="cards/cardback.jpg"></td> <td width=30 align=center><img name="card3" src="cards/cardback.jpg"></td> <td width=30 align=center><img name="card8" src=""></td> <td width=30 align=center><img name="card9" src=""></td> <td width=30 align=center><img name="card10" src=""></td> <table> <tr><form name="drwcrd"> <td width=590></td> <td><b>Player</b></td> </tr><tr></form> <table> <tr><form name="drwcrd"> <td width=500></td> <td width=30 align=center><img name="card2" src="cards/cardback.jpg"</td> <td width=30 align=center><img name="card4" src="cards/cardback.jpg"</td> <td width=30 align=center><img name="card5" src=""</td> <td width=30 align=center><img name="card6" src=""</td> <td width=30 align=center><img name="card7" src=""</td> </tr><tr></form> <table> <tr><td><input type="button" value ="DEAL Cards" onClick="javascript:deal();"></td> <td><input type="button" value ="Hit" onClick="javascript:hit();"></td> <td><input type="button" value ="Stand" onClick="javascript:stand();"></td> </body> </html> if anyone has any help id be grateful or if anyone has any ideas on how to approach this differently. thanks in advance please excuse the code its a little messy atm. sorry |