# GuessAWordSolutions.py Copyright (c) Kari Laitinen # http://www.naturalprogramming.com # 2013-10-10 File created. # 2022-12-28 Converted to Python 3. # Solutions to exercises with program GuessAWord.py import random games_played = 0 played_words = [] guesses_in_games = [] user_wants_to_play_more = True while user_wants_to_play_more == True : print( "\n This is a GUESS-A-WORD game \n" ) words_to_be_guessed = [ "VIENNA", "HELSINKI", "COPENHAGEN", "LONDON", "BERLIN", "AMSTERDAM" ] random_word_index = int ( ( random.random() * len( words_to_be_guessed ) ) ) word_to_be_guessed = words_to_be_guessed[ random_word_index ] number_of_guesses = 0 guessed_characters = len( word_to_be_guessed ) * [ "_" ] # Now guessed_characters refers to a list that contains as # many strings "_" as there are characters in the word to be guessed # By writing "".join( guessed_characters ) the list of strings can # be converted to a single string. game_is_over = False while game_is_over == False : print( " " + "".join( guessed_characters ) + " " + "Give a character or word: ", end="" ) player_input = input().upper() # input and convert to uppercase number_of_guesses += 1 if len( player_input ) == 1 : # The player gave a single character for character_index in range( len( word_to_be_guessed ) ) : if word_to_be_guessed[ character_index ] == player_input : guessed_characters[ character_index ] = player_input if not "_" in guessed_characters : # "_" is not among the guessed characters. # This means that all characters have been guessed. game_is_over = True print( " " + "".join( guessed_characters ) + " " + "Congratulations!!" ) elif len( player_input ) > 1 : # The player tried to guess the whole word. if player_input == word_to_be_guessed : print( "\n Congratulations!!! \n" ) game_is_over = True else : # The player gave an empty string. # That means that she does not want play any more. game_is_over = True print( "\n You made " + str( number_of_guesses ) + " guesses.\n" ) games_played += 1 played_words.append( word_to_be_guessed ) guesses_in_games.append( number_of_guesses ) print( "\n You want to play more (Y/N) ? ", end="" ) # User input will be 'stripped' of whitespace characters, # and it will be converted to uppercase character(s). user_choice = input().strip().upper() if not user_choice == "Y" : user_wants_to_play_more = False print( "\n PLAYED WORD GUESSES \n" ) for game_index in range( games_played ) : print( " %-14s %4d" % ( played_words[ game_index ], guesses_in_games[ game_index ] ) )