Python implements Hangman game

Interpretation of the game process

The computer randomly selects a word from a text, the string representation, and displays the length of the string. The user guesses one character by one character, and manually enters the guess result. There are a total of 6 guesses. After each guess, the computer informs the player that the player has been guessed. The guessing result and the remaining letter range that can be guessed have certain rules for the player's guessing process:

Cannot guess the characters that have already been guessed. Every time the guess is repeated, the computer will warn once, and there will be a total of 3 warning opportunities; characters other than uppercase and lowercase letters cannot be guessed, such as some special characters such as'#'. Every time you guess, you will be warned. The number of times is reduced by 1; when the number of warnings is gone, if the player continues to foul (repeated guessing, or guessing characters other than uppercase and lowercase letters), the number of guesses is reduced by 1; the letter guessed by the player is not in the target string secret_letters, if the guessed letter If it is a vowel, the number of guesses is reduced by 2 as a penalty. If it is a consonant, the number of guesses is reduced by 1. This guessing is too difficult for the player. Is it possible to implement an improved version of the game? Every time the player enters an asterisk * When the computer automatically outputs all words in the text that match the guessed result of the current player? This can greatly reduce the player's guessing range and reduce the difficulty of the game.

Modular programming ideas

How to realize this game? We must first implement some functions, these functions are as follows:

How the computer obtains the text How to randomly obtain the words from the text to determine whether the player guessed the characters correctly. Obtain the player’s guessed letters. Obtain the remaining guessable letters. The codes of the computer player interaction process are not given separately. The entire project is directly given below. The code

Game code

Hangman Game

import random

import string

WORDLIST_FILENAME = “words.txt”

def load_words():#Read file

print("Loading word list from file...") 

# inFile: file 

inFile = open(WORDLIST_FILENAME,'r') 

# line: string 

line = inFile.readline() 

# wordlist: list of strings 

wordlist = line.split( ) #Space separated words 

print(" ", len(wordlist), "words loaded.") 

return wordlist #Returns a list

wordlist=load_words()

def choose_word(wordlist):

return random.choice(wordlist) #Get a random word

#Judging whether the player's guess is correct

def is_word_guessed(secret_word, letters_guessed):

list_secret=list(secret_word) #As 

long as there is a letter in the target that is not in the player's guess result, return False, if all are there, return True 

for i in list_secret: 

    if i not in letters_guessed : 

        return False 

return True

#Get the letter that the player has guessed right

def get_guessed_word(secret_word, letters_guessed):

length=len(secret_word) 

list_secret=['_']*length #First initialize all list elements to'_' 

for i in letters_guessed: 

    for j in range(length):  

        if i==secret_word[j]: #用猜Replace the corresponding letter with 

            the'_ ' in the corresponding position list_secret[j]=secret_word[j] 



string="".join(map(lambda x:str(x),list_secret)) #List to string 

return string

#Get the remaining guessable letter range

def get_available_letters(letters_guessed):



#Initial guessable letters are all lowercase letters letters_all="abcdefghijklmnopqrstuvwxyz" 

for i in letters_all: 

    if i in letters_guessed: #If the player has guessed i, replace it 

        with'_ ' letters_all=letters_all.replace(i,'') 

return letters_all

def hangman(secret_word):

list_unique=[] #for secret_word deduplication 

for i in secret_word: 

    if i not in list_unique: 

        list_unique.append(i) 

unique_numbers=len(list_unique) #The number of different characters in the target word, used to calculate the player score 

vowels=" aeiou" 
#vowel letters 

print("Welcome to the game hangman!") 
length=len(secret_word) #target word length 

print("I'm thinking of a word that is {} letters long!".format(length) ) 

times_left=6 

#The number of remaining guesses of the player warning_left=3 #The number of remaining warnings of the player 

print("You have {} warnings left.".format(warning_left)) 

print("------------- ") 

list_guessed=[] 

while times_left>0: #Players have not used up the number of guesses 

    print("You have {} guesses left.".format(times_left)) 

    print("Available letters:",get_available_letters(list_guessed))

    char=input("Please guess a letter:") 

    x=str.lower(char) 

    if x in list_guessed:#The player has guessed the letter 

        if warning_left>0: 

            #The number of warnings is not used up warning_left-=1 

            print(" Oops! You've already guessed that letter. You have {} warnings left:".format(warning_left),get_guessed_word(secret_word,list_guessed)) 

        else: #The number of warnings is 0. Reduce the number of 

            guesses times_left-=1 

            print("Oops ! You've already guessed that letter.You have no warnings left,so you lose one guess:",get_guessed_word(secret_word,list_guessed)) 

        

    else: #The player has not guessed this letter 

        list_guessed.append(x) #First store the player guess Result 

        if not str.isalpha(x): #The player input is not a letter 

            if warning_left>0:

                warning_left-=1

                print("Oops!That is not a valid letter.You have {} warnings left:".format(warning_left),get_guessed_word(secret_word,list_guessed))

            else:

                times_left-=1

                print(" Oops! That is not a valid letter. You have no warnings left,so you lose one guess:",get_guessed_word(secret_word,list_guessed))

        #玩家输入是字母时

        elif x in secret_word:#玩家猜测字母在目标中

            print("Good guess:",get_guessed_word(secret_word,list_guessed))

            # 玩家猜出全部字母

            if secret_word==get_guessed_word(secret_word,list_guessed):

                print("------------- ")

                print("Congratulations, you won!")

                total_score=times_left*unique_numbers 

                print("Your total score for this game is:",total_score) 

                return  

        else: #The player guesses that the letter is not in the target 

            print("Oops! That letter is not in my word.",get_guessed_word(secret_word,list_guessed )) 

            if x in vowels: 

                #I did not guess correctly , and it is a vowel time_left-=2 

            else: 

                times_left-=1  

    print("------------- ") 

print("Sorry, you ran out of guesses.The word was {}".format(secret_word)) #The player fails, the game is over 

return  



"""

def del_space(string): # Convert the string into a list after removing spaces

lst=[]

for i in string:

    if i!=' ':

        lst.append(i)

return lst

#Check whether two words match according to the rules

def match_with_gaps(my_word, other_word):



#First convert the string into a list for easy operation list_my_word=del_space(my_word) 

list_other_word=list(other_word) 

if len(list_my_word)!=len(list_other_word): #length is not consistent 

    return False 

else: 

    length=len(list_my_word) 

    for i in range(length): 

        #The corresponding positions are all letters and are not equal if list_my_word[i]!='_' and list_my_word[i]!=list_other_word[i]: 

            return False 

    #list_my_word[i]=='_' 

    for i in range(length):  

        j=i+1 

        for j in range(length): 

            if list_other_word[i]==list_other_word[j] and list_my_word[i]!=list_my_word[j]: 

                return False 

return True

def show_possible_matches(my_word):

flag=0 
    #Used to mark whether there are possible matching words 

possible_word=[] #Store possible matching words 

for i in wordlist: 
if match_with_gaps(my_word,i): 

        flag=1 

        possible_word.append(i) 

if flag==0 : 

    #No possible matching word print("No matches found.") 

else: 

    print("Possible word matches are:") 

    for i in possible_word: 

        print(i,end='') 

print("")

def hangman_with_hints(secret_word):

list_unique=[] #for secret_word deduplication 

for i in secret_word: 

    if i not in list_unique: 

        list_unique.append(i) 

unique_numbers=len(list_unique) #The number of different characters in the target word, used to calculate the player score 

vowels=" aeiou" 
#vowel letters 

print("Welcome to the game hangman!") 
length=len(secret_word) #target word length 

print("I'm thinking of a word that is {} letters long!".format(length) ) 

times_left=6 

#The number of remaining guesses of the player warning_left=3 #The number of remaining warnings of the player 

print("You have {} warnings left.".format(warning_left)) 

print("------------- ") 

list_guessed=[] 

while times_left>0: #When the number of guesses is not used up 

    print("You have {} guesses left.".format(times_left)) 

    print("Available letters:",get_available_letters(list_guessed))

    char=input("Please guess a letter:") 

    x=str.lower(char) 

    if x in list_guessed:#The player has guessed this letter 

        if warning_left>0:  

            warning_left-=1 

            print("Oops!You've already guessed that letter.You have {} warnings left:".format(warning_left),get_guessed_word(secret_word,list_guessed)) 

        else: #The number of warnings is 0. Reduce the number of 

            guesses times_left-=1 

            print("Oops! You've already guessed that letter.You have no warnings eft,so you lose one guess:",get_guessed_word(secret_word,list_guessed)) 

        

    else: #The player has not guessed this letter 

        list_guessed.append(x) #Store the player's guess result first 

        if x==' *': #Yes'*' 的情况

            my_word=get_guessed_word(secret_word,list_guessed)

            show_possible_matches(my_word) 

        elif not str.isalpha(x): #The player input is not a letter and not a * sign 

            if warning_left>0: 

                warning_left-=1 

                print("Oops! That is not a valid letter. You have {} warnings left :".format(warning_left),get_guessed_word(secret_word,list_guessed)) 

            else: 

                times_left-=1 

                print(" Oops! That is not a valid letter.You have no warnings left,so you lose one guess:",get_guessed_word(secret_word ,list_guessed)) #When the 

        player input is a letter 

        elif x in secret_word:#The player guesses the letter in the target 

            print("Good guess:",get_guessed_word(secret_word,list_guessed)) 

            # The player guesses all letters

            if secret_word==get_guessed_word(secret_word,list_guessed):

                print("------------- ")

                print("Congratulations,you won!")

                total_score=times_left*unique_numbers

                print("Your total score for this game is:",total_score)

                return

        else: #玩家猜测字母不在目标中

            print("Oops! That letter is not in my word.",get_guessed_word(secret_word,list_guessed))

            if x in vowels: #没有猜中,且是元音字母

                times_left-=2

            else:

                times_left-=1 

    print("------------- ")

print("Sorry,you ran out of guesses.The word was {}".format(secret_word)) #The player fails, the game is over

return

“”"

if name == “main”:

secret_word=choose_word(wordlist)

hangman(secret_word)



#secret_word = choose_word(wordlist)

#hangman_with_hints("apple")

Note that the commented out part is to implement an improved version of the hangman game, a version with a computer prompt function. Whenever the user enters *, the computer outputs all the words in the text that match the current guessed result to narrow down the player Guess the range as a reminder. The game effect is as follows: If there is any problem with the project code, please feel free to point it out, thank you very much!
Article source: Web game http://www.hp91.cn/ Web game

Guess you like

Origin blog.51cto.com/14621511/2679083