import random # The words that the game knows about: dictionary = ['apple','banana','python','prestidigitation'] # The grim scene. Numbers will be replaced with body parts # The numbers are in the order the body parts should be added scene = ['+--+ ', '| 1 ', '| 324', '| 5 6', '| ', '-----'] # These are the body parts # Notice the double back-slashes \\ are replaced with a single \ parts = '*|/\\/\\' # Go through the scene, and figure out where the parts go def make_part_indexes(): result = [0] * 6 for row in range(len(scene)): for col in range(len(scene[row])): symbol = scene[row][col] if symbol in '123456': # It's a number. First, replace it with a space scene[row] = scene[row][:col] + ' ' + scene[row][col+1:] # and get the corresponding part index = int(symbol) - 1 part = parts[index] # Finally, add 3 things to our result: # the part, and its row and column in the scene result[index] = (part, row, col) return result # call the function we just wrote part_indexes = make_part_indexes() # Show the grim scene def show_scene(): for row in scene: print row # These variables are used to play the game n_mistakes = 0 bad_guesses = '' letters_guessed = '' # Pick a random word from the dictionary secret = dictionary[random.randrange(0,len(dictionary))] solution = '_' * len(secret) # Main loop while n_mistakes < 6: # First, tell the user the state of the game show_scene() print solution if letters_guessed != '': print 'guesses:', letters_guessed # Get a guess from the user guess = raw_input('letter? ') if guess in letters_guessed: print 'You already guessed', guess # Is it a good guess? elif guess in secret: letters_guessed += guess # This sorts the letters guessed so far # sorted() returns a list, so we have to use join() # to make the list back into a string letters_guessed = ''.join(sorted(letters_guessed)) # wherever the guess matches the secret, put that # letter into the solution for i in range(len(secret)): if guess == secret[i]: solution = solution[0:i] + guess + solution[i+1:] # Check if we're done if solution == secret: print 'You win!' break # Is it a bad guess? else: letters_guessed += guess n_mistakes += 1 bad_guesses += guess print 'Bad guesses: ',bad_guesses # Replace one cell in the scene with a body part part = part_indexes[n_mistakes-1][0] row = part_indexes[n_mistakes-1][1] col = part_indexes[n_mistakes-1][2] scene[row] = scene[row][:col] + part + scene[row][col+1:] if n_mistakes >= 6: # We exited the while-loop, by losing. show_scene() print 'You lose!' print 'My word was', secret