JavaScript - Beginner. Need Help Finishing A Simple Shoot Em Up Game!!!!
I am trying to create a simple shoot em up on java and it is due by tomorrow 5/2.
I need help making the gun I have created, shoot up to 10 bullets using the space bar. Also, I need some kind of either bullet countdown bar or something to show the shooter the number of bullets that he has left to shoot out of 10. So far I have created the Ufo's that bounce around the screen randomly and the gun that moves along the bottom using the arrow keys. When a Ufo huts the gun the game ends and goes to a blank screen. Here is what I have so far: Code: //Shoot.java import acm.graphics.*; import acm.program.*; import java.awt.event.*; import java.awt.*; import acm.util.*; public class Shoot extends GraphicsProgram { public static final int APPLICATION_WIDTH = 800; public static final int APPLICATION_HEIGHT = 500; final int AW=APPLICATION_WIDTH; final int AH=APPLICATION_HEIGHT; final int WAIT=5; final int MV_AMT=5; final int JUMP_AMT=100; final int U_SIZE=30; int xMove,yMove; UFO u1,u2,u3; public void init() { u1=new UFO(); u2=new UFO(); u3=new UFO(); RandomGenerator rg= new RandomGenerator(); int rand1= rg.nextInt(0,AW-50); int rand2= rg.nextInt(0,AW-75); int rand3= rg.nextInt(0,AW-100); add(u1,rand1,0); add(u2,rand2,0); add(u3,rand3,0); xMove=yMove=0; addKeyListeners(); }//init public void keyPressed(KeyEvent e) { int key = e.getKeyCode( ); if (key == KeyEvent.VK_RIGHT) { xMove = MV_AMT ; } else if (key == KeyEvent.VK_LEFT) { xMove = -MV_AMT ; } } //keyPressed public void run() { RandomGenerator rg =new RandomGenerator(); GRectangle u1Box, u2Box, u3Box, g1Box; int xMove1=1,xMove2=1,xMove3=1; int yMove1=1,yMove2=0,yMove3=1/4; boolean u1Done=false, u2Done=false, u3Done=false; GUN g1=new GUN(); add(g1,300,480); xMove=yMove=0; addKeyListeners(); waitForClick(); while(true) { u1.move(xMove1,yMove1); u2.move(xMove2,yMove2); u3.move(xMove3,yMove3); u1Box=u1.getBounds(); u2Box=u2.getBounds(); u3Box=u3.getBounds(); g1Box=g1.getBounds(); pause(WAIT); g1.move(xMove,yMove); xMove=yMove=0; //intersections if(u1Box.intersects(g1Box)==true) {g1.setVisible(false); u1.setVisible(false); u2.setVisible(false); u3.setVisible(false); break; } if(u2Box.intersects(g1Box)==true) {g1.setVisible(false); u1.setVisible(false); u2.setVisible(false); u3.setVisible(false); break; } if(u3Box.intersects(g1Box)==true) {g1.setVisible(false); u1.setVisible(false); u2.setVisible(false); u3.setVisible(false); break; } //at top of window if (u1.getY( ) == 0) { yMove1 = -yMove1 ; } if (u2.getY( ) == 0) { yMove2 = -yMove2 ; } if (u3.getY( ) == 0) { yMove3 = -yMove3 ; } //at left or right side if ((u1.getX( ) <= 0) || (u1.getX( ) + U_SIZE >= AW)) { xMove1 = -xMove1 ; } if ((u2.getX( ) <= 0) || (u2.getX( ) + U_SIZE >= AW)) { xMove2 = -xMove2 ; } if ((u3.getX( ) <= 0) || (u3.getX( ) + U_SIZE >= AW)) { xMove3 = -xMove3 ; } //at bottom of window if (u1.getY( ) == 450) { yMove1 = -yMove1 ; } if (u2.getY( ) == 450) { yMove2 = -yMove2 ; } if (u3.getY( ) == 450) { yMove3 = -yMove3 ; } } } } Thank you so much Courtney 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> Can some please help me. I'm really new at this and is having trouble with this simple example Code: <html> <head> <script type="text/javascript"> //Below i was trying to set up a var pam that includes some text //and the value of form field name pamcheck and then display that result of pam on the screen //using a check box with a value of 'pale ale malt' hoping that when the ckeck box is checked //and then user clicks submit the result would be displayed on the screen as // 'Your selected malt is Pale ale malt' function pamff1() { pam = ("<p>Your selected malt is <p>" + pamcheck); document.write(pam); } </script> </head> <body> <form onsubmit="pamff1();"> <input type="checkbox" name="pamcheck" value="Pale ale malt" > <input type="submit" value="Submit"> </form> </body> </html> 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?
I have a simple project that is getting me stuck. The current submission is included. The question is: Write a class named Acc2 containing: An instance variable named sum of type integer, initialized to 0. A method named getSum that returns the value of sum . This is my current sumbission: public class Acc2 { private int sum = 0; public int getSum (){method sum;} } The system says that the only thing wrong with it is the bold word method. I have tryed many things in place of it however I am unable to move on. Okay I'm writing a JavaScript application that would prompt the user for a number between 0 and 2, generate a random number for the computer, then take that input and display two images (in this case two hands making rock, paper, or scissor symbols at each other) using an array, and displaying text indicating a win, draw, or loss. I'm having a lot of problems getting this to work as I am new to JavaScript and am wondering if anyone could help me fix this problem. I just want the input from the prompt AND the random number to translate to what in the array should be displayed and what text is then shown at the bottom. Any comments/advice/help is greatly appreciated! By the way for some reason it doesn't let the letters H T M L show up together so that is where the ellipses are showing up! Code: <script type = "text/javascript"> selection = prompt("Enter 0 for rock, 1 for paper, and 2 for scissors") userChoice = parseInt(selection) arrayHolder = new Array(); arrayHolder[0] = "rock.jpg"; arrayHolder[1] = "paper.jpg"; arrayHolder[2] = "scissors.jpg"; compchoice = Math.floor(Math.random()*arrayHolder.length) function playGame(idholder1) { document.images["userpic"].src = arrayHolder[userchoice]; document.images["comppic"].src = arrayHolder[compchoice]; if (userChoice == 0 && compchoice == 0) { document.getElementbyId(idholder1).innerHTML = "DRAW!" } else if (userChoice == 0 && compchoice == 1) { document.getElementbyId(idholder1).innerHTML = "Paper beats Rock, you lose!" } else if (userChoice == 0 && compchoice == 2) { document.getElementbyId(idholder1).innerHTML = "Rock beats Scissors, you win!" } else if (userChoice == 1 && compchoice == 0) { document.getElementbyId(idholder1).innerHTML = "Paper beats Rock, you win!" } else if (userChoice == 1 && compchoice == 1) { document.getElementbyId(idholder1).innerHTML = "Draw!" } else if (userChoice == 1 && compchoice == 2) { document.getElementbyId(idholder1).innerHTML = "Scissors beats Paper, you lose!" } else if (userChoice == 2 && compchoice == 0) { document.getElementbyId(idholder1).innerHTML = "Rock beats Scissors, you lose!" } else if (userChoice == 2 && compchoice == 1) { document.getElementbyId(idholder1).innerHTML = "Scissors beat Paper, you win!" } else if (userChoice == 2 && compchoice == 2) { document.getElementbyId(idholder1).innerHTML = "Draw!" } } </script> </head> <body> <p> <center><img src="rock.jpg" width="197" height="171" alt="rock" id="userpic" /><img src="paper.jpg" width="210" height="95" id="comppic" /><br /> <h1 id="gametext" onLoad="playGame('gametext')">ROCK PAPER SCISSORS SHOOT!</h1></center> </p> I'm developing a simple game that involves a system of interconnected nodes with unidirectional travel between nodes (similar to the circulation system!). The goal of the game is to get from a starting node to an ending node, which can be a variable number of nodes away. The program picks a random starting point, then randomly chooses one of its connecting nodes (cNodes) and pushes it onto a pathArray. A cNode is randomly chosen from this new node and it is pushed onto the pathArray. This continues for a designated number of turns, thus generating a pathArray (invisible to the player). The last element in the pathArray is the endNode and the goal of the puzzle. At each node the player is given two options of travel (though there may be more than two ways to go). One of these options MUST be the correct way if the player has not deviated from the path up until that point. If the player has deviated, this option can be any cNode. The other node is any cNode that does not lead to the endNode. The following code contains a simplified list of nodes that represents the content in my game. The function, however, is taken word for word. In this snippet, the pathArray & startNode have already been generated and I am trying to resolve how to assign "nodeChoice" as either the correct direction of travel (for a player on the correct path) or any random cNode (for a player who has deviated from the path). Keep in mind that the pathArray and cNodes lengths can be any size. Code: <script> //NODES: var nodeA = {name:"A"}; var nodeB = {name:"B"}; var nodeC = {name:"C"}; var nodeD = {name:"D"}; var nodeE = {name:"E"}; var nodeF = {name:"F"}; var nodeG = {name:"G"}; var nodeH = {name:"H"}; var nodeI = {name:"I"}; var nodeJ = {name:"J"}; var nodeK = {name:"K"}; //An array of all nodes in the system: var systemArray = [nodeA, nodeB, nodeC, nodeD, nodeE, nodeF, nodeG, nodeH, nodeI, nodeJ, nodeK]; //Connecting Nodes (cNodes): //(uni-directional, but cyclical) nodeA.cNodes = [nodeB, nodeC]; nodeB.cNodes = [nodeD, nodeE, nodeF]; nodeC.cNodes = [nodeF, nodeG]; nodeD.cNodes = [nodeI, nodeH]; nodeE.cNodes = [nodeJ]; nodeF.cNodes = [nodeK]; nodeG.cNodes = [nodeK]; nodeJ.cNodes = [nodeA]; nodeK.cNodes = [nodeA]; nodeI.cNodes = [nodeA]; nodeH.cNodes = [nodeA]; //The path chosen (generated from code not included here) var pathArray = [nodeA, nodeB, nodeE, nodeJ]; //nodeChoice will represent a cNode from any given node var nodeChoice; //chooseNode is supposed to assign nodeChoice the next element in pathArray if the player on on the right path (if at nodeB, nodeChoice = nodeE). //However, if the user has taken a different path, its cNodes will not be in pathArray in which case a random cNode is assigned to nodeChoice function chooseNode(_node) { //check each cNode to see if any are in pathArray for (var j = 0; j < _node.cNodes.length; j++) { //if a cNode is in pathArray, then we know to assign it nodeChoice... if (_node.cNodes[j] in pathArray) { nodeChoice = _node.cNodes[j]; console.log("choiceNode CORRECT: " + nodeChoice.name); //(for debugging purposes only) } //...otherwise don't do anything in this forLoop/ifStatement }; //if by this point nodeChoice is still undefined, meaning none of the current node's cNodes are in pathArray, assign it any one of its cNodes. if (nodeChoice == undefined) { nodeChoice = _node.cNodes[Math.floor(Math.random()* _node.cNodes.length)]; console.log("choiceNode INCORRECT: " + nodeChoice.name);//(for debugging purposes only) }; }; //Runtime: chooseNode(nodeB); //Result should be only nodeE.name since nodeD is not in the pathArray... console.log(nodeChoice.name); </script> ...however, nodeChoice is assigned either D, E or F randomly and we are given the troubleshooting statement "choiceNode INCORRECT: D (or) E (or) F", indicating that the if-in statement is always ignored. I know that the if-in statement doesn't work but am not sure how else to write it so that each cNode is compared the each element in pathArray, both of which can be of variable lengths... I dont know how im gonna achieve this but i have an image slider i made (images slide of to the right, new one comes on from the left) however i need them to disappear when they leave the container there in. If anyone can help me code this would be greatly appreciated . Heres what i have. Also it wont properly cycle through my array so if anyone can help me fix that would be great too . Code: <h1>Image slider</h1> <span id="number"></span> <div id="sliderContainer"> <div id="leftButton"><a href="#" id="slideLeft"><</a></div> <div id="rightButton" onclick="moveRight()">></div> <div id="gallery"><img id="theImage" height="400" style="position:relative;left:0px;" /></div> </div> <script type="text/javascript"> var theImages=["images/a.jpg","images/b.jpg","images/c.jpg", "images/d.jpg", "images/e.jpg"]; // Build the array of text var arrayRows = theImages.length; //Get the length of the array (Note: This starts at 1 not 0 like the array) var i=0; //Set a counter document.getElementById('theImage').src = theImages[0]; document.getElementById('number').innerHTML = arrayRows - 1; function moveRight1() { var pp = document.getElementById("theImage"); var lft = parseInt(pp.style.left); var tim = setTimeout("moveRight1()",1); // 1 controls the speed lft = lft+15; // move by 15 pixels pp.style.left = lft+"px"; if (lft > 600) { // left edge of image past the right edge of screen clearTimeout(tim); pp.style.left = "-600px"; i++; if (i >= (arrayRows - 1)) { i = 0; } moveLeft1(); } } function moveLeft1() { document.getElementById('theImage').src = theImages[i]; var pp = document.getElementById("theImage"); var lft = parseInt(pp.style.left); var tim = setTimeout("moveLeft1()",1); // 1 controls the speed lft = lft+15; // move by 15 pixels pp.style.left = lft+"px"; if (lft > 0) { // left edge of image past the right edge of screen pp.style.left = "0px"; clearTimeout(tim); } document.getElementById('number').innerHTML = i; } </script> Also any general improvements will be good too 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! 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. 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. I am very new to JavaScript and I am currently following the Eloquent JavaScript book online. On one of the exercises, we are told to make a function that returns the range of the inputs in an array. I tried this code below but it doesn't seem to work. The problem seems to be in the "If" function because if I change the condition to (start < end) it seems to work. Can someone please explain to me why this is? function range (start, end) { var j = []; if (start > end) { for (i = start; i <= end; i++) { j.push(i); } } else { for (i = start; i >= end; i--) { j.push(i); } } return j; } console.log(range(10, 2)); console.log(range(2, 10)); Reply With Quote 01-26-2015, 08:49 PM #2 Labrar View Profile View Forum Posts New Coder Join Date Jun 2008 Posts 65 Thanks 0 Thanked 12 Times in 12 Posts Why you do not use something like this var range = function(start, end, step) { var range = []; var typeofStart = typeof start; var typeofEnd = typeof end; if (step === 0) { throw TypeError("Step cannot be zero."); } if (typeofStart == "undefined" || typeofEnd == "undefined") { throw TypeError("Must pass start and end arguments."); } else if (typeofStart != typeofEnd) { throw TypeError("Start and end arguments must be of same type."); } typeof step == "undefined" && (step = 1); if (end < start) { step = -step; } if (typeofStart == "number") { while (step > 0 ? end >= start : end <= start) { range.push(start); start += step; } } else if (typeofStart == "string") { if (start.length != 1 || end.length != 1) { throw TypeError("Only strings with one character are supported."); } start = start.charCodeAt(0); end = end.charCodeAt(0); while (step > 0 ? end >= start : end <= start) { range.push(String.fromCharCode(start)); start += step; } } else { throw TypeError("Only string and number types are supported"); } return range; } Thats pretty similar to php range Reply With Quote 01-26-2015, 09:25 PM #3 Old Pedant View Profile View Forum Posts Supreme Master coder! Join Date Feb 2009 Posts 28,310 Thanks 82 Thanked 4,754 Times in 4,716 Posts Ignore Labrar's ridiculously complicated answer to a very simple problem. Instead look CAREFULLY at this code: Code: if (start > end) { for (i = start; i <= end; i++) { Let's use your first example, where you call range(10, 2) So start is 10. And end is 2. So you get to if ( start > end ) and JavaScript executes that as if ( 10 > 2 ) Indeed, 10 *IS* greater than 2, yes? SO you the go execute the NEXT line: for (i = start; i <= end; i++) Which, of course, JavaScript then executes as for (i = 10; i <= 2; i++) But then 10 is *IMMEDIATELY* <= 2. So the for loop NEVER RUNS. All you need to do to fix your code is change Code: if (start > end) { into Code: if (start < end) { PRESTO! ********** The tiniest bit of debugging using your JavaScript debugger would have found this. But also just learning to THINK like the computer would help. Actually run the code in your head, using your example numbers, and you'd see where you went wrong. Hi there, im wondering if you can help me i need help in finding javascript resources to build my skills and knowledge of Jscript because im a beginner. Please help I will start off by saying yes this is homework but I only want help. I'm trying to make the content show up in the read only boxes but I can't figure out where I'm going wrong. My test page can be found at http://sidewalk-cafe.com/test/maddox-hw2a.html. It's small. Any help would be appreciated. Code: function orderForm() { var formDaysStaying = document.getElementById("daysStaying").value; var formSeason = document.getElementById("season").value; var formPropertyType = document.getElementById("propertyType").value; document.getElementById("FEE").value = "$" + today.toFixed(2); document.getElementById("totalCost").value = "$" + today.toFixed(2); document.getElementById("today").value = "$" + today.toFixed(2); document.getElementById("due").value = "$" + due.toFixed(2); } function formTotalCost(form) { const FEE = 55; var totalCost = (formPropertyType * formSeason) * formDaysStaying; var today = totalCost * .10; var due = (totalCost + FEE) - today; if (document.getElementById("daysStaying").value == "" || isNaN(document.getElementById("daysStaying").value)) alert("Please provide the number of days you will be staying."); // Submit the order to the server form.submit(); } hello! i have a problem: i want to change the height of my side bar as long as the text in the center of page long, it means when I have for ex 3 news in a page the side bar which have a background color must be increase to fit the long of text(3 news). i think it will do by javascript but i'm not sure! i my question isn't clear please tell me to explane more i really need it, 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> 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 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? 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.
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);} } |