【问题标题】:Python HangMan game using functions使用函数的 Python HangMan 游戏
【发布时间】:2021-08-11 19:39:08
【问题描述】:

所以我正在尝试用 Python 制作一个小刽子手游戏。我已经管理过了,但我看到很多其他人使用函数来实现这一点。这是我没有使用函数的代码:


from hangman_words import word_list
import random

def select_word():
    return random.choice(word_list)


hidden_word = select_word()
char_lines = "_" * len(hidden_word)
guessed_letters = []
Lives = 8

game_start = input("Would you like to play HangMan? (Y/N)\n")
if game_start.upper() == "Y":
    prompt_user = True
elif game_start.upper() == "N":
    print("*Sad Python Noises*")
    prompt_user = False
else:
    print("You to say 'Yes'(Y) or 'No'(N)")

while (Lives > 0 and prompt_user == True):
    user_input = input("Choose a letter!\n\n")
    user_input = user_input.upper()
    if user_input.upper() in guessed_letters:
        print("\nYou have already guessed that letter. Choose something else!")
    elif hidden_word.count(user_input) > 0:
        for i, L in enumerate(hidden_word):
            if L == user_input:
                char_lines = char_lines[:i] + hidden_word[i] + char_lines[i+1:]
        print("\nCorrect!")
        print(char_lines)
    else:
        guessed_letters.append(user_input)
        print("\nNope, that letter isn't in the word. Try again!")
        Lives -= 1

    if char_lines == hidden_word:
        print("Well done! You won the game!")
        print(f"You had {Lives} lives remaining and your incorrect guesses were:")
        print(guessed_letters)
        exit()

    print(f"Lives remaining: {Lives}")
    print(f"Incorrect guessed letters: {guessed_letters}")
    print(char_lines)

    if (Lives == 0 and prompt_user == True):
        print("You have ran out of lives and lost the game!.....you suck")

    if prompt_user == False:
        print("Please play with me")

我目前使用函数的版本代码是这样的:

from hangman_words import word_list
import random


def select_word():
    global blanks
    selected_word = random.choice(word_list)
    blanks = "_" * len(selected_word)
    return selected_word, blanks


def game_setup():
    global lives
    global guessed_letters
    global hidden_word
    lives = 20
    guessed_letters = []
    hidden_word = select_word()
    return lives, guessed_letters, hidden_word 


def play_option():
    game_start = (input("Would you like to play HangMan? (Y/N)\n")).upper()
    if game_start == "Y":
        global prompt_user
        prompt_user = True
        game_setup()
        return prompt_user
    elif game_start == "N":
        print("*Sad Python Noises*")
        exit()
    else:
        print("You need to say 'Yes'(Y) or 'No'(N)")


def user_input_check(user_input):
    if type(user_input) != str: # [Want to check if unput is of tpye Str]
        print("Please input letter values!")
    elif user_input != 1:
        print("Please only input single letters! (e.g. F)")
    else:
        pass


def game_board(user_input, hidden_word, guessed_letters, blanks, lives):
    if user_input in guessed_letters:
        print("You have already guessed that letter. Choose something else!")
    elif hidden_word.count(user_input) > 0:
        for i, L in enumerate(hidden_word):
            if L == user_input:
                blanks = blanks[:i] + hidden_word[i] + blanks[i+1:]
        print("Correct!")
        print(blanks)
    else:
        guessed_letters.append(user_input)
        print("Nope, that letter isn't in the word. Try again!")
        lives -= 1

    print(f"Lives remaining: {lives}")
    print(f"Incorrect guessed letters: {guessed_letters}")
    print(blanks)
    return


def win_check(blanks, hidden_word, lives, guessed_letters):
    if blanks == hidden_word:
        print("Well done! You won the game!")
        print(f"You had {lives} lives remaining and your incorrect guesses were:")
        print(guessed_letters)
        exit()


def lives_check(lives, prompt_user):
    if (lives == 0 and prompt_user == True):
        print("You have ran out of lives and lost the game!.....you suck")
        exit()


play_option()

while (lives > 0 and prompt_user == True):
    user_input = (input("Choose a letter!\n\n")).upper()
    user_input_check(user_input)
    game_board(user_input, hidden_word, guessed_letters, blanks, lives)
    win_check(blanks, hidden_word, lives, guessed_letters)
    lives_check(lives, prompt_user)

我认为我真的应该使用类而不是函数,但我想先让它与函数一起使用,然后尝试调整它以与类一起使用。如果我使用函数, return 实际如何工作?返回变量名称是否将这些变量放在全局名称空间中?还是仅当您将返回值分配给全局名称空间变量时才返回有效?像这样:

def add_one(a):
    return a + 1

b = add_one(3) # b = 4

【问题讨论】:

  • 我知道我在游戏的函数版本中使用了全局命令,这正是我为了让它工作而改变的,我知道脚本中的全局命令是可能很愚蠢
  • return 与全局变量或全局范围没有任何关系。你是对的,如果一个函数返回一些东西,首先调用该函数的代码应该以某种方式捕获返回的值,比如在变量中。这个变量可以是全局变量,也可以是局部变量,没有区别。
  • 这能回答你的问题吗? What is the purpose of the return statement? 如果您唯一的问题是“退货是如何工作的?”,您可以通过快速的网络搜索轻松找到它。所有这些代码似乎与您的问题无关。请使用tour,阅读How to Askon-topicHow much research effort is expected of Stack Overflow users?,如果您对代码有具体问题,如何提供minimal reproducible example。欢迎使用 Stack Overflow!

标签: python function return


【解决方案1】:

你是对的,通过将函数设置为等于你返回它的任何值来返回工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    相关资源
    最近更新 更多