Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hangman implementation [duplicate]

Tags:

javascript

SITUATION

I started to implement the game "HANGMAN" using only JavaScript and HTML on client side machines. I have completed all the logical work. Now only the aesthetics are remaining. And I am stuck up because we can't write to strings in JS.

a = "abcd"; a[0] = "e"; -- This type of thing is not allowed.

What I have done

CODE

The code I have tried, This does not work:

See here

I now have the following three arrays:

a -- The array that contains the letters of the word(for gel this would be g,e,l)

gai -- This array consists of the letters that have been entered by the user and are there in the word.(like g or e)

ag -- This array consists of the letters that have been entered by the user regardless of whether or not they are there in the word to be guessed or not.

What I need to do

I need to generate the output that would show the letter in case it has been guessed by the user and is there in the word(letters in the array gai) and _ in place of letters that have not yet been entered by the user.

What I want

A function that will return the desired output, as explained in the following example.

Example

Let the word to be guessed be:

together

User enters e:

The function should return: _ _ _ e _ _ e _

User then enters d, my program will prompt him to say that this letter is not there in the word.

User enters r

Function should return: _ _ _ e _ _ e r

And so on....

I hope you get the idea!

In case you don't get it(owing to my bad explanation or otherwise!!)

You can play a game of hangman here: Hangman

Just watch the output at the bottom of the screen... Thats what I want this function to generate.

Kindly help me with this issue!

like image 750
IcyFlame Avatar asked Jan 29 '26 20:01

IcyFlame


1 Answers

Reading just the start of your question (because no other code is provided), there is a problem which could be solved using native javascript functions.

var strarr = "Hello world!".split(''); // this will give you an array of characters to be manipulated
strarr[6] = "X"; // so you can do this
console.dir(strarr.join('')); // test it!

As an idea (not mine, its from comments) one could even wrap this simple code as a missing toCharArray() function and use that.

Another thing is that this method is fast enough even for relatively large bulk of text. For a test I used lorem ipsum with 1000 words. On my rather old dev machine, manipulation executes in milliseconds.

For more information, see this discussion.

like image 144
OzrenTkalcecKrznaric Avatar answered Jan 31 '26 10:01

OzrenTkalcecKrznaric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!