JavaScript - While Loop Problems For Hangman Game
Hi all,
I am working on a hangman game and have got myself into a bit of muddle with designing the function that prompts the user to enter a letter and then checks it hasn't already been entered, if it has it asks them to enter a different letter. I basically want each letter that is entered to be added to the var allGuesses, then each new entry should be compared against this - however it's not looping at the moment and I don't really know where to go from here.. Am I close? Or miles off? function getInput(aString) { var allGuesses = ''; var inputCharacter = window.prompt("Pick a single lower-case character", "") while (inputCharacter == allGuesses.indexOf(-1)) { reInputCharacter = window.prompt("You have picked " + inputCharacter + " already. Pick another single lower-case character", "") } allGuesses = allGuesses + inputCharacter document.write(allGuesses) } Any advice would be much appreciated! Similar TutorialsHey guys, I just started to create my first Javascript game. It is a platformer and i just cant figure out how to do the movement. ATM my "character" is just a black rectangle. Here is my code. I have not been able to find the bug. var c = document.getElementById("mainCanvas"); var ctx = c.getContext("2d"); var level1 = new Image(); level1.src = "Textures/level1.png" level1.addEventListener("load", function() {ctx.drawImage(level1, 0,0,1024,1024) ctx.fillRect(playerX, playerY, 55, 118)}) //Charecter Position var playerX = 512 var playerY = 512 //Render function playerRender() {ctx.fillRect(playerX, playerY, 55, 118)} window.addEventListener("keydown", function(evt){ if (evt.keycode == 87) {playerY-=10} }) var RenderPlayerInterval = setInterval(playerRender() ,10) Reply With Quote 01-25-2015, 12:34 AM #2 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 Code: ctx.fillRect(playerX, playerY, 55, 118)}) //Charecter Position var playerX = 512 var playerY = 512 When you *CALL* that fillRect, neither playerX nor playerY has yet been defined! SO you are essentially doing Code: ctx.fillRect( null, null, 55, 118) And where are the semicolons on the end of EACH LINE. Yes, I know they aren't required. But put them in. It will save you from grief someday. import java.util.Scanner; import java.util.Arrays; /*********************************************************** * WordGuess game is a Hangman like game for two (or more) * players. This is a two player version *The game of Hangman involves one player making a word and a second * player guessing the word by guessing each letter in turn. If the guessing *player cannot get it in 6 (or so depending on the version) tries, the other *player wins. If the guesser gets it in the requisite number of tries, then the *guesser wins. This is a variant of the Hangman game involving two players *guessing against each other. * * * @author JavaFish * @I can't seem to get my loop working....it's not behaving like i want it to. ***********************************************************/ public class WordGuess { private Scanner kb; // use for all keyboard entry private Player player1; // first player private Player player2; // second player private WordBank wordList; // the dictionary to use /* alternate instance variable for the players deactivate the individual players if you choose to use this version. */ // private Player[] players; /********************************************************* * Explicit value constructor that builds a random dictioinary * * @param player1 The name of player1 * @param player2 The name of player2 ********************************************************/ public WordGuess(String player1, String player2) { wordList = new WordBank(); wordList.getWord(); this.player1 = new Player(player1); this.player2 = new Player(player2); } /********************************************************* * Explicit value constructor that builds a seeded dictioinary * * @param player1 The name of player1 * @param player2 The name of player2 * @param seed The seed to pass to WordBank constructor ********************************************************/ public WordGuess(String player1, String player2, long seed) { wordList = new WordBank(); wordList.getWord(); this.player1 = new Player(player1); this.player2 = new Player(player2); } /********************************************************* * play game plays the game until one player reaches 10 wins *********************************************************/ public void playGame() { boolean loopControl; boolean loopControlOne; boolean loopControlTwo; boolean playerTurn; boolean startOver; String playerInput; char playerCheck; String checkProgress; String checkGuess; String word; char[] dashes; char[] wordLetters; char[] lettersGuessed; kb = new Scanner(System.in); startOver = true; loopControl = true; playerTurn = true; System.out.printf("Welcome to Word Guess %s and %s\n\n", player1.getName(), player2.getName()); if (loopControl) { startOver = true; word = wordList.getWord(); dashes = new char[word.length()]; wordLetters = new char[word.length()]; lettersGuessed = new char[6]; for(int i = 0; i < word.length(); i++) { dashes[i] = ('-'); wordLetters[i] = word.charAt(i); } System.out.print('-'); if(startOver) { checkGuess = new String(lettersGuessed); checkProgress = new String(dashes); loopControlOne = true; loopControlTwo = true; if(playerTurn) { loopControlOne = false; } if (loopControlOne) checkGuess = new String(lettersGuessed); checkProgress = new String(dashes); playerTurn = true; { for(int i = 0; i < word.length(); i++) { System.out.print(dashes[i]); } System.out.print("\nUsed letters: "); for(int i = 0; i < 6; i++) { if(lettersGuessed[i] != 0) { System.out.print(lettersGuessed[i] + " "); } } System.out.printf("\n%s, guess a letter. ", player1.getName()); // Gets the players input and assigns it to variable playerInput playerInput = kb.nextLine(); playerCheck = playerInput.charAt(0); playerInput = new String("" + playerCheck); System.out.println(); for(int i = 0; i < word.length(); i++) { if(playerCheck == wordLetters[i]) { dashes[i] = playerCheck; } } if(checkGuess.contains(playerInput)) { System.out.printf("%s is already guessed. %s, you lose your turn.\n", playerInput, player1.getName()); loopControlOne = false; } else if(word.contains(playerInput)) { for(int i = 0; i < word.length(); i++) { if(wordLetters[i] == playerCheck) { dashes[i] = playerCheck; } } if(checkProgress.contains("-")) { System.out.printf("Correct: %s go again.\n", player1.getName()); for(int i = 0; i < 6; i++) { if(lettersGuessed[i] != 0) { lettersGuessed[i] = playerCheck; i = 6; } Arrays.sort(lettersGuessed); } } else { System.out.printf("Correct. %s you win a point!\n", player1.getName()); System.out.println(word); player1.iWon(); System.out.printf("%s: %d\t%s: %d\n\n", player1.getName(), player1.getScore(), player2.getName(), player2.getScore()); startOver = false; if(player2.getScore() == 5 || player1.getScore() == 5) { System.out.print("Game over. %s wins!\n"); loopControl = false; loopControlTwo = false; } // Set up new loop that clears everything. } } else { System.out.printf("Incorrect. %s, you lose your turn.\n", player1.getName()); loopControlOne = false; for(int i = 0; i < 6; i++) { if(lettersGuessed[i] == 0) { lettersGuessed[i] = playerCheck; i = 6; } Arrays.sort(lettersGuessed); } } } if (loopControlTwo) { checkGuess = new String(lettersGuessed); checkProgress = new String(dashes); playerTurn = true; for(int i = 0; i < word.length(); i++) { System.out.print(dashes[i]); } System.out.print("\nUsed letters: "); for(int i = 0; i < 6; i++) { System.out.print(lettersGuessed[i] + " "); } System.out.printf("%s, guess a letter. ", player2.getName()); // Gets the players input and assigns it to variable playerInput playerInput = kb.nextLine(); playerCheck = playerInput.charAt(0); playerInput = new String("" + playerCheck); for(int i = 0; i < word.length(); i++) { if(playerCheck == wordLetters[i]) { dashes[i] = playerCheck; } } if(checkGuess.contains(playerInput)) { System.out.printf("%s is already guessed. %s, you lose your turn.\n", playerInput, player1.getName()); loopControlTwo = false; } else if(word.contains(playerInput) && checkProgress.contains("-")) { { System.out.printf("Correct: %s go again.\n", player2.getName()); for(int i = 0; i <6; i++) { if(lettersGuessed[i] != 0) { lettersGuessed[i] = playerCheck; i = 6; } } Arrays.sort(lettersGuessed); } } else if(word.contains(playerInput)) { System.out.printf("Correct. %s you win a point!\n", player1.getName()); System.out.println(word); player1.iWon(); System.out.printf("%s: %d\t%s: %d\n\n", player2.getName(), player2.getScore(), player1.getName(), player1.getScore()); loopControlTwo = false; if(player2.getScore() == 0 || player1.getScore() == 0) { System.out.print("Game over. %s wins!\n"); loopControl = false; } } else { System.out.print("Incorrect. %s, you lose your turn.\n"); loopControlTwo = false; for(int i = 0; i < 6; i++) { if(lettersGuessed[i] == 0) { lettersGuessed[i] = playerCheck; i = 6; } Arrays.sort(lettersGuessed); } } } } } } } 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... Hey everyone! I'm new to coding and I've been working on a hangman game, but I got one problem I just can't figure out. I want to be able to insert feedback at the end of the game where I give the player the definition of the word they were guessing. Also I will gladly take any suggestions or commentary on my game. Heres my code so far: Code: <html> <head> <script> var canvas, ctx; var dc=0;//draw counter var it, dg, ds, swa;//input text, display guess div, display string sw = ["Netherlands","world","zombies","ashtray","mouse", "asperagus", "wooden", "energy", "arial", "horseshoe", "foundation", "majestic", "titties", "coffee", "postman", "perfect", "yellow", "onomatopoeia"];//secret word var sw = sw[Math.floor(Math.random()*sw.length)]; function init(){ canvas = document.getElementById("hungman"); ctx = canvas.getContext('2d'); ctx.lineWidth = 3; it = document.getElementById("input_txt"); dg = document.getElementById("display_guess_div"); displayGuess("-"); } function drawStuff(){ ctx.beginPath(); dc++; switch(dc){ case 1: gallows1(); break; case 2: gallows2(); break; case 3: gallows3(); break; case 4: gallows4(); break; case 5: drawHead(); break; case 6: drawBody(); break; case 7: drawLeftArm(); break; case 8: drawRightArm(); break; case 9: drawLeftLeg(); break; case 10: drawRightLeg(); break; } ctx.stroke(); } function drawHead(){ //draw head ctx.arc(150,175,50,0,Math.PI*2, true);//outer circle ctx.moveTo(115,175); ctx.arc(150,175,35,0, Math.PI, false);//mouth ctx.moveTo(135,155); ctx.arc(130,155,5,0,Math.PI*2,true);//left eye ctx.moveTo(175,155) ctx.arc(170,155,5,0,Math.PI*2,true);//right eye } function drawBody(){ //draw body ctx.moveTo(150,225); ctx.lineTo(150, 320); } function drawLeftArm(){ //draw left arm ctx.moveTo(150,250); ctx.lineTo(50,200); } function drawRightArm(){ //draw right arm ctx.moveTo(150,250); ctx.lineTo(250,200); } function drawLeftLeg(){ //draw left leg ctx.moveTo(150,300); ctx.lineTo(100,450); } function drawRightLeg(){ //draw right leg ctx.moveTo(150,300); ctx.lineTo(200,450); } function gallows1(){ //draw gallow1 ctx.moveTo(20,20); ctx.lineTo(20,500); } function gallows2(){ //draw gallow2 ctx.moveTo(20,20); ctx.lineTo(150,20); } function gallows3(){ //draw gallow3 ctx.moveTo(20,80); ctx.lineTo(80,20); } function gallows4(){ //draw gallow4 - rope ctx.moveTo(150,20); ctx.lineTo(150,125); } function checkLetter(){ var len = it.value.length-1; var guess = it.value.charAt(len); if(sw.indexOf(guess)==-1){ drawStuff(); if (dc>=10){ alert("bad luck, you're hung! The word was " + sw + "."); playAgain(); } }else{ displayGuess(guess) if(ds.indexOf("-")==-1){ alert("You win! The word was " + sw + "!"); playAgain(); } } } function displayGuess(guess){ //first time if(guess == "-"){ ds = ""; for(i=0; i<sw.length; i++){ ds+="-"; } }else{ //display a correct letter var newds =""; for(i=0; i<sw.length; i++){ if(sw.charAt(i)==guess){ newds +=guess; }else{ newds +=ds.charAt(i); } } ds = newds; } dg.innerHTML= ds; } function playAgain() //Copyright Joey { var r=confirm("Play Again?"); if (r==true) { window.location.reload(); } else { alert("Thanks For Playing!"); window.close(); } } function changeWord() { var r=confirm("Change word?"); if (r==true) { window.location.reload(); } } function clear() { document.text_form.input_text.value=""; return true; } //function numberCheck() //{ // if ( isNaN ( it ) || it != ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ) // { // alert("Please Insert a Letter") ; // return; // } //} </script> <style type="text/css"> canvas{border:1px solid black} </style> </head> <body onLoad="init()"> <center> <h1>Hangman</h1> <p>Guess The Word or !</p> <canvas id="hungman" width="300px" height="600px"> </canvas><br/> <div id="input"> <div id="display_guess_div">display guessed letters here</div><br/> <input type="text" id="input_txt" maxlength="1" size="19"> </input> <br> <input type="button" value="Guess" onClick="checkLetter()" onSubmit="clear()"></input> <input type="button" value="Change Word" onClick="changeWord()"></input> </div> </center> </body> </html> I'm trying to create a simple hangman script, i want to enter a letter in the guess box and have it detect whether its in the secret word or not and print out the result to the another text input eg: guess: b secret word: b_b___ guess: o secret word: bob_o____ etc... Here's what I have: Code: <html> <head> <title>Hangman</title> <script type="text/javascript"> var secretWord="Bob-o-Ran"; var guessLetters = new Array(); function processGuess(form) { guess = form.guessBox.value; console.log("You typed: " + guess); guessLetters.push(guess); var output = ""; for(var i=0;i<secretWord.length;i++) { var letter = secretWord.charAt[i]; for(var j=0;j<guess.length;j++) { if(guess==letter) { output += letter; } else { output += "_"; } } } var inputObj = document.getElementById('secretWordBox'); inputObj.value = output; } </script> </head> <body> <form name="myform" id="myform" action="" method="GET"> Enter something in the box: <br /> Enter Guess: <input type="text" id="guessBox" VALUE=""><br /> Secret Word:<input type="text" id="secretWordBox" VALUE=""><br /> <input type="button" NAME="button1" Value="Guess" onClick="processGuess(this.form)" /> </form> </body> </html> the problem im having is its not detecting the letter ive just started studying computing and am struggling with javascript a little. one of our assignment is to create a hangman game and i have given it a good go, just wondering if someone could help me out with a problem im facing. ive got the code to read a file and randomise a word, however im struggling with the section after a guess. my code is able to tell if the guess is correct or not, however im not sure how to print a _ if the guess is false or the letter if the guess is true. below is my code so far (excuse the poor layout) (io.js/io.output/io.input is a file that the university use instead of println) Code: var fs = require("fs"); var io = require("./io.js"); var words = ""; var theWord = ""; var guessedLetter = ""; /* Hangman Games */ io.output("Hello, welcome to my hangman game! \nwould you like to begin?"); var start = io.input(""); if (start == "no") { io.output("goodbye\n------------------"); } else { io.output("lets begin\n-----------------------------------------\n"); function letterLookup (guessedLetter){ for( var a = 0; a < letters.length -1 ; a++ ){ //if guessed then display letter if (guessedLetter == letters) { dashes = dashes + Letters; } //io.output(letters[a]); //else display dash dashes = dashes + "-"; } } function guess () { io.output("please guess a letter..."); guessedLetter = io.input("\n"); } //pick a word from file at random. //read the file words = fs.readFileSync("\words.txt" , 'utf-8').split("\n"); //randomise number var numberOfWords = words.length; var rand = Math.floor(Math.random() * numberOfWords); //get word from random number theWord = words[rand]; io.output(theWord); var letters = theWord.split(""); var dashes = "" //use letterLookup Function letterLookup(); io.output(dashes); //guess guess(); letterLookup(guessedLetter); io.output(dashes); guessInWord = (theWord.indexOf(guessedLetter)) != -1; io.output(guessInWord); } } Reply With Quote 01-09-2015, 03:05 PM #2 sunfighter View Profile View Forum Posts Senior Coder Join Date Jan 2011 Location Missouri Posts 4,830 Thanks 25 Thanked 672 Times in 671 Posts I am pretty sure println() is not part of javascript. I looked it up in java just to be sure and can't find it there. JS uses document.write().... Anyway you might want to study this: Source Code - JsMadeEasy.com Hi, I have been working on a hangman game and I have run into a glitch. I have it coded so that when the user guesses a letter correct, the letter is filled into the corresponding text spot. Like this: Code: if (randomword.indexOf(guess1) == 0) { document.form1.letter1.value = guess1 letter1 = guess1 } if (randomword.indexOf(guess1) == 1) { document.form1.letter2.value = guess1 letter2 = guess1 } if (randomword.indexOf(guess1) ==2) { document.form1.letter3.value = guess1 letter3 = guess1 } if (randomword.indexOf(guess1) == 3) { document.form1.letter4.value = guess1 letter4 = guess1 } if (randomword.indexOf(guess1) == 4) { document.form1.letter5.value = guess1 letter5 = guess1 } if (randomword.indexOf(guess1) == 5) { document.form1.letter6.value = guess1 letter6 = guess1 } if (randomword.indexOf(guess1) == 6) { document.form1.letter7.value = guess1 letter7 = guess1 } if (randomword.indexOf(guess1) == 7) { document.form1.letter8.value = guess1 letter8 = guess1 } if (randomword.indexOf(guess1) == 8) { document.form1.letter9.value == guess1 letter9 = guess1 } if (randomword.indexOf(guess1) == 9) { document.form1.letter10.value = guess1 letter10 = guess1 } if (randomword.indexOf(guess1) == 10) { document.form1.letter11.value = guess1 letter11 = guess1 } The variable randomword is the randomly selected word from an array. The guess1 is the users guess. The letter variables are just to check to see if all the spots are filled to win the game. It works fine if the the word doesnt have repeating letters in it such as "Lucky". However words such as "Happy" do not work. If you guess 'p' code fills in the 3 text box with a 'P' but it leaves the 4 spot empty. Even if you guess 'p' again, it still leaves the 4 box empty. Thanks for the help! If you need to see the full code i can post it. Thanks again! Okay I'm having a problem getting this code to work. I've tried different things. The application is supposed to calculate the sum of two numbers the user enters and the numbers inbetween those numbers. For example 10 and 15 would make 75 (10+11+12+13+14+15) There's nothing in the parameters of the for loop as I have tried different things but I don't think I've come up with a possible solution. Code: <html> <head> <script type="text/javascript"> function calculation() { var a = document.getElementById("oneNum").value; var b = document.getElementById("twoNum").value; for (a=a;a=b;a++) { } document.getElementById("sum").innerHTML = "The Sum is " + totalsum.toFixed(2); } </script> </head> <body> <h2>Sum Application</h2> <p>This calculator calculates the sum of the numbers between two numbers inclusive that are entered by the user. <br /> For example, if the user enters 10 and 15 the application would calculate 75 (10+11+12+13+14+15).<p> Enter first number: <input type="text" id="oneNum"> Enter second number: <input type="text" id="twoNum"> <br /> <input type="button" value="Calculate" onClick="calculation()"> </body> <p id="sum"></p> </html> I am stuck on these problems and cannot figure them out! Any help would be appreciated. Thank you! Code: public int sumkj(int k, int j){ // Complete the method using a for loop that will add the numbers from k to j, // where j is greater than k int total = 0; // TODO: ADD LOOP CODE HERE return total; } // whilesum10 public int whilesum10(){ // Complete the method using a while loop that will add the numbers // from 1 to 10 int total = 0; int i = 1; // TODO: ADD LOOP CODE HERE return total; } // whilesumkj public int whilesumkj(int k, int j){ // Complete the method using a while loop that will add the numbers // from k to j, where j is greater than k int total = 0; int i = k; // TODO: ADD LOOP CODE HERE return total; } public int dosum10(){ // Complete the method using a do-while loop (i.e. condition at end of loop) // that will add the numbers from 1 to 10 int total = 0; int i = 1; // TODO: ADD LOOP CODE HERE return total; } public int dosumkj(int k, int j){ // Complete the method using a do-while loop (i.e. condition at end of loop) // that will add the numbers from k to j, where j is greater than k int total = 0; int i = k; // TODO: ADD LOOP CODE HERE return total; } public String arrayprint(){ String msg = ""; String abc[] = new String[6]; abc[0] = "a"; abc[1] = "b"; abc[2] = "c"; abc[3] = "d"; abc[4] = "e"; abc[5] = "f"; // Create a loop that will output the values stored in the array abc // using a for loop and the array length // TODO: ADD LOOP CODE HERE return msg; } public String baseballOuts(){ String msg = ""; int totalOuts = 0; // Write a set of nested for-loops that willdetermine the number of // outs in a regulation baseball game. Assume: 9 innings per game, // 2 halves per inning, 3 outs per half inning. // You solution should include a loop (outer or nested) for each // of the assumptions. // TODO: ADD LOOP CODE HERE msg = "Total number of outs in a regulation baseball game is " + totalOuts + "."; return msg; } public String factorial (int n){ String msg = ""; int factnum = 1; // Use a loop to calculate the factorial of an input integer. // Note: If the input integer is too high an error may occur even if your // logic is correct. Why? At what value of input does the error occur? // How can you adjust the method so that either the error does not occur // or the method "fails gracefully?" Write your answers in the form of // a comment here. // TODO: ADD LOOP CODE HERE msg = n + "! = " + factnum; return msg; } } 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! Ok, I'm nearly pulling my hair out with this one. I have been looking at this code for two evenings now, and rewrote it 4 times already. It started out as jQuery code and now it's just concatenating strings together. What I'm trying to do: Build a menu/outline using unordered lists from a multidimensional array. What is happening: Inside the buildMenuHTML function, if I call buildMenuHTML, the for loop only happens once (i.e. only for 'i' having a value of '0'.) If I comment out the call to itself, it goes through the for loop all 3 times, but obviously the submenus are not created. Here is the test object: Code: test = [ { "name" : "Menu 1", "url" : "menu1.html", "submenu" : [ { "name" : "menu 1 subitem 1", "url" : "menu1subitem1.html" }, { "name" : "menu 1 subitem 2", "url" : "menu1subitem2.html" } ] }, { "name" : "Menu 2", "url" : "menu2.html", "submenu" : [ { "name" : "menu 2subitem 1", "url" : "menu2subitem1.html" }, { "name" : "menu 2subitem 1", "url" : "menu2subitem1.html" } ] }, { "name" : "Menu 3", "url" : "menu3.html", "submenu" : [ { "name" : "menu 3 subitem 1", "url" : "menu3subitem1.html" }, { "name" : "menu 3 subitem 1", "url" : "menu3subitem1.html" } ] } ]; Here is the recursive function: Code: function buildMenuHTML(menuData,level) { var ul; if (level == 1) { ul = "<ul id='menu'>"; } else { ul = "<ul class='level" + level + "'>"; } for (i = 0; i < menuData.length; i++) { menuItemData = menuData[i]; ul += "<li>"; ul += "<a href='" + menuItemData.url + "'>" + menuItemData.name + "</a>"; if (typeof menuItemData.submenu != 'undefined') { ul += buildMenuHTML(menuItemData.submenu,level + 1); } ul += "</li>"; } ul += "</ul>"; return ul; } Here is how the function is called initially: Code: buildMenuHTML(test,1); This is it's return value (with indentation added for readability): Code: <ul id='menu'> <li><a href='menu1.html'>Menu 1</a> <ul class='level2'> <li><a href='menu1subitem1.html'>menu 1 subitem 1</a></li> <li><a href='menu1subitem2.html'>menu 1 subitem 2</a></li> </ul> </li> </ul> 'Menu 2' and 'Menu 3' don't show up! I'm sure it's something small that I'm overlooking, but any help would be appreciated. Hi all I'm well aware that I can't post assignments here and expect an answer, however, I have been staring at this code for so long. I feel I am close to the solution (to get the correct output to the browser) but I just cannot get it to count how many moves it takes. I don't want an answer, but a nudge in the right direction would be very grateful. As you can see from the code and the output, it will attempt to write to the browser how many moves, but only '0'. Code: function rollDie() { return Math.floor(Math.random() * 6) + 1; } /* *searches for a number in a number array. * *function takes two arguments * the number to search for * the number array to search *function returns the array index at which the number was found, or -1 if not found. */ function findIndexOf(number, numberArray) { var indexWhereFound = -1; for (var position = 0; position < numberArray.length; position = position + 1) { if (numberArray[position] == number) { indexWhereFound = position; } } return indexWhereFound; } //ARRAYS that represent the board -- you do not need to change these //array of special squares var specialSquaresArray = [1,7,25,32,39,46,65,68,71,77]; //array of corresponding squares the player ascends or descends to var connectedSquaresArray = [20,9,29,13,51,41,79,73,35,58]; //VARIABLES used -- you do not need to change these //the square the player is currently on var playersPosition; //play is initially at START playersPosition = 0; //what they score when they roll the die var playersScore; //the index of the player's position in the special squares array or -1 var indexOfNumber; //MAIN PROGRAM //TODO add code here for parts (iii), (iv)(b), (v), and (vi) // start of question(iii) playersScore = rollDie(); document.write(' Sco ' + playersScore); playersPosition = playersScore + playersPosition; document.write(', Squa ' + playersPosition); indexOfNumber = findIndexOf(playersPosition, specialSquaresArray); if (indexOfNumber != -1) { document.write(', Ladder to Squa ' + connectedSquaresArray[indexOfNumber]); playersPosition = connectedSquaresArray[indexOfNumber]; indexOfNumber = -1; } document.write('<BR>') // end of question(iii) // start of question(iv)(b) while(playersPosition<=80) { playersScore = rollDie() document.write(' Sco ' + playersScore) playersPosition = playersPosition + playersScore document.write(', Squa ' + playersPosition) indexOfNumber = findIndexOf(playersPosition, specialSquaresArray) if(indexOfNumber != -1) { document.write(', Ladder to Squa ' + connectedSquaresArray[indexOfNumber]); playersPosition = connectedSquaresArray[indexOfNumber]; } document.write('<BR>'); } var countMoves = 0; while(countMoves <= 0) { document.write('You took ' + countMoves + ' moves to get out'); countMoves = countMoves + 1 } /*for (var countMoves = 0; countMoves < playersPosition; countMoves = countMoves + 1) { countMoves = countMoves + playersPosition; document.write('You took ' + countMoves + ' moves to get out'); }*/ // end of question(iv)(b) // start of question (v) /*if (playersPosition >=80) { document.write('The player is out'); }*/ // end of question (v) </SCRIPT> </HEAD> <BODY> </BODY> </HTML> Many thanks. 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
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, 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);} } 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! 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. 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? |