JavaScript - Javascript Hangman
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 Similar Tutorialsive 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 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> 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! 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! Hello! I am trying to find a script that allows you to open multiple browser tabs and then close each of those tabs, either one by one or all at once. Does anyone know how to do this please? Thanks so much for your help. I want to have another go at Javascript. I have several books on the subject but I find that my eyesight is a major problem. Therefore I want to try an on-line solution, preferably free. I have Googled, but there are so many that I am almost dizzy with the choices. Perhaps someone could recommend one. Not too fussy visually. My knowledge is VERY basic. Frank Does anyone know how to make URL links that use Javascript still work when users have Javascript disabled on their browser? The only reason I'm using JS on a URL is because my link opens a PDF file, and I'm forcing it not to cache so users have the latest version. I tried the <script><noscript> tags, but I'm not sure if I'm using it correctly, as my URL completely disappears. Below is my HTML/Javascript code: <p class="download"> <script type="text/javascript">document.write("<span style=\"text-decoration: underline;\"><a href=\"javascript:void(0);\" onclick=\"window.open( 'http://www.webchild.com.au/mediakit/Direct_Media_Kit_Web.pdf?nocache='+ Math.floor( Math.random()*11 ) );\" >The Child Magazines Media Kit</a></span> (PDF 1 MB) ");</script> <noscript><span style="text-decoration: underline;"><a href="http://www.webchild.com.au/mediakit/Direct_Media_Kit_Web.pdf" >The Child Magazines Media Kit</a></span> (PDF 1 MB)</noscript> </p> Thanks for any help, Michael Hi Guys, I am new at JavaScript and start to do some tutorials.What I am trying to do here is prompting user to input a name and if the name was valid the page(document) will display with all objects like the button.But if user enter a wrong name then the button will be disabled! I create the following code but it did not work <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>New Web Project</title> <script language="JavaScript" type=""> function changeColor(){ document.bgColor = "Gray"; } </script> </head> <body> <script language="JavaScript" type="text/javascript"> var person = ""; person = prompt('What is Your Name:'); if (person == "Foo") { document.write("<h1 />Welcome " + person); document.bgColor = "Yellow"; } else { document.write("<h1 />Access Denied!!!!"); document.bgColor = "Red"; document.getElementById("gree").disabled = true; } </script> <div> <p/><input id="gree" type="button" value="Gray " onClick="changeColor();"> </div> </body> </html> as you can see I used the: document.getElementById("gree").disabled = true; but it did not work , could you please give an idea how I can solve this problem? Thanks Hi, I have the following code snippet: test.html ====== <script language="javascript" type="text/javascript"> var testVariable = "test"; </script> <script language="javascript" type="text/javascript" src="test.js"> </script> test.js ===== var testVariable = window.top.testVariable; In firefox, I'm able to access testvariable defined within test.html in test.js. But in chrome, test.js couldnot get the window.top.testVariable field defined in test.html. Can any one please let me know how i can make it work in chrome?. Am i missing something here?. I want to insert this js snippet Code: function addText(smiley) { document.getElementById('message').value += " " + smiley + " "; document.getElementById('message').focus(); return false; } to a loaded iframe with name&id chtifrm. I can access it & change embed something in its html via using something like: Code: $(parent.chtifrm.document.body).append('<div id=\"smly\" style=\"cursor:pointer;float:left;top:200px;display:none;position:absolute;\"><\/div>'); .... Code: parent.chtifrm.document.getElementById('chatbox_option_disco').style.display == 'none' but how do I insert js in the head of loaded iframe? Hey, I've got to make the values of some textboxes change the co-ordinates of my sprite on a canvas and havent a clue on how to do it, Here is my form with the two textboxes and submit button: <form> x: <input type="text" name="x" /><br /> y: <input type="text" name:"y" /><br /> <input type="submit" value="Submit"/><br /> </form> And i need it so that they change the values of these: //this shows where my sprite will start on the canvas var block_x; var block_y; searched the internet for hours and cant really find anything i understand or works. any help is much appreciated Hi Guys I am trying to modify the functionality of my page. I want to be able to activate this piece of code using another javascript function. This is the code I want to activate: Code: <script type="text/javascript"><!-- $('#button-cart').bind('click', function() { $.ajax({ url: 'index.php?route=checkout/cart/update', type: 'post', data: $('.product-info input[type=\'text\'], .product-info input[type=\'hidden\'], .product-info input[type=\'radio\']:checked, .product-info input[type=\'checkbox\']:checked, .product-info select, .product-info textarea, .date_data input[type=\'text\']'), dataType: 'json', success: function(json) { $('.success, .warning, .attention, information, .error').remove(); if (json['error']) { if (json['error']['warning']) { $('#notification').html('<div class="warning" style="display: none;">' + json['error']['warning'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>'); $('.warning').fadeIn('slow'); } for (i in json['error']) { $('#option-' + i).after('<span class="error">' + json['error'][i] + '</span>'); } } if (json['success']) { $('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>'); $('.success').fadeIn('slow'); $('#cart_total').html(json['total']); $('html, body').animate({ scrollTop: 0 }, 'slow'); } } }); }); //--></script> And this is how I want the format of the function to be: function testsession() { if there is a session called 'hiredate' { activate the script above } else { var el = document.getElementById("product_data"); } } I just dont know how to write this in javascript Could you help me if possible please I got an index.php Code: <html> <form action="bacakomik.php" method='post'> <select name="kodekomik"> <option value='../komik1/|23'>Judul Komik1</option> <option value="../komik2/|20">Judul Komik2</option> <option value="../komik3/|10">Juduk Komik3</option> <option value="../komik4/|20">Judul Komik4</option> </select> <input type="submit" /> </form> <?php echo ('<select>'); echo ('<option value= "'.$i.'">'.'Page '.$i.'</option>'); echo ('</select>'); ?> </html> As you can see, each of the option brings specific value "../komik1/|23" komik1 is a directory | is a delimiter 23 is the pages in one chapter and can be considered also as how many images are there on a specific directory This is my bacakomik.php Code: <?php $dirkomik = $_POST['kodekomik']; $exploded = explode("|", $dirkomik); echo ($exploded[0]); //picture directory echo ("<br>"); echo ($exploded[1]); //total page in the comic $pagecount = (int)$exploded[1]; //Take last posted value, process it right away echo ('<FORM name="guideform"> '); echo ('<select name="guidelinks">'); $i=1; do { echo ('<option value= "'.$i.'">'.'Page '.$i.'</option>'); $i= $i+1; }while($i <= $pagecount); //Printing option and select echo ("</select>"); ?> <input type="button" name="go" value="Go!" onClick="document.getElementById('im').src=document.guideform.guidelinks.options[document.guideform.guidelinks.selectedIndex].value+'.png';"> </FORM> <img src="img0.jpg" id="im"> With the current code on bacakomik.php, I only can change the img src of id "im" in the same directory only. What I want is that the Javascript could "add" the "$exploded[0]" variable so that the picture can be loaded from different directory. Anyone can do this? I believe that the fix should be somewhere on input tag inside OnClick, or do you know where? Anyway, I found this on the net http://p2p.wrox.com/php-faqs/11606-q...avascript.html Please help me to those who can... All -- I have a JavaScript config file called gameSetting.js which contains a bunch of variables which configures a particular game. I also have a shared JavaScript library which uses the variables in gameSetting.js, which I include like so: <script type="text/javascript" src="gameSetting.js" ></script> <script type="text/javascript" src="gameLibrary.js" ></script> In gameSetting.js I have: $(document).ready(function() { // call some functions / classes in gameLibrary.js } in Firefox, Safari, and Chrome, this works fine. However, in IE, when it's parsing gameSetting.js, it complains that the functions that live in gameLibrary.js aren't defined. When it gets to parsing gameLibrary.js, the variables in gameSetting.js are reported as not being defined. I've tried dynamically bootstrapping the gameLibrary file using this function in document.ready for dynamic load... $.getScript("gameLibrary.js"); However, the same problem still happens in IE, where when it parses the files individually it's not taking into context the file/variables that came before, so it's not an out of load order problem. My options a 1) collapsing all the functions in gameLibrary.js and variables in gameSetting.js into one file. However, this is not practical because this is dealing with literally hundreds of games, and having a gameLibrary.js in ONE location for ONE update is what makes most logical sense. 2) figure out a way to get this to work where variables in file1 are accessible to file2 in IE (as it seems they are in other browsers). jQuery seems to be able to have multiple plugins that all refer to the based jQuery-1.3.2.js, so I know there is a way to get this to work. Help appreciated. Nero I wrote a log function that took note of various function calls. Thinking that functions are first class objects, and objects have properties, I made the name of each logged function a property of that function, e.g., brightenInnerPara.name = "brightenInnerPara"; Every browser I tried (Firefox, MSIE, Opera, Chrome, Safari) accepted the assignment, no problem. In Firefox and MSIE, the result was what I wanted: brightenInnerPara.name == "brightenInnerPara" But in the others, the result was: brightenInnerPara.name == null Question 1. Which Javascript is correct here? I favor Firefox and MSIE, not merely because they were willing to give me what I wanted, but also because it makes no sense to accept an assignment statement without throwing an error and then give it a null semantics, like Chrome, Opera, and Safari did. I found a workaround, using assignments like this: brightenInnerPara.prototype.name = "brightenInnerPara"; To my surprise, that worked in every browser. But I don't know why. It seems that such assignments are enough to cause each function to have its own distinct prototype. Question 2. Just how inefficient is my workaround, and why does it work? I'v very new to javascript and need some help. Here's what I need to do: I need to have a text input with a button, and when the button is clicked the text must be copied to a div. When copying, each character needs to be placed on a separate line within that div container. Before this happens though, the content currently in the div must be cleared. This probably very simple, but as I said i'm new and confused out the wazoo. Thanks in advance! Sir i have a problem that, in head tag i have a easyslider script that working well, now i want to add new script of lightbox for image viewing but it does not working, when i remove the slider script files then lightbox working properly but when i add slider scripts files then lightbox not working, may be some function have same names or may be other problem i do not know. plz help me This is my javascript: <script type=text/javascript> function alert(){var value=1; alert("value");} </script> <?php Some Code.... ?> Now i want to convert "var value" in to php variable in my php script on the same page. How can i do it? Hi I am trying to remove spaces from the 'username' field but leave the spaces in the first and last name fields. The below code removes *one* space from the string but no more. Code: <html> <head> <title> </title> <script language="javascript"> function makename() { var firstname = document.mine.firstname.value; var lastname = document.mine.lastname.value; var username = firstname + "." + lastname; document.mine.username.value = (username.replace(" ", "")); } </script> </head> <body> <form name="mine" method="post"> UserName <input type="text" name="username" readonly/> <br />First Name <input type="text" name="firstname" onkeyup="makename()"/> <br />Last Name <input type="text" name="lastname" onkeyup="makename()" /> <p><input type="submit" /> </form> </body> </html> I am thinking I need to run a do, while loop eg. Code: do { document.mine.username.value = (username.replace(" ","")); } while (username still contains space) But I am not sure how to define username still contains space user pastes 32 characters into the first split textbox, the method will place 8 characters into each of the 4 textboxes i have 4 text box ... max length (8) bro i want this in textbox <input type = "text" size = "8" maxlength="32" name = "LicenseNumber1" id="LicenseNumber1"> <input type = "text" size = "8" maxlength="32" name = "LicenseNumber2" id="LicenseNumber2"> <input type = "text" size = "8" maxlength="32" name = "LicenseNumber3" id="LicenseNumber3"> <input type = "text" size = "8" maxlength="32" name = "LicenseNumber4" id="LicenseNumber4"> & my license is 32 characters like 06e1823681f48e2f013904403b33ff08 now if i paste the whole 32 character in my first test box i.e. LicenseNumber1 then i want other three textbox wil be automatic fill bcause(8*4=32) |