JavaScript - Hangman Letter Glitch <solved>
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! Similar TutorialsHey, I'm writing a piece of code, using a given code as an example, but few things are confusing to me, if you could just explain me step by step what it does, I would really appreciated. Code: function getGeneticCodeString (type) { if ((type.toLowerCase() == "standard") || (type.toLowerCase() == "transl_table=1")) { return "/gc[acgturyswkmbdhvn]/=A," + // Here I know that the three letter combination HAS to begin with 'gc' // can be followed by a,c,t,g or u. // What do the other letter represent? "/[tu]g[ctuy]/=C," + // Begins with either 't' or 'u', middle symbol is 'g' // third symbol can be c, t, or u ('u' can be used only if it begins with 'u'. // what is the 'y' for in the second square brackets for?? "/ga[agr]/=E " ; // Must start with 'ga' followed by 'a' or 'g'. // What is 'r' for? } } Hope, I didn't confuse anybody. Thank you. 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 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! Hi there, I have an issue with my slideshow in IE7. There is a transparent grey box that slides upwards with text on the bottom of the slideshow. In IE7 the grey box does not go right across to the right hand side it leaves a small gap. It does this in IE7 compatability mode in IE9 and i've tried the proper version of IE7 too. My site is located at http://www.passmarkdrivinglessons.co.uk The slideshow I used in my site is from here http://www.queness.com/resources/htm...slideshow.html Can any help me to solve this issue, thanks Hey yall Im finishing up my uncles site... fritzhoffmann.com when you click on the pictures button in the nav the slider glitches. I didn't write the slider script so I know if this is something in the jQuery or what. any ideas would be awesome! ty Hello guys my question has changed, i dont want to double post so here is my new question, I now have 3 arrays name price quantity totalPrices now i want to create a table that will hold them but it will be created when you click the shop cart button, this button will take you to a blank page with the table on it i would like something like this Toy name| Quantity | Price | Total price Toy1 | Quantity | Price | Total price of that toy Toy2 | Quantity | Price | Total price of that toy Toy3 | Quantity | Price | Total price of that toy ----- | -------- | ----- | Total price all together I have looked at many tutorials but i cant get any to work, all they do is draw nothing and i cant get it to work I think I have the regex side of this script worked out. But I need help getting everything into an array for regex to read. Is there a way to use tokenizer to read everything before a carriage return? Each line should be added to an array for the regex to analyze and parse as needed. It's been ages since I touched tokenizer, so I forgot most of it. This is the text area in the html that the script should reference. Code: <textarea cols="60" rows="14" value="" id="paste" name="paste"></textarea> Thanks so much for any help you can give. Solved. thanks so much Phil!!!! Here is yet another project of mine...ive got most done but the timers are working in milliseconds and the hours, minutes, and seconds arent working right. heres the code. THE .JS FILE Code: /* Function List: showDateTime(time) Returns the date in a text string formatted as: mm/dd/yyyy at hh:mm:ss am changeYear(today, holiday) Changes the year value of the holiday object to point to the next year if it has already occurred in the present year countdown(stop, start) Displays the time between the stop and start date objects in the text format: dd days, hh hrs, mm mins, ss secs */ function showDateTime(time) { date = time.getDate(); month = time.getMonth()+1; year = time.getFullYear(); second = time.getSeconds(); minute = time.getMinutes(); hour = time.getHours(); ampm = (hour < 12) ? " am" : " pm"; hour = (hour > 12) ? hour - 12 : hour; hour = (hour == 0) ? 12 : hour; minute = minute < 10 ? "0"+minute : minute; second = second < 10 ? "0"+second : second; return month+"/"+date +"/"+year+" at "+hour+":"+minute+":"+second+ampm; } function changeYear(today, holiday){ year = today.getFullYear(); holiday.setFullYear(year); (holiday < today) ? year++ : year; holiday.setFullYear(year); } function countdown(start, stop) { time = stop - start; days = Math.floor(time/1000*60*60*24); hours = (days - Math.floor(days))*24; minutes = (hours - Math.floor(hours))*60; seconds = (minutes - Math.floor(minutes))*60; return days + " days," + hours + "hours," + minutes + " mins," + seconds + "secs"; } THE HTML FILE.. Code: <script type="text/javascript" src="dates1.js"></script> <script type="text/javascript"> function showCountdown() { var today = new Date(); var Date1 = new Date("January 14, 2007 10:00:00"); var Date2 = new Date("May 21, 2007 12:00:00"); var Date3 = new Date("July 4, 2007 21:00:00"); var Date4 = new Date("September 1, 2007 12:00:00"); var Date5 = new Date("December 1, 2007 11:30:00"); var Date6 = new Date("December 31, 2007 15:30:00"); document.eventform.thisDay.value = showDateTime(today); changeYear(today, Date1); changeYear(today, Date2); changeYear(today, Date3); changeYear(today, Date4); changeYear(today, Date5); changeYear(today, Date6); document.eventform.count1.value = countdown(today, Date1); document.eventform.count2.value = countdown(today, Date2); document.eventform.count3.value = countdown(today, Date3); document.eventform.count4.value = countdown(today, Date4); document.eventform.count5.value = countdown(today, Date5); document.eventform.count6.value = countdown(today, Date6); } </script> </head> <body onload="setInterval('showCountdown()' ,100)"> yes ive done all the coding just cant figure out why the timers wont work correctly. Hi, below is my code and i cant seem to figure out how i can loop the string and find the location of letter "a" in the string and display it like "1 3 17" ... i cant seem to figure out what i am doing wrong in the loop and keep getting "1 1" ... Thanks before hand! <html> <body> <script type="text/javascript"> var char = "a"; var str="JavaScript is great!" var pos= 0 for(i=0; i<=str.length; i++) { if(pos == i) { var pos = str.indexOf("a") document.write(pos++ + " ") } } </script> </body> </html> Hi, I have a 'Register' page on my site. When someone registers to my website, I would like to make it necessary to have a div box which generates a random number/letter, which is linked to a text field where the user has to match the generated output. I've been sitting here wondering which would be the best route to take regarding completing this. I was thinking about using charAt() method. Could anybody please possibly give me some tips for generating random letter/numbers? Possibly would I create a string containing "ABCDE....Z0123456789", then use the charAt method to find a character at a certain index position? If so, would I need create something which generates a random index position? Any help would be fantastic, thank-you. I need to change one letter in a text string, but near as I can figure out, I can't just do this: Code: TextString[8] = "X"; Is that possible, or do I have to break the string and rebuild it into a second string? I need to make something that will automatically insert values into a letter based on user input, just like this one right here. please tell me how it works....
Hi, I want to display my listings like they do he http://www.ticketnetwork.com/performers/concerts/a.aspx The code on my end calling the third party service looks like this: <script language="javascript" type="text/javascript"> document.write('<script language="javascript" src="http://###########.com/?bid='+####+'&sitenumber='+#+'&tid=event_names&pcatid=2&showcats=true&title=Concerts Tickets"></' + 'script>'); </script> How do I make it only display one letter at a time? I believe some variation on the sort method might work... I am working on a work project that requires a 5*5 table, that will generate random letters in each cell upon button click. I have most of the coding complete with the exception of the letter generation. I am currently generating numbers, I would even be fine with having a RandBetween(and listing the 26 letters of the alphabet) at this point. Any suggestions? Code: <script type="text/javascript"> var random1, random2, random3, random4, random5, random6, random7, random8, random9, random10, random11, random12, random13, random14, random15, random16, random17, random18, random19, random20, random21, random22, random23, random24, random25; var randomArray = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; //generate the random characters function CreateCellData() { for (var i=0; i<randomArray.length; i++) { randomArray[i] = Math.floor(Math.random()*99 + 1); } } Hi, i know i should have 2 fields for a first and last name in my form but i dont - and was wondering if someone would be able to help me with - or has - a java script valadation rule to only allow a one letter character (letter in between spaces such as a middle initial) in a text field if at least 2 words are also included (2 words of at least 2 or more characters) so if the user input ' John H ' an error prompt would display until one more word is added/at least 2 words are found right now im using the below coding to allow at least 2 words in the text field but would like to see if its possible to enhance it so it will only block a one letter word if there are less than 2 other words in the form - right now if any words is added with less than 2 characters it will display an error... if anyone knows of a better form of code that needs a minimum of 2 words added and still allows single characters such as middle initials to in a validation script i'd greatly appreciate your help... i get lost on validation process' 'cheers' in advance to anyone that may know of something or a site that can point me in a better direction function(value,element){return this.optional(element)||/^((\b[a-zA-Z]{2,80}\b)\s*){2,}/ The statement does what I want it to do, except if there is multiple instances of the word, it only outputs one, how can I work it so all instances are output in red? (while still using .slice) var phrase = prompt("Enter a messate: ", 'Message'); var searchFor = prompt("Enter search text: ", 's'); var matchPhrase = ""; var searchIndex = -1; /* if there's a match, create a text string by * add the phrase text from before the match, * add <font> tags around the match text, * add the rest of the phrase from after the match */ searchIndex = phrase.indexOf(searchFor); if (searchIndex >=0 ) { // Copy text from phrase up till the match. matchPhrase += phrase.slice(0, searchIndex); matchPhrase += '<font color="red">' + searchFor + '</font>'; matchPhrase += phrase.slice(searchIndex + searchFor.length); phrase++ } else { matchPhrase = "No matches" } document.writeln(matchPhrase); Reply With Quote 01-31-2015, 09:08 AM #2 Philip M View Profile View Forum Posts Supreme Master coder! Join Date Jun 2002 Location London, England Posts 18,371 Thanks 204 Thanked 2,573 Times in 2,551 Posts Use a regular expression. |