Sunday, 15 February 2015

Python hangman, replacing letters? -



Python hangman, replacing letters? -

how create python hangman game replace underscores in variable blanks right letter if guessed.

i have right if statement not sure how letters replaced.

this tried:

def main() if selection in correctanswer: print("\ncorrect!\n------...\n") index = 0 while index < len(correctanswer): index = correctanswer.find(choice, index) if index == -1: break print(index) index += 1 used.append(choice) places = [] place=correctanswer.index(choice) blanks[place]=choice blanks=''.join(blanks) main()

that gives me typeerror: typeerror: 'str' object not back upwards item assignment

any ideas on how this?

thanks

update:

blanks = list(makeboard(correctanswer)) print (correctanswer) def main(): used = [] print(blanks) selection = input("\nenter letter:") if len(choice) == 1 , special_match(choice) == true: if selection in correctanswer: print("\ncorrect!\n--------------------------------------------------------------------\n") index = 0 while index < len(correctanswer): index = correctanswer.find(choice, index) if index == -1: break print(index) index += 1 used.append(choice) [choice if letter == selection else blank blank, letter in zip(blanks, correctanswer)] main()

you'd improve off working list because strings immutable

>>> blanks = list('_______') >>> reply = 'hangman' >>> guess = 'g' >>> blanks[answer.index(guess)] = guess >>> blanks ['_', '_', '_', 'g', '_', '_', '_']

so keeps blanks mutable can replace elements @ will. when want display user string

>>> ''.join(blanks) '___g___'

a list comprehension handle repeated letters

>>> [guess if letter == guess else blank blank, letter in zip(blanks, answer)] ['_', 'a', '_', '_', '_', 'a', '_']

edit please see next quick demo, note should add together handling of wrong guesses

answer = 'hangman' blanks = list('_'*len(answer)) guess in set('hangman'): blanks = [guess if letter == guess else blank blank, letter in zip(blanks, answer)] print(''.join(blanks))

output

h______ h__g___ h__gm__ ha_gma_ hangman

python

No comments:

Post a Comment