0

I've written a simple game that compares a lucky number solicited from the user to a simulated dice roll. I've managed to add a scoring feature as well, but now I want to add a replay feature. The best way I can think to do this is with a "Replay" function. Here's what I've got:

import random

lucky_number = None
dice_roll = None
score = 0


def get_lucky_number():
    print("What's your lucky number?")
    global lucky_number
    lucky_number = int(input())

    while lucky_number > 6 or lucky_number < 1:
        print("Error! Try again!")
        get_lucky_number()


def roll_dice():
    global dice_roll
    dice_roll = random.randrange(1, 7, 1)
    print("Your lucky number is " + str(lucky_number) + "!")
    print("Your dice rolled a " + str(dice_roll) + "!")


def score_and_output():
    if lucky_number == dice_roll:
        global score
        score = score + 1
        print("You won! Your score is " + str(score) + "!")
    else:
        print("You lose! Your score is " + str(score) + "!")


def replay():
    play_again = input("Would you like to play again? Type 1 if Yes, 2 if No!")
    if play_again == 1:
        game()
    else:
        quit()


def game():
    get_lucky_number()
    roll_dice()
    score_and_output()
    replay()


game()

Problem is, the game() function doesn't yet exist when called by replay(). How do I get around this?

wex
  • 21
  • Did you run your code to see if it works or not? – rdas Sep 12 '22 at 14:30
  • It is impossible to call a function that doesn't exist. You'll overcome this by rearranging your code. However, you need to consider the (almost certainly) unwanted recursion -> game() calls replay() which potentially calls game() – DarkKnight Sep 12 '22 at 14:31
  • 4
    your code runs fine. what's the issue? – rv.kvetch Sep 12 '22 at 14:31
  • 2
    The order of function definition doesn't matter. The only thing you need to change is this line: From `if play_again == 1:` to `if play_again == '1':` – JNevill Sep 12 '22 at 14:32
  • You are thinking as if Python was a compiled language. If it was in C++ it wouldn't work because of circular referencing but that is not a problem in Python – Bruno Mello Sep 12 '22 at 14:33
  • Solved my issue! I simply needed to quote around the 1. – wex Sep 12 '22 at 14:41

1 Answers1

1

Your code in fact works fine, but you may want to adjust it to make the flow clearer and avoid maximum recursion limits - have replay return a response, and use a while loop that continues until the user no longer wants to.

def replay():
    play_again = input("Would you like to play again? Type 1 if Yes, 2 if No!")
    return play_again == "1"

def game():
    while True:
        get_lucky_number()
        roll_dice()
        score_and_output()
        if not replay():
            return      # break out of the loop and quit game
            
Stuart
  • 9,597
  • 1
  • 21
  • 30