JavaScript - Javascript 2d Game, Item Spawn, Fullscreen Mode, Time Limit
This is my first javascript game and it's pretty much built of code I've gathered over
time and cleaned up. Here's a manipulated screenshot of what I'm trying to accomplish. You're an ant and you want those goodies on the map as quickly as possible! click this link to view a bigger manipulated screenshot click this link to view the goodies (items) The ant is the playable character you control by using the arrow keys. Every time you load the page, or click "restart game", three new items will spawn randomly on the level and the time will be reset to 0 seconds. An arrow key must be pressed to start the time counter and the game itself. There are only 5 items so far, cheese, apple, banana, candy and donut. The items are supposed to be collected as quickly as possible, when the last item has been collected (by simply running over it) the game will end, save the time and display a hi-score list. Time limit is 30 seconds, the game will display a classic "GAMER OVER" if the limit is overrided. Problems I'm trying to solve: 1: Fullscreen mode (and make the ant actually STAY on the screen) I want the game level to adapt itself to the computer screen. The game dimensions are 1000x600px at the moment but the ant does not respect the level dimensions. Screenshot: http://i41.tinypic.com/kc1j81.jpg. I have a feeling about that somekind of percental code has to be implented but I've never done this before. (Please note that the size of the ant and the items will remain as they are) 2: Spawning three items randomly on the level I drew 5 items and saved them as 100x100 PNG. Three of these items have to spawn at a random location on the fullscreen level. The LAST item collected must trigger the time counter to stop. The time will later be used on the hi-score list where he/she can type her nickname. This information will be uploaded to a database. 3: 30 second time limit Letting the time counter reach 30 seconds will trigger a "GAME OVER". The only way to try again is page refresh or "restart game". Code: <html> <head> <style type="text/css"> div#game { width:1000px; height:600px; position:absolute; background:#c3c3c3; } </style> <script type='text/javascript'> // movement vars var xpos = 100; var ypos = 100; var xspeed = 1; var yspeed =1; var maxSpeed = 5; // boundary var minx = 0; var miny = 0; var maxx = 1000; // characters movement field, width var maxy =600; // characters movement field, height // controller vars var upPressed = 0; var downPressed = 0; var leftPressed = 0; var rightPressed = 0; function slowDownX() { if (xspeed > 0) xspeed = xspeed - 1; if (xspeed < 0) xspeed = xspeed + 1; } function slowDownY() { if (yspeed > 0) yspeed = yspeed - 1; if (yspeed < 0) yspeed = yspeed + 1; } function gameLoop() { // change position based on speed xpos = Math.min(Math.max(xpos + xspeed,minx),maxx); ypos = Math.min(Math.max(ypos + yspeed,miny),maxy); // or, without boundaries: // xpos = xpos + xspeed; // ypos = ypos + yspeed; // change actual position document.getElementById('character').style.left = xpos + "px"; document.getElementById('character').style.top = ypos + "px"; // change speed based on keyboard events if (upPressed == 1) yspeed = Math.max(yspeed - 1,-1*maxSpeed); if (downPressed == 1) yspeed = Math.min(yspeed + 1,1*maxSpeed) if (rightPressed == 1) xspeed = Math.min(xspeed + 1,1*maxSpeed); if (leftPressed == 1) xspeed = Math.max(xspeed - 1,-1*maxSpeed); // deceleration if (upPressed == 0 && downPressed == 0) slowDownY(); if (leftPressed == 0 && rightPressed == 0) slowDownX(); // loop setTimeout("gameLoop()",10); } function keyDown(e) { var code = e.keyCode ? e.keyCode : e.which; if (code == 38) upPressed = 1; if (code == 40) downPressed = 1; if (code == 37) leftPressed = 1; if (code == 39) rightPressed = 1; } function keyUp(e) { var code = e.keyCode ? e.keyCode : e.which; if (code == 38) upPressed = 0; if (code == 40) downPressed = 0; if (code == 37) leftPressed = 0; if (code == 39) rightPressed = 0; } </script> </head> <body onload="gameLoop()" onkeydown="keyDown(event)" onkeyup="keyUp(event)" bgcolor='gray'> <!-- level --> <div id="game"></div> <!-- ant character --> <img id='character' src='images/ant.png' style='position:absolute;left:500px;top:500px;height:125px;width:200px;'/> </body> </html> Similar TutorialsHi Peers, i have a Drop down list with 10 choices (skillset). users must choose one skillset and the corresponding level (beginer/intermediate/master). ( they have to do this 10 times for all the sillsets) what i want is : 1 - i need to show up only one record (dropdowanlist) with level then have a button to add new skill and level if required 2- then when they choose the 1st skill from the dropdown , this one will not show up on the 2nd choice dropdown. is it possible any help ? thanks guys Hi, well making a page fullscreen is one of my favorite topics but whenever I have thought of doing it, I have always received one answer and that is, it is only done with flash. For the first time today I saw one that is not done with flash, can someone tell me how exactly it is done, so I could atlast full my dream of using it ^^ here is the image http://content.screencast.com/users/...04-13_0001.png and here is the link to the page where this fullscreen button exists. http://tutorialzine.com/2010/09/html...deshow-jquery/ i'm trying to get this effect http://css-tricks.com/3458-perfect-f...kground-image/ except, instead of using an image, i would like to use a javascript image gallery. I was playing around with smoothgallery2.0 but I don't really care which I use as long as I'm just displaying images (no text) and there is a smooth fade effect (since the images are pretty high res). thanks so much in advance! Hello, Is there any way that I can add a limit for the amount of time that a javascript loader bar stays on screen? The specific loading screen I am using is http://www.fliesen-info-spanien.net/loadbox.php. This loading box actually activates once the page is loaded apparently, but in my instance, it is loading then disappearing in the matter of a second, but I wouldnt mind leaving it up for a couple of seconds, say 3-5. Is there any line of code I can add to do this? Andy hi, i am now playing with the time. can you please tell me how to make the time move in downwards, i mean a countdown like format, e.g the time will start countdown and end in 2 days? here's my initial noob code for creating time Code: <script type="text/javascript"> var today = new Date(); h = today.getHours(); m = today.getMinutes(); s = today.getSeconds(); function showDate(){ if(document.getElementById('but').value = "locked"){ h = checktime(h); m = checktime(m); s = checktime(s); } document.getElementById('t').innerHTML = h +":"+m+":"+s; } function checktime(i){ if(i < 10){ i = "0" + i; } return i; } function ocl(){ var x = true; if(x){ document.getElementById('but').value = "locked"; showDate(); } } function mo(){ document.getElementById('but').value = "lock me ?"; x = false; } </script> <h3> <a id="t"></a> </h3> <input type="button" id="but" value="unlocked" onmouseover="mo();" onclick="ocl();" /> 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! 1 down vote favorite I do have the countdown script (see link below) to display the time between current time and the date given in real-time. However, I want to achieve to display the time difference between a given start and end time. Right now, it calculates from the current server time to the end time. I want to be able to set up my own start time and end time. Here is what I have: http://jsfiddle.net/BgEtE/ thank you for help 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++; } } } } 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> 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). Hi, well i searched at google and was not exactly able to find what i was looking for, i am looking for a script the shows by logo while loading the game at back end, shows loading percentage or bar representing how game is loaded and then makes the my logo disappear once the game is loaded e-g like this site has used http://www.gamegape.com/en-2095-elemental-battles.html if some thing like this is not available can someone atleast tell me how this site has done it, so we could copy it from them ^_^ 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! Hi there, On this website: http://www.lutanho.net/stroke/online.html it's allowed to "copy the games to your PC and play them offline". That's nice but how do I do that? I've tried to download/copy the game "WordGrid" to my PC but it didn't work. Help would be appreciated. Thanks in advance........... Hey all, I'm trying to code a javascript game for my final project as a mini game within an interactive website, but I'm having some problems since I don't know javascript. It's supposed to be a piano game with a specific pattern to one song (so the game has the same pattern everytime) and I can't get it to work. This is my code right now (I started working with a code I found online). I'm really struggling, if anyone has any ideas on what I'm doing wrong it would be greatly appreciated! Code: <SCRIPT LANGUAGE="JavaScript"> <!-- Original: Brian Gosselin (bgaudiodr@aol.com) --> <!-- Web Site: http://www.bgaudiodr.iwarp.com --> <!-- This script and many more are available free online at --> <!-- The JavaScript Source!! http://www.javascriptsource.com --> <!-- Begin var image_directory = "http://www.your-web-site-address-here.com/simon-says-pics/"; var ok = false; var pcbusy = false; var userturn = true; var butdown = false; var stage = 1; var cnt = 1; var pcclicks = new Array(); var userclicks = new Array(); var pos; var tst = true; var msg = "Click Go!"; btn1 = new Image(); btn1.src = image_directory + "purple.gif"; btn2 = new Image(); btn2.src = image_directory + "yellow.gif"; function updown(isdn) { if (isdn) { document.f[('pl'+pos)].src = image_directory + 'yellow.gif'; } else { document.f[('pl'+pos)].src= image_directory + 'purple.gif'; } } function getPattern() { if(stage=1) return new Array(1); if(stage=2) return new Array(1,2); if(stage=3) return new Array(1,2,3); if(stage=4) return new Array(1,2,3,4); if(stage=5) return new Array(1,2,3,4,5); if(stage=6) return new Array(1,2,3,4,5,6); else return new Array(1,2,3,4,5,6,7); } function dopc() { document.f.st.value = stage; if (cnt <= stage) { pcbusy = true; userturn = false; document.f.s.value = getPattern()[0]; pos=getPattern()[cnt - 1]; setTimeout("updown(true)",500); setTimeout("updown(false) ; pcclicks[cnt]=pos; cnt++; dopc()",1200); } else { userclicks = new Array(); cnt = 1; document.f.s.value = "Player's Turn"; pcbusy = false; userturn = true; document.f.b.focus(); } } function testclicks() { tst = true; for(i = 1;cnt > i; i++) { if (pcclicks[i] == userclicks[i]) { tst = true && tst; } else { tst = false && tst; } } if(tst) { setTimeout("stage++ ; document.f.st.value=stage ; alert('That is correct! Advancing to the next level....'); document.f.s.value=msg ; document.f.b.focus()",300); } else { setTimeout("stage=1 ; cnt=1 ; pcclicks=new Array() ; document.f.st.value=stage ; alert('Sorry, that is not correct. Start a new game if you would like to play again.') ; document.f.s.value=msg",300); } cnt = 1; } function testclk(downflag, pos) { if (userturn&&(!pcbusy)) { if (downflag) { document.f[('pl'+pos)].src = image_directory + 'yellow.gif'; }else{ document.f[('pl'+pos)].src = image_directory + 'purple.gif'; } if (ok && !downflag) { userclicks[cnt] = pos; cnt++; if (pcclicks.length == userclicks.length) { testclicks(); } } } } // End --> </script> </HEAD> <!-- STEP TWO: Copy this code into the BODY of your HTML document --> <BODY> <embed src="G#.wav" autostart="false" hidden="true" name="sound1" enablejavascript="true"> <!-- <a href="#" onclick="playSound('G#.wav');"></a> !--> <img src="piano.png" /> <center> <form name="f"> <table cellspacing="20" cols="8" width="600"> <tr height="60"> <td align="center" width="20%"><img src="purple.gif" onclick="playsound('G#.wav')"; name="1" onMousedown="testclk(true,1)" onMouseup="testclk(false,1)"></td> <td align="center" width="20%"><img src="purple.gif" name="2" onMousedown="testclk(true,2)" onMouseup="testclk(false,2)"></td> <td align="center" width="20%"><img src="purple.gif" name="3" onMousedown="testclk(true,3)" onMouseup="testclk(false,3)"></td> <td align="center" width="20%"><img src="purple.gif" name="4" onMousedown="testclk(true,4)" onMouseup="testclk(false,4)"></td> <td align="center" width="20%"><img src="purple.gif" name="5" onMousedown="testclk(true,5)" onMouseup="testclk(false,5)"></td> <td align="center" width="20%"><img src="purple.gif" name="6" onMousedown="testclk(true,6)" onMouseup="testclk(false,6)"></td> <td align="center" width="20%"><img src="purple.gif" name="7" onMousedown="testclk(true,7)" onMouseup="testclk(false,7)"></td> <td align="center" width="20%"><img src="purple.gif" name="8" onMousedown="testclk(true,8)" onMouseup="testclk(false,8)"></td> </tr> <tr height = 60> <td width="20%" align="center"><font size="3">Level<br></font><input type="text" size="2" value="1" name="st" readonly></td> <td align="center" colspan="3"><input type="text" name="s" value="Click 'Go!' to start" readonly></td> <td align="center"><input type="button" value=" Go! " name="b" onClick="ok=true ; if(!pcbusy) dopc()"></td> </tr> </table> </form> </center> <p><center> <font face="arial, helvetica" size="-2">Free JavaScripts provided<br/> by <a href="http://javascriptsource.com">The JavaScript Source</a></font> </center><p> <!-- Script Size: 4.21 KB --> 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> can u like make games like pong wikth javascript? my friend said he did, but i dont think u can.
|