PDA

View Full Version : While loop problems for hangman game



offski
Sep 18th, 2009, 03:46 PM
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!

Philip M
Sep 18th, 2009, 05:24 PM
This will move you forward (note the syntax of indexOf):-


<script type = "text/javascript">

function getInput(){
var allGuesses = '';
var inputCharacter;
while (inputCharacter = window.prompt("Enter a single lower-case character then OK, or Cancel to end"," ")) {
inputCharacter = inputCharacter.replace(/^\s+/,""); // strip leading spaces
// test for a valid entry
if ((/[^A-Z]/gi.test(inputCharacter)) || (inputCharacter == "") || (inputCharacter.length >1)) {
alert ("You must enter a valid single letter! ");
}
else {
if (allGuesses.indexOf(inputCharacter) ==-1) { // inputCharacter not found
allGuesses += inputCharacter;
}
else {
alert ("You have already entered " + inputCharacter + " - try again!")
}
}

}

document.write(allGuesses);
}

getInput();
</script>

But why cannot the same letter occur twice in Hangman? There is no such rule!


"In the beginner's mind there are many possibilities, but in the expert's mind there are few” - Shunryu Suzuki (Japanese Zen priest, ?-1971)

offski
Sep 18th, 2009, 06:00 PM
That has really helped, thankyou! It was begining to get more than tedious, I've been at it for hours.. thanks again :-)