JavaScript - Gallow Game Guessing Word
Im making a simple "gallow" guessing game. I got a virtual keyboard styled with boxes and onclick event, and a randomized guessing word when i click on button new game.
Here is the virtual keyboard: Code: <div align="center" style="width: 700px; float: left;" id="keys"> <span onclick="selection(this)">Q</span> <span onclick="selection(this)">W</span> <span onclick="selection(this)">E</span> <span onclick="selection(this)">R</span> <span onclick="selection(this)">T</span> <span onclick="selection(this)">Z</span> <span onclick="selection(this)">U</span> ... all keys + a .css for looking like a keyboard - see picture at bottom</div> The function that randomizes a word from the array of words + css styled boxes around the word chars. the array of words: Code: var strings= [ "indexof", "round", "fixed", "touppercase", "alert", "prompt"]; Code: function newgame() { document.getElementById('display').innerHTML = ""; var wordArr = strings[Math.floor(Math.random() * strings.length)].split(""); for (var i=0; i<wordArr.length; i++) { document.getElementById('display').innerHTML += '<span>'+wordArr[i]+'</span>'; } } css for this words Code: #display span { border-top:1px solid #000; border-right:1px solid #000; border-bottom:1px solid #000; width:10px; background-color:gray; text-align:justify; padding:5px 10px; } #display span:first-child { border:1px solid #000; } I also have function to colorize the pressed key on virtual keyboard-that colors it red-so the user knows it pressed it already Code: function selection(key) { key.style.background = "red"; } So now i have the question how do i make the guessing word - the boxes around chars without the chars - that the boxes are empty, but somehow the word stays in back of it or something like that -temporary save?.. I mean now i got [f] [i] [x] [e] [d], i wanna when i press new game to be like [] [] [] [] [].. and then i need to guess the word.. i press e on keyboard.. then it comes like this [] [] [] [e] []... Somehow i need to check if the pressed key on the keyboard is inside the word, and then show it in the box (but how).. then i press f -> [f] [] [] [e] [] .... and so on till i guess all of the word.. Here is an screenshot if u dont know what i mean.. http://img13.imageshack.us/i/printscreenshot1.jpg/ Thank you for helping! Similar TutorialsGood day. I'm working on a word guessing game. Simple premise, enter a letter, if it's in the mystery word it fills the asterick if not you keep guessing until it is guessed. However, I can't get it to fill in the astericks or to acknowledge when you've guessed it...soem help would be appreciated...thanks in advance. ao5431 <!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"> <head> <title>Guessing Game</title> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <script type="text/javascript"> /* <![CDATA[ */ var mysteryWord = "suspicious"; function checkGuess() { if (document.forms[0].letter.value != "") { var progress = document.forms[0].mysteryWord.value; var guess = document.forms[0].letter.value; document.forms[0].letter.value = guess; mysteryWordArray = mysteryWord.split(" "); var progressArray = progress.split(""); for (var i=0; i<mysteryWord.length; ++i) { var curLetter = mysteryWordArray[i]; if (curLetter == guess) progressArray[i] = guess; } progress = progressArray.join(""); if (progress == mysteryWord) document.forms[0].mysteryWord.value = "You guessed correctly! The mystery word is '" + progress + "'."; else document.forms[0].mysteryWord.value = progress; } else window.alert("You must enter a letter!"); } /* ]]> */ </script> </head> <body> <h1>Guessing Game</h1><hr /> <form action="" method="get" enctype="application/x-www-form-urlencoded"> <p>Mystery word: <input type="text" name="mysteryWord" value="**********" size="100" readonly="readonly" style="border: 0" /></p> <p>Enter a letter and click the Submit Letter button.</p> <p><input type="text" name="letter" size="2" /> <input type="button" value="Submit Letter" onclick="checkGuess()" /></p> </form><hr /> </body> </html> 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> What I'm trying to achieve is it initialises a number between 1-2000 randomly. When the submit button is clicked it simply returns if the number that is in putted is higher or lower than the randomly initialised number. External JavaScript: Html Code: <html> <head> <script type="text/javascript" src="jsscri.js"></script> </head> <body onload="initialisation ()"> <form name="exampleform"> <h3> Number: <input name="number" type="text" onchange='checkNumber( this.value );'> </h3> <p> <input name="submit" type="button" value="Guess" onclick= 'checkValue()';/> </p> </body> </html> If you load this onto a webpage you'll see what i'm trying to do. I tried deleting the rest of the code to keep the size of the code down. Absolutely nothing happens when I click on the button, and I know NOTHING about Java. Need serious help! The user is supposed to arbitrarily type a number (1-5) and see if it's the same one that JavaScript generates. The function "secretNum" is supposed to be a global variable, but I don't have a clue as to what that means. Anyways, an alert should pop up saying either congrats or try again. Code: <html> <head> <title>Guessing Game</title> <script type="text/javascript"> function setUp () { secretNum = 1+Math.floor(5*Math.random()); alert = (secretNum); } function checkGuess () { userGuess = document.IfForm.guessBox.value; userGuess = parseFloat(userGuess); // get value from text box if (secretNum == userGuess) {alert ("Correct!");} else {alert ("Sorry, Try Again");} } </script> </head> <body style="text-align:center" onLoad="setUp();"> <h2>Guess the Number From 1 to 5</h2> <form name="IfForm"> Enter Your Guess: <input type="text" size="5" name="guessBox" value="" /> <br /> <input type="button" value="Check Guess" onClick="checkGuess" /> </form> </body> </html> Hi everyone. Right now I'm doing a guessing game assignment for my class. I'm new to the forums so sorry if copy/pasting code into the thread here isn't the right thing to do. I have ran firebug a few times on this code and for some reason the variable "Football" is the only answer that is declared true. How can I fix this code so that all of the variables in the array display the true statement when typed in the box? Note: I have the questions looped to ask 3 times. Thanks! <html> <head> <h1>Welcome to the guessing game!</h1> <h2>Second Submission Attempt</h2> </head> <body> <script type = "text/javascript"> var sportsAry = new Array(6); sportsAry[0] = "Football"; sportsAry[1] = "Basketball"; sportsAry[2] = "Rollerblading"; sportsAry[3] = "Hiking"; sportsAry[4] = "Biking"; sportsAry[5] = "Swimming"; var firstName; var points = 0; var finalscore; var ask; do { firstName = prompt("Please enter your first name.",""); } while (firstName == "" || firstName == null || firstName == parseInt(firstName)); alert("Welcome to the Game, " + firstName + " !"); for (var count = 0; count < 3; count++){ ask = prompt("Please guess a sport : ",""); if (ask == null){ alert("You are chicken!!!"); } else if (ask == ""){ alert("You forgot to enter a game!"); count--; }else { for ( var i = 0; i < sportsAry.length; i++){ if (ask.toUpperCase() == sportsAry[i].toUpperCase()) { points +=5; alert("You have guessed correctly! You have gained 5 points"); break; }else if (ask.toUpperCase() !== sportsAry[i].toUpperCase()) { points -=5; alert("You have guessed incorrectly, you gain no points."); break; } } } } if (points == 15){ document.write(firstName + ", you are a mind reader!" + "<br>"); } else if (points < 15){ document.write(firstName + ", you are pretty good!"); }else { document.write(firstName + ", you do not display ESP tendencies at this time."); } </script> </body> </html> Hello! So, here is my problem. I have to write a number-guessing game that prompts the visitor to guess the right number in a maximum of 4 attempts. If the visitor guesses the target number within 4 tries, I want to write an alert that congratulates them as well as indicates the number of tries taken. If they guess incorrectly, I want to prompt with "Try again." And I finally want to keep track of each number they typed with a document.write. I have something like this, but its just not working out: Code: <script type="text/javascript"> var count = "" ; if (count >=0 && count <=88) { for (i=1; i<=4; i++) { count = prompt("I'm thinking of a number between 0-88. Can you guess it?", ""); document.write("Guess #" + i + ":" + count + "<br />"); }} else if (count>88){ alert("Too high!") } else if (count=55){ alert("Congratulations, you guessed it in " + i + " tries!) } else{ alert ("Guess again!") } </script> Thank you for your time. 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); } } } } } } } Sorry about the title, I didn't know what else to use to describe my problem. Basically, I'm generating a random word with a function; then I'm trying to pass this word down to another function. The problem is, when I pass the word, it changes each time (due to it being randomly generated originally). I'm only calling the function once (via button click), but I'm also calling the function in my code lower down to retrieve the returned variable; and the function seems to be running again and returning a new word from my array. Here's a snippet of my code: Code: function ranNum(){ var ranNum = Math.round(Math.random()*10); var chosenWord = wordArray[ranNum]; return chosenWord; } function makeBoxes(x){ //remove children when new word is chosen var hM = document.getElementById("hangMan"); while(hM.firstChild){ hM.removeChild(hM.firstChild); } var chosenWord = ranNum(x); var wL = chosenWord.length; //create box for length of letters in word var i = 0; for(i=0;i<wL;i++){ var cBoxes = document.createElement("div"); cBoxes.className = "letterBoxes"; cBoxes.innerHTML = chosenWord.charAt(i); hangMan.appendChild(cBoxes); } return chosenWord; } function checkLetter(y){ var chosenWord = makeBoxes(y); alert(chosenWord); } So I generate a word with one button; now I need to be able to work with said word in my checkLetter() function. The word changes however. Any help would be greatly received. I found a nice script online that will count words. Problem is, I need it to also count each DIGIT (0-9) as a seperate word, whether the numbers are seperated by a space or not. I've searched this forum to no avail. Can anyone help me or show me how to do this, here is the original script: Code: <!-- TWO STEPS TO INSTALL WORD COUNT: 1. Copy the coding into the HEAD of your HTML document 2. Add the last code into the BODY of your HTML document --> <!-- STEP ONE: Paste this code into the HEAD of your HTML document --> <HEAD> <SCRIPT LANGUAGE="JavaScript"> <!-- Original: Shawn Seley --> <!-- This script and many more are available free online at --> <!-- The JavaScript Source!! http://javascript.internet.com --> <!-- Begin function CountWords (this_field, show_word_count, show_char_count) { if (show_word_count == null) { show_word_count = true; } if (show_char_count == null) { show_char_count = false; } var char_count = this_field.value.length; var fullStr = this_field.value + " "; var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi; var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, ""); var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi; var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " "); var splitString = cleanedStr.split(" "); var word_count = splitString.length -1; if (fullStr.length <2) { word_count = 0; } if (word_count == 1) { wordOrWords = " word"; } else { wordOrWords = " words"; } if (char_count == 1) { charOrChars = " character"; } else { charOrChars = " characters"; } if (show_word_count & show_char_count) { alert ("Word Count:\n" + " " + word_count + wordOrWords + "\n" + " " + char_count + charOrChars); } else { if (show_word_count) { alert ("Word Count: " + word_count + wordOrWords); } else { if (show_char_count) { alert ("Character Count: " + char_count + charOrChars); } } } return word_count; } // End --> </script> </HEAD> <!-- STEP TWO: Copy this code into the BODY of your HTML document --> <BODY> <form> <textarea cols=40 rows=5 name=x> </textarea> <br> <input type=button value="Count Words" OnClick ="CountWords(this.form.x, true, true);"> </form> <p><center> <font face="arial, helvetica" size"-2">Free JavaScripts provided<br> by <a href="http://javascriptsource.com">The JavaScript Source</a></font> </center><p> <!-- Script Size: 2.04 KB --> This is a simple basic game i want to make. Its a "What Am I" Riddle... The questions is (In HTML which i already know): I'm as light as a feather but no man can hold me for long. What am I? the answer is: Your Breath. (This is where the JAVASCRIPT comes in) Lets say they guess a rock, have a pop up say: Wrong Answer. Please try again. Lets say they guess Your breath -OR- Breath, have a pop up say: Correct! I want a text field where you can enter your answer, and if they choose ANYTHING but the 2 correct answers above, it will display please try again. Can anyone code this please? Thanks for reading. Ok so i want to work on an EASY basic game. As simple as Guess what number... But there are some twist... Ok So here is my example... (HTML, i know this.)I'm Guessing a number 1-99. What is it? (java) Lets say its 66 and they guess 53, have the text rusult be in a pop up window be: Too low! (java) Lets say they guess 78, have the text rusult be in a pop up window be: Too high! (java) Lets say they guess 100+, have the text rusult be in a pop up window be: Out of range! (java)But lets say they guess 66, have a text result be in a pop up window be: You've won! (java) I want a text field where you can enter your answer, and it will do the actions above. Can anyone code this? Thanks for reading! I have a game page on my site and I am trying to protect direct access to it by .htaccess .htpasswd but is not accepting user name and password? .htaccess: AuthUserFile /home/vhosts/kandcoentertainment.freetzi.com/.htpasswd AuthType Basic AuthName "game1" <Files "cookietest.html"> Require valid-user </Files> .htpasswd test:8888 Any suggestions on why it is not working? What I would like to do is have apay and play once setup but as I am a novice and dont have a clue HELP PLEASE!!! What I have been told is - protect the files, add a client side cookie to game page then upon url payment return validate cookie giving single access and when played the user cannot replay by refresh or just typing in url because cookie expired ? I have tried to write the scripts up with no success. 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! How hard would it be to make a 2d game similar to super smash bros? Basically I want to have a scrolling position (instead of a static image, where the background is always the same) where when the user moves his character object, the area of vision moves with him. Also, will it work with using keyboard keys? I have to integrate it into a database and I know quite a bit of javascript so I am hoping it is possible. Thanks! Max Hi 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 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. I am creating a guessing word game and when the user types in a guess a pop-up tells the user how many letters the user got right to the actual answer. My problem is I can't seem to display the number of letters the user guessed right. This is what the function looks like: Code: function guessing() { words = "album"; guess = document.getElementById("txt1").value; answer = document.getElementById("result").value = parseInt(); alert("You have " + answer + " matches"); used = false; for(i = 0; i<=guess.length; i++) { for(j = 0; j<=answer.length; j++) if(!used[j] && guess[i] == words) { alert("Congradulations! You got it!"); used[j] = true; count++; break; } else { count = 5; while(count > 5) { alert("Sorry, that's game over!"); count++; } } } } 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> sorry this post is duplicated, the original post:http://www.codingforums.com/showthread.php?t=261488
|