user10307893
user10307893

Reputation: 1

How do I build a list of the same length as a string for my hangman game?

I'm writing a hangman game and can't figure out how to account for words of varying lengths, and my code doesn't seem to work.

Here are the steps:

  1. A word is randomly selected from a list of strings
  2. A board is built resembling ['_','_','_','_','_','_']
  3. The user guesses a letter
  4. Replace the board with any matches in the word based on the input
  5. End the game when the turns are up or the letter has been found

word = random.choice(i)
guesses = 0
turns = 11
a = [['_']*len(word)]
print(a)

print ( word)
while turns > 0:
  letter = input('Enter a letter:')
  for i in range (0, 6):
      if word[0][i] == letter:
          a[0][i] = letter
          print(a)

  if a == word:
      turns -= 1
      print("You won. ")
  else :
      turns -= 1

Upvotes: 0

Views: 56

Answers (3)

JBallin
JBallin

Reputation: 9787

You need to loop through the entire length of word, instead of only 6 letters:

for i in range (0, len(word)):

Don't put a inside of a list, to get your desired format:

a = ['_']*len(word)
print(a) # ['_','_','_','_','_','_']

In your loop you should just access i directly

if word[i] == letter:
    a[i] = letter

Check that the game is over by joining the list of letters together into a string:

print(''.join(['h', 'i']) # 'hi'

if ''.join(a) == word:

If they won, break out of the while loop:

print("You won. ")
break

For style, add a space after the input prompt:

letter = input('Enter a letter: ')

Also, remove the guesses variable if you aren't using it. And don't print(word) (once you're done debugging).


NOTE: This assumes that word is a string, not a list of strings. I believe this is a better implementation.

Upvotes: 2

MadLordDev
MadLordDev

Reputation: 260

I agree with @JBallin , but instead of

for i in range (0, len(word)):

you can use

for index,ch in enumerate(word):

where index is from 0 to length of the word, and ch is the character itself

Upvotes: 0

Stefano Gogioso
Stefano Gogioso

Reputation: 235

A working example:

word = "dead"
guesses = 0
turns = 11
a = ["_" for i in range(0,len(word))]
print(a)

print (word)
while turns > 0:
    letter = input('Enter a letter:')
    for i in range (0, len(word)):
        if word[i] == letter:
            a[i] = letter
    print(a)

    if "".join(a) == word:
        print("You won.")
        break
    turns -= 1

Upvotes: 1

Related Questions