JavaScript - Need Help With My Code For A Game Of Craps
Similar TutorialsHi, 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 I am using httpXmlRequest object to call a xml web service. In order to successfully perform a task there are couple steps need to happen. 1 you have to request for a session (cookie) 2 with the cookie, we need to authenticate with the server 3 then perform other actions snippet of my code looks something like this. Basically here i am trying to get the cookie, login and then logout once logged in. function connect() { document.myForm.elements['myTextArea'].value += "connecting to teh server.\n"; try { xhttp.open("GET",urlStr + commonInfoParam, true); xhttp.send(); xmlDoc = xhttp.responseXML; xmlDoc.onreadystatechange = function () { if(xmlDoc.readyState == 4) { var resultsTag = null; resultsTag = xmlDoc.getElementsByTagName("results"); if(resultsTag != null) { for(i=0;i<resultsTag.length;i++) { var commonTag = resultsTag[i].getElementsByTagName("common"); for(j=0;j<commonTag.length; j++) { cookie = commonTag[j].getElementsByTagName("cookie")[0].childNodes[0].nodeValue; break; } } } if(cookie != null) { document.myForm.elements['myTextArea'].value += "cookie found: " + cookie + "\n"; login(); } } }; } catch(e) { document.myForm.elements['myTextArea'].value += "Exception occurred at connect: " + e.message + "\n"; } } function login() { var loginRequestURL = "http://testconnect.com/api/xml?action=login&login=" + username+ "&password=" + password + "&session=" + cookie; try { xhttp.open("GET", loginRequestURL, true); xhttp.send(); xmlDoc = xhttp.responseXML; xmlDoc.onreadystatechange = function () { alert('in loginResponseHandler'); if(xmlDoc.readyState == 4) { try { loginStatus = xmlDoc.documentElement.childNodes[0].attributes.getNamedItem("code").nodeValue; if(loginStatus == 'ok') { alert("login is good: " + loginStatus); logout(); } else { } } catch(e) {} } }; } catch(e) { } } function logout() { alert("in logout"); try { xhttp.open("GET", logoutRequestURL + cookie, true); xhttp.send(); xmlDoc = xhttp.responseXML; xmlDoc.onreadystatechange = function () { alert("in logoutResponseHandler"); if(xmlDoc.readyState == 4) { try { status = xmlDoc.documentElement.childNodes[0].attributes.getNamedItem("code").nodeValue; if(status == 'ok') { alert(status); } } catch(e) {} } }; } catch(e) {} } so when I run my code in the browser, all my alert stages give me proper message as expected. But at the final alert, it hangs. I just could not figvure out what am i doing wrong. can any one pin point this out for me please? Thanks in advance. KM Basically, I have a Simon Says game with very simple functions but I added an image map with buttons that I now want to use, rather than a table with images as buttons. The problem is, now I can't get the game to work with the image map. Can anyone help me?
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! I have a game page on my site and I am trying to protect direct access to it by .htaccess .htpasswd but is not accepting user name and password? .htaccess: AuthUserFile /home/vhosts/kandcoentertainment.freetzi.com/.htpasswd AuthType Basic AuthName "game1" <Files "cookietest.html"> Require valid-user </Files> .htpasswd test:8888 Any suggestions on why it is not working? What I would like to do is have apay and play once setup but as I am a novice and dont have a clue HELP PLEASE!!! What I have been told is - protect the files, add a client side cookie to game page then upon url payment return validate cookie giving single access and when played the user cannot replay by refresh or just typing in url because cookie expired ? I have tried to write the scripts up with no success. sorry this post is duplicated, the original post:http://www.codingforums.com/showthread.php?t=261488
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! 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, i made a game,where you controll a paddle to bounce back a ball and it hits the bricks on top. The problem is that my eventhandlers don't work after i've added delay function,to make a counter(counting from 3 to 1 before game starts). Any tips?Is it scope problem? Code: var ballx = 100; var bally = 100; //coord x and y,radius of a ball var ballr = 10; var recx; var recy; //coord x and y,width and height of a paddle var recw = 100; var rech = 15; var dx = 2; //x coord step for animated movement of ball var dy = 2; //y coord step for animated movement of ball var rx = 5; //x coord step for animated movement of paddle var WIDTH; //width of main canvas var HEIGHT; //height of main canvas var ctx; //drawn shape var leftDown = false; var rightDown = false; //keyboard arrow buttons var upDown = false; var downDown = false; var mouseXmin; var mouseXmax; var intervalId; var bricks; var NROWS; var NCOLS; var BRICKWIDTH; var BRICKHEIGHT; var PADDING; var y=4; window.addEventListener("load",init,false); //event for loading main func window.addEventListener("keydown",buttonpressed,false); //event for checking if button is pressed window.addEventListener("keyup",buttonreleased,false); //event to check if button is released window.addEventListener("mousemove",mousemoved,false); //event for controlling paddle with mouse movement function init_mouse(){ //initialize coord for mouse movement mouseXmin = document.getElementById('can').offsetLeft; mouseXmax = mouseXmin + (WIDTH-recw); //doesn't work that pretty...check? } function init_bricks(){ //initialize bricks NROWS = 5; NCOLS = 3; BRICKWIDTH = (WIDTH/NCOLS) - 1; BRICKHEIGHT = 15; PADDING = 1; bricks = new Array(NROWS); for(i=0; i<NROWS; i++){ bricks[i] = new Array(NCOLS); for(j=0; j<NCOLS; j++){ bricks[i][j] = 1; } } } function mousemoved(e){ //function that enables movement of paddle with mouse if(e.pageX > mouseXmin && e.pageX < mouseXmax) recx = e.pageX ;//- mouseXmin; <---why would you need that?Movement is bugyy! FIX:) } function buttonpressed(e){ //to check if any of keyboard arrow buttons are pressed if(e.which==37) { leftDown = true; } if(e.which==39) { rightDown = true; } if(e.which==40) { upDown = true; } if(e.which==38) { downDown = true; } } function buttonreleased(e){ //function to check if button up,down,left or right is released if(e.which==37) { leftDown = false; } if(e.which==39) { rightDown = false; } if(e.which==40) { upDown = false; } if(e.which==38) { downDown = false; } } function clear(){ //function to clear the stage ctx.clearRect(0,0,800,600); } function circle(x,y,r){ //function to draw circle shape ctx.beginPath(); ctx.arc(x,y,r,0,Math.PI*2,true); ctx.closePath(); ctx.fill(); } function rect(x,y,w,h){ //function to draw rectangle shape ctx.beginPath(); ctx.rect(x,y,w,h); ctx.closePath(); ctx.fill(); } function checkforCoallision(){ //checks for borders of main canvas and if ball hits the paddle if(ballx + dx > WIDTH-ballr || ballx + dx < ballr) dx = -dx; if(bally + dy < ballr ) dy = -dy; else if (bally + dy > HEIGHT - ballr){ if(ballx + ballr > recx && ballx + ballr < recx + recw) dy = -dy; else {clearInterval(intervalId); alert('Game Over,Baby!');} bounce();} } function draw(){ //function that draws the desired shapes and animates them clear(); //clears the main canvas,so the animation would look smooth checkforCoallision(); //checks for borders of main canvas and if ball hits the paddle if(leftDown) recx -= rx; //enables movement of paddle right and left if(rightDown) recx += rx; for(i=0; i<NROWS; i++){ //drawing bricks for(j=0; j<NCOLS; j++){ if(bricks[i][j] == 1) { //checking if brick exists rect(j * (BRICKWIDTH+PADDING)+PADDING,i * (BRICKHEIGHT+PADDING) + PADDING, BRICKWIDTH, BRICKHEIGHT) } } } //have we hit a brick? rowheight = BRICKHEIGHT + PADDING; colwidth = BRICKWIDTH + PADDING; row = Math.floor(bally/rowheight); col = Math.floor(ballx/colwidth); //if so, reverse the ball and mark the brick as broken if (bally < NROWS * rowheight && row >= 0 && col >= 0 && bricks[row][col] == 1) { dy = -dy; bricks[row][col] = 0; } circle(ballx,bally,ballr); rect(recx,recy,recw,rech); ballx += dx; bally += dy; } /* function init(){ ctx = document.getElementById('can').getContext('2d'); WIDTH = document.getElementById('can').offsetWidth ; //gets the width of main canvas HEIGHT = document.getElementById('can').offsetHeight ; //gets the height of main canvastto recx = WIDTH / 2; //setting the coord x of a paddle recy = HEIGHT - rech; //setting the coord y of a paddle init_mouse(); init_bricks(); intervalId = setInterval(draw,10); //calls draw func on desired interval,which is represented by number next to it return intervalId; } */ function delay() { if(y<=0) { document.getElementById('content2').innerHTML = "<canvas id='can' width='300' height='300'>This text is displayed if your browser does not support HTML5 Canvas.</canvas>"; ctx = document.getElementById('can').getContext('2d'); WIDTH = document.getElementById('can').offsetWidth ; //gets the width of main canvas HEIGHT = document.getElementById('can').offsetHeight ; //gets the height of main canvastto recx = WIDTH / 2; //setting the coord x of a paddle recy = HEIGHT - rech; //setting the coord y of a paddle init_mouse(); init_bricks(); intervalId = setInterval(draw,10); //calls draw func on desired interval,which is represented by number next to it return intervalId; } else { Object = document.getElementById('content2'); y = y - 1; Object.innerHTML = "<div style='text-align:center;width:25em;margin: 0px auto;height:100px;position:absolute;top:50%;margin-top:-50px;'>"+y+"</div>"; setTimeout("delay()", 1000);} } 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 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). Hello, I am trying to create a clock for my video game. I need to begin the clock at zero and count while the game is going. I need to have the clock count in standard minutes and seconds but not be based on the actual time of day. I am coding in javascript for an applet.
Can someone guide me to what I am doing wrong. My book does not show how to do this. This is what I have to far.I am just getting more and more confused. I am suppose to have a button there asking write a timeout that asks users if they want to stop the game if they do not press the Guess button within 10 seconds. They are suppose to pick a number between 1-100. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Guessing Game</title> <script type="text/javascript"> while (runAgain == 'y' || runAgain == 'Y') { guessedNumber = reader.readDouble("Please pick a number between 1 and 100: "); while (guessedNumber != randomNumber) { if (guessedNumber < randomNumber) System.out.println("Too low!\nGuess again!"); else if (guessedNumber > randomNumber) System.out.println("Too high\nGuess again!"); else if (guessedNumber == randomNumber) System.out.println("You got it!"); } runAgain = reader.readChar("Play again (y/n)? "); } </script> </head> <body> <div id="content"> <h2>JavaScript Guessing Game</h2> <p>Enter a number between 1 and 100, then press the Guess button.</p> <form action="myForm" method="post"> <p><input type="text" name="guessgame" /> <input type="hidden" name="eGame" value="1"/> <input type="submit" value=" Guess" name="submit"/></p> </form> </body> </html> 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> Hello all, * I'm very new to javascript and working on a quiz game. Theres a set of code im working on but i need help, and greatly appreciate any help. * After every questions, there is a tick or wrong animation/image that should pop over the answer card. I created the gif file one for a tick and one for a wrong: http://www.freeimagehosting.net/cqn91 http://www.freeimagehosting.net/v74v6 *By right the user should not be able to click on the answer cards anymore after finishing the quiz. For now the score keeps going up although the quiz is done. And after the quiz is done, a button should direct the user to the DetailedResult page, instead of the popup. *How to change the popup into a Html(DetailedResult) page, and instead of a text eg.(resent.jpg), how can I make the real image show, and if the qn is correct, how can I place a tick and if the qn is wrong how can I place a wrong image. Ive created both images. tick image==>http://i1069.photobucket.com/albums/...ttica/tick.jpg wrong image==>http://i1069.photobucket.com/albums/...ca/wrong-1.jpg *Suppose at the bottom of the html page, should have a button for the user to retry only wrong answers. *And how do i keep updating the user score for each attempt he tries on the table. Below are a set of code i'm working on, and another set of Html layout(DetailedResult) which i intend to achieve. Code: <!DOCTYPE HTML> <html> <head> <title> Card Test </title> <style> img { margin:7px; } #Question { text-align:left; font-family:"Vladimir Script"; font-size:40px; } </style> <script type="text/javascript"> // For: http://www.codingforums.com/private....pm&pmid=124136 var baseURL = 'http://s1069.photobucket.com/albums/u475/felettica/'; var questions = [ // format [pic,[image1,imag2,image3]], ['happy.jpg', ['*|delight.jpg','|sad.jpg','|confuse.jpg']], // 0 ['angry.jpg', ['|sad.jpg','*|resent.jpg','|joyful.jpg']], // 1 ['father.jpg',['|sister.jpg','|mum.jpg','*|dad.jpg']], // 2 ['sports.jpg',['|crying.jpg','*|soccer.jpg','|sleep.jpg']], // 1 ['fruit.jpg', ['*|apple.jpg','|meat.jpg','|bacon.jpg']], // 0 ]; var qNo = 0; var correct = []; function $_(IDS) { return document.getElementById(IDS); } function NextQuestion(IDS) { var response; switch (IDS) { case 'image1' : response = 0; break; case 'image2' : response = 1; break; case 'image3' : response = 2; break; } if (response == currentQuestion[4]) { correct[0]++; alert('Well Done'); } else { alert('Wrong Answer'); } correct.push(currentQuestion.join('|')+'|'+response); // alert(correct.join('\n')); qNo++; if (qNo < questions.length) { $_('score').innerHTML = 'Sco '+correct[0]; showImages(qNo); $_('Question').innerHTML = 'Question: '+(qNo+1); } else { $_('score').innerHTML = 'You had '+correct[0]+' correct answers for '+questions.length+' questions'; DisplayQuizResults(); // alert('End of quizi\n\n'+correct.join('\n')); return; } // I created a two .gif animation of a tick and a wrong // but unsure how to place it so that it appears on the // correct answer image instead of the alertbox. // Tick animation Url==> http://www.freeimagehosting.net/cqn91 // Wrong animation Url==>http://www.freeimagehosting.net/v74v6 // I tried to add a button to direct to the DetailedResult page // which shows the correct and wrong questions but it didnt appear. // It should appear after the alert('End of quiz'); pops up. } var currentQuestion = []; function showImages(ptr) { var tarr = []; var tmp = ''; currentQuestion = []; currentQuestion.push(questions[ptr][0]); // 0 temp_questions = questions[ptr][1].slice(); temp_questions.sort(randOrd); for (var i=0; i<3; i++) { tarr = temp_questions[i].split('|') if (tarr[0] != '') { tmp = i; } // save correct answer currentQuestion.push(tarr[1]); // 1,2,3 // save response order } currentQuestion.push(tmp); // 4 $_("Pic").src=baseURL+currentQuestion[0]; $_("image1").src=baseURL+currentQuestion[1]; $_("image2").src=baseURL+currentQuestion[2]; $_("image3").src=baseURL+currentQuestion[3]; } function randOrd() { return (Math.round(Math.random())-0.5); } window.onload = function() { correct = []; correct.push(0); questions = questions.sort(randOrd); showImages(0); } // Following from: http://www.yourhtmlsource.com/javascript/popupwindows.html function DisplayQuizResults() { var generator=window.open('','name','height=400,width=500'); generator.document.write('<html><head><title>Popup</title>'); generator.document.write('<link rel="stylesheet" href="style.css">'); generator.document.write('</head><body>'); var str = ''; var tarr = []; // correct array format: item +|+ question +|+ answer +|+ response var str = '<h1> Your Results</h1>'; for (var i=1; i<correct.length; i++) { tarr = correct[i].split('|'); // item|img1|img2|img3|ans|resp str += 'Question #'+i; str += ' was: '+tarr[0]; str += '<br>Correct answer was: '+tarr[4] +'('+tarr[tarr[4]*1+1]+')'; if (tarr[4] != tarr[5]) { str += ' but your answer was: '+tarr[5] +'('+tarr[tarr[5]*1+1]+')'; } str += '<p>'; } generator.document.write('<p>'+str+'<p>'); generator.document.write('<p><a href="java_script:self.close()">Close</a> the popup.</p>'); generator.document.write('</body></html>'); generator.document.close(); } </script> </head> <body> <div id="Question">Question: 1</div> <div align="center"> <img id="Pic" src="" height="220" width="321"> <p> <img id="image1" src="" width="269" height="171" onclick="NextQuestion(this.id)"> <img id="image2" src="" width="269" height="171" onclick="NextQuestion(this.id)"> <img id="image3" src="" width="269" height="171" onclick="NextQuestion(this.id)"> <p> <span id="score">Sco </span> <p></div> </body> </html> ================================================ Instead of the popup, instead i thought having it on a Html page (DetailedResult), the layout below ================================================ Code: <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> <style type="text/css"> Table{ position:absolute; left:632px; top:97px; width: 408px; border:1px solid black; } table, td, th { border:1px solid green; } th { background-color:green; color:white; } </style> </head> <body> <table width="472" border="0" cellspacing="0" cellpadding="0"> <!--In the table,the scores of the user should appear for the the current attempt and previous attempts so that the user can track his scores--> <tr> <th width="227" scope="row"><strong>My Attempts</strong></th> <td width="181"> <div align="center">My sco </div></td> </tr> <tr> <th height="19" scope="row">1st Attempt</th> <td><div align="center">4/5</div></td> </tr> <tr> <th scope="row">2nd Attempt</th> <td> </td> </tr> <tr> <th scope="row">3rd Attempt</th> <td> </td> </tr> </table> <h1> My Current Attempt </h1> <p> </p> <p>Question 1: "code to get Qn 1 image" "either tick image or wrong image" </p> <!-- For each qn, its picture will appear and either a tick or wrong image next to it. If the user answer it correctly, then a tick will appear or other wise. The image of the question would be smaller. --> <p>Question 2: "code to get Qn 1 image" "either tick image or wrong image"</p> <p>Question 3: "code to get Qn 1 image" "either tick image or wrong image"</p> <p>Question 4: "code to get Qn 1 image" "either tick image or wrong image"</p> <p>Question 5: "code to get Qn 1 image" "either tick image or wrong image"</p> <p><button type="button">Retry Wrong Question</button><p> <!-- direct page to retry wrong qns once more --> <!-- tick image URL:http://i1069.photobucket.com/albums/...ttica/tick.jpg wrong image URL http://i1069.photobucket.com/albums/...ca/wrong-1.jpg baseURL:http://s1069.photobucket.com/albums/u475/felettica/ --> </body> </html> Hi every1! Got a task in university to make a memory game (card matching game). Thats what i've got so far: Code: var selected = 0; var choiceOne; var choiceTwo; var matches = 0; var numOfTries = 0; var interval = 700; var gamePlace = document.getElementById("wrap"); var backcard="img/memoryBg.png"; var timeStart; var timeFinish; var time; function nameEnter(){ var name = prompt("Please enter your name"); if (name != null){ document.title = "Welcome " + name + "!"; } } function game(){ var nOfPairs = document.getElementById("nPairs").value; timeStart = new Date().getTime(); if (nOfPairs==1){ var cards=[]; cards[0] = 'img/card1.png'; cards[1] = 'img/card1.png'; } if (nOfPairs==2){ var cards=[]; cards[0] = 'img/card1.png'; cards[1] = 'img/card1.png'; cards[2] = 'img/card2.png'; cards[3] = 'img/card2.png'; cards.sort(function shuffle(){ return Math.random() - 0.5;}); } if (nOfPairs==3){ var cards=[]; cards[0] = 'img/card1.png'; cards[1] = 'img/card1.png'; cards[2] = 'img/card2.png'; cards[3] = 'img/card2.png'; cards[4] = 'img/card3.png'; cards[5] = 'img/card3.png'; cards.sort(function shuffle(){ return Math.random() - 0.5;}); } if (nOfPairs==4){ var cards=[]; cards[0] = 'img/card1.png'; cards[1] = 'img/card1.png'; cards[2] = 'img/card2.png'; cards[3] = 'img/card2.png'; cards[4] = 'img/card3.png'; cards[5] = 'img/card3.png'; cards[6] = 'img/card4.png'; cards[7] = 'img/card4.png'; cards.sort(function shuffle(){ return Math.random() - 0.5;}); } if (nOfPairs==5){ var cards=[]; cards[0] = 'img/card1.png'; cards[1] = 'img/card1.png'; cards[2] = 'img/card2.png'; cards[3] = 'img/card2.png'; cards[4] = 'img/card3.png'; cards[5] = 'img/card3.png'; cards[6] = 'img/card4.png'; cards[7] = 'img/card4.png'; cards[8] = 'img/card5.png'; cards[9] = 'img/card5.png'; cards.sort(function shuffle(){ return Math.random() - 0.5;}); } if (nOfPairs==6){ var cards=[]; cards[0] = 'img/card1.png'; cards[1] = 'img/card1.png'; cards[2] = 'img/card2.png'; cards[3] = 'img/card2.png'; cards[4] = 'img/card3.png'; cards[5] = 'img/card3.png'; cards[6] = 'img/card4.png'; cards[7] = 'img/card4.png'; cards[8] = 'img/card5.png'; cards[9] = 'img/card5.png'; cards[10] = 'img/card6.png'; cards[11] = 'img/card6.png'; cards.sort(function shuffle() { return Math.random() - 0.5;}); } if (nOfPairs==7){ var cards=[]; cards[0] = 'img/card1.png'; cards[1] = 'img/card1.png'; cards[2] = 'img/card2.png'; cards[3] = 'img/card2.png'; cards[4] = 'img/card3.png'; cards[5] = 'img/card3.png'; cards[6] = 'img/card4.png'; cards[7] = 'img/card4.png'; cards[8] = 'img/card5.png'; cards[9] = 'img/card5.png'; cards[10] = 'img/card6.png'; cards[11] = 'img/card6.png'; cards[12] = 'img/card7.png'; cards[13] = 'img/card7.png'; cards.sort(function shuffle(){ return Math.random() - 0.5;}); } if (nOfPairs==8){ var cards=[]; cards[0] = 'img/card1.png'; cards[1] = 'img/card1.png'; cards[2] = 'img/card2.png'; cards[3] = 'img/card2.png'; cards[4] = 'img/card3.png'; cards[5] = 'img/card3.png'; cards[6] = 'img/card4.png'; cards[7] = 'img/card4.png'; cards[8] = 'img/card5.png'; cards[9] = 'img/card5.png'; cards[10] = 'img/card6.png'; cards[11] = 'img/card6.png'; cards[12] = 'img/card7.png'; cards[13] = 'img/card7.png'; cards[14] = 'img/card8.png'; cards[15] = 'img/card8.png'; cards.sort(function shuffle(){ return Math.random() - 0.5;}); } if(nOfPairs>8||nOfPairs<1){ alert("Please enter the number from 1 to 8"); }else{ for(i = 0; i<=nOfPairs*2-1; i++){ var cardDiv = document.createElement("div"); cardDiv.setAttribute("id",""+i+""); cardDiv.style.height="65px"; cardDiv.style.width="65px"; cardDiv.style.float='left'; gamePlace.appendChild(cardDiv); document.getElementById(""+i+"").innerHTML='<img src="img/memoryBg.png">'; cardDiv.onclick=function(){cardClick(this.id);}; } } function cardClick(card){ if (selected==2){ return ; } if (selected==0){ choiceOne=card; document.images[card].src = cards[card]; selected = 1; }else { selected = 2; choiceTwo = card; document.images[card].src =cards[card]; var timer=setInterval(checking,interval); } function checking() { clearInterval(timer); numOfTries++; document.getElementById("tries").innerHTML = numOfTries; if (cards[choiceTwo]==cards[choiceOne]){ matches++; document.images[choiceOne].src = "img/memoryBgI.png"; document.images[choiceTwo].src = "img/memoryBgI.png"; //choiceTwo.onclick=null; } else { document.images[choiceOne].src = "img/memoryBg.png"; document.images[choiceTwo].src = "img/memoryBg.png"; selected = 0; return ; } if (matches == nOfPairs){ timeFinish = new Date().getTime(); time = Math.round (((timeFinish - timeStart)/1000)); alert("Congrats! You needed " + numOfTries + " tries, and " + time + " seconds."); } selected = 0; return ; } } } so the problem is, that I can just click 2 times on one card and it will look like a coincidence. My second problem is that when I have a real coincidence, I can still click on that card (by "real coincidence" i mean two same pics. so when i find them, they have to be not active, and when im clicking on them, they should just simply do nothing.). Can someone help me? What I'm trying to achieve is it initialises a number between 1-2000 randomly. When the submit button is clicked it simply returns if the number that is in putted is higher or lower than the randomly initialised number. External JavaScript: Html Code: <html> <head> <script type="text/javascript" src="jsscri.js"></script> </head> <body onload="initialisation ()"> <form name="exampleform"> <h3> Number: <input name="number" type="text" onchange='checkNumber( this.value );'> </h3> <p> <input name="submit" type="button" value="Guess" onclick= 'checkValue()';/> </p> </body> </html> If you load this onto a webpage you'll see what i'm trying to do. I tried deleting the rest of the code to keep the size of the code down. Hello everyone. I have a tic tac toe game I am working on and I managed to make it so you can place X's and O's respectively. My next problem is making a win condition so it checks to see if the X's won the game or the O's did. Here is what I have so far. Edit fiddle - JSFiddle What I am basically thinking is that when you are clicking I want whatever letter it is that is placed to be saved and then I can check to see if all 3 are equal to that letter. It is a bit hard to explain. Essentially I want to make a win condition. If anyone could throw some assistance my way that would be great. I know for sure it requires a lot of checks because there are so many different ways of winning, I just need to know that initial one. Thank you very much. |