简体   繁体   中英

How to have a value decrease or stay the same after a general function call?

So I am creating a hangman game. I want the remaining number of guesses to remain the same if the player guesses a letter that is in the puzzle, and I want it so decrease by 1 if they do not guess correctly. The issue I am having is since my function which checks whether the guess is in the word or not is defined outside of the main() function, each time it is called it will simply reset the value of the number of guesses remaining to what it is at the time of the function call. How do I change it so that it will still call the function when it's supposed to but decrease the remaining guesses accordinly?

def update_puzzle_string(puzzle,answer,guess):
    update_bool=False
    if guess in answer: 
        update_bool=True
        for i, letter in enumerate(answer):
            if answer[i]==guess:
                puzzle[i]=guess                
    return update_bool


def play_game(puzzle,answer):
    guess=get_guess()      
    did_update=update_puzzle_string(puzzle,answer,guess)
    update_puzzle_string(puzzle,answer,guess)
    print(did_update)
    display_puzzle_string(puzzle)

def main():

    # general identifiers
    answer_update_msg='The answer so far is '

    #instruction identifiers
    instruct_filename='instructions.txt'
    mode='r'

    #puzzle word list identifiers
    list_filename='word_list.py'

    #choose word identifiers
    correct_answer=[] 

    #puzzle_string identifier
    puzzle_state=[]

    #print instructions    
    print_instruction(instruct_filename,mode)

    #stores correct answer as a string, identifier answer
    correct_answer=choose_word(correct_answer,list_filename,mode)   

    #number of guesses the player has 

    num_guesses=4

    for letter in correct_answer:
        puzzle_state.append('_')  

    while num_guesses>=0:
        play_game(puzzle_state,correct_answer)


main()

Return a value from play_game that will update your guesses

while num_guesses>=0:
    num_guesses = play_game(puzzle_state, correct_answer, num_guesses)

So Over here you check if the word was correct.. ( i am guessing did_update holds the Boolean value for this). so you check if it didnt update( answer provided was wrong.. in which case you decrements the num_guesses and return it.

def play_game(puzzle, answer, num_guesses):
    guess=get_guess()      
    did_update=update_puzzle_string(puzzle,answer,guess)
    update_puzzle_string(puzzle,answer,guess)
    print(did_update)
    display_puzzle_string(puzzle)
    if not did_update :
        num_guesses -= 1
    return num_guesses

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM