I am creating a Hangman guessing game/machine. I know it's been done a million times before but I'm just starting out in python so I'm trying to figure out how to do it without having the answer thrown in my face.
I had initially copied the code out 7 times, was going to continue with an if statement up to 11 but with my VBA experience I thought I would try make it semi-smart even if it is only version 1 by adding a while loop in. (Plan for v2 is to add a bit of intelligence in, possibly a dictionary to cross reference/calculate letter frequencies etc. but just a pipe dream until version 1 is finished)
Basically the code was working fine when it was repeating but once I added the while loop in it first failed due to lnG1 and pos not being defined. So I added a list to define the values as 0 or "" even though they are being overwritten.
import random
lcGuess = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
lnLife = 7
lcWord = 'a'
while (len(lcWord)!=5):
try:
lcWord = str(input("""Fancy a game of Hangman? Pick a 5 letter word, I have 7 wrong guesses to
try figure it out \n """))
except:
print('5 letter words only')
lcClean = lcWord.lower()
tokens = list(lcClean)
maxVal = 25
x = 1
lnG1 = [0,0,0,0,0,0,0,0,0,0,]
pos1 = ["","","","",""]
pos2 = ["","","","",""]
pos3 = ["","","","",""]
pos4 = ["","","","",""]
pos5 = ["","","","",""]
maxChar = 0
while lnLife > 1:
g = random.randint(0,maxVal)
lnG1[x] = lcGuess[g]
print('My 1st guess is ' + str(lnG1[x]))
if lnG1[x] in tokens:
print('I guessed right ' + lnG1[x] + ' is in your word \n')
maxChar = lcClean.count(lnG1[x])
if maxChar >= 1:
pos1[x] = lcClean.find(lnG1[x])
if maxChar >= 2:
pos2[x] = lcClean.find(lnG1[x], pos1[x] + 1)
if maxChar >= 3:
pos3[x] = lcClean.find(lnG1[x], pos2[x] + 1)
if maxChar >= 4:
pos4[x] = lcClean.find(lnG1[x], pos3[x] + 1)
if maxChar >= 5:
pos5[x] = lcClean.find(lnG1[x], pos4[x] + 1)
if lnG1[x] not in tokens:
lnLife = lnLife - 1
print('I guessed wrong ' + lnG1[x] + ' is not in your word, I have ' +
str(lnLife) + ' lives left
\n')
del lcGuess[g]
maxVal = maxVal - 1
x = x + 1
So I thought the creating the list would fix it but now I am getting IndexError: list assignment index out of range at this line of code: pos1[x] = lcClean.find(lnG1[x])
Obviously don't get the error when all of the guesses are wrong.
The way I read it is pos1[1] should be = "" and is about to be replaced by the number of correct letters in the word
Apologies for how long winded this is. Any help would be appreciated.
Thanks!