jeudi 5 mars 2020

Python: random() function called from within another function [closed]

Below is a snippet from a very, very simple text-based adventure game I'm using as a learning exercise.

The full script is here. (Yes, it's disgusting, hacky and horrible-I know. I plan to rewrite the entire thing as classes or some other more elegant approach soon.)

import random
import sys

def getExit():
    exitNum = random.randint(2,3)
    return exitNum

def playerWins():
    print('You\'re out. Yay. Presumably you found the massive hole in the floor?')
    playAgain = input("Play Again? 'y' or 'n'")
    if playAgain == 'y':
        exitLoc = getExit()
        room1(exitLoc)
    if playAgain == 'n':
        print("Scared, huh? Obviously you hate puzzles with as many as 3 pieces. Let\'s see how you handle my fiendish two piece rubix cube...anyhow, see ya.")
        sys.exit()

When the game is first run, the user searches through rooms until they find the one containing the exit. The exit can be found in either room 2 or 3, determined by the output of randint(2,3).

At this point, the playerWins() function is called. No issues here (although the code could do with a LOT of tidying up-I know that! Go easy :) ).

My issue is with obtaining a new random number if the user wants to play again. Currently, no new number is generated.

I believe the issue is that since the function to generate a new random number, getExit(), sits within playerWins(), it is only being called locally and so its value is lost. I'm guessing one potential solution would be, at the end of the playerwins() function, to return getExit(), but having tried this, I feel that this would at best make for some horrifically confusing code.

Another potential solution would be, within playerWins(), to assign getExit() to a global function. I want to avoid doing this because, again, it would make for very bad practice from what I've heard; I want to stick to local variables in functions wherever possible.

Is there a cleaner solution?

Thanks.




Aucun commentaire:

Enregistrer un commentaire