-2

So I'm trying to make a little hangman game in Python. I've managed it already, but I've seen lots of other people using functions to achieve this. Here's my code without using function:


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")

My current code for the version using functions is like this:

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)

I think I should be using classes instead of functions really, but I'd like to get it work with functions first, then try adapting it to work with classes. If I'm using functions, how does return actually work? Does returning variable names put those variables within the global name-space? Or does return only work when you assign the returned value to a global name-space variable? Like this:

def add_one(a):
    return a + 1

b = add_one(3) # b = 4
Mo0rBy
  • 165
  • 2
  • 15
  • I know I've used the global command in the functions version of the game, this was just what I was changing to try and get it to work, I understand that the global commands in the script are probably pretty stupid – Mo0rBy Aug 11 '21 at 19:40
  • 1
    `return` doesn't have anything to do with global variables or global scope. You're correct, that if a function returns something, the code that called the function in the first place should capture the returned value in some way, like in a variable. This variable could be global, or a local variable, it makes no difference. – Paul M. Aug 11 '21 at 19:45
  • Does this answer your question? [What is the purpose of the return statement?](https://stackoverflow.com/questions/7129285/what-is-the-purpose-of-the-return-statement) If your only question is "how does return work?", you could easily find this by doing a quick web search. All that code seems irrelevant to your question. Please take the [tour], read [ask], [on-topic](/help/on-topic) and [How much research effort is expected of Stack Overflow users?](//meta.stackoverflow.com/a/261593/843953), and how to provide a [mre] if you have a specific question about your code. Welcome to Stack Overflow! – Pranav Hosangadi Aug 11 '21 at 19:58

1 Answers1

0

You're correct, return works by setting the function to be equal to whatever you return it as.

Dpythonrobot
  • 46
  • 10