Question

I'm new in Python but bear with me.

In my code, I am trying to make variable room to 2, via west() function.

Code:

EDIT: I have isolated most of the non-essential code.

room = 1

cmds = 'west'.lower()

def isValidCMD(cmd):
    if cmd in cmds:
        return True
    else:
        print("Unknown command. For help type /help, for available options type /options")
        cmd = input(">> ")
        if isValidCMD(cmd):
            runCMD(cmd)
        return False

def runCMD(cmd):
    if cmd == '/help':
        help()
    elif cmd == '/exit':
        exit()
    elif cmd == '/about':
        about()
    elif cmd == '/stats':
        stats()
    elif cmd == '/options':
        options()
    elif cmd == 'north':
        north()
    elif cmd == 'south':
        south()
    elif cmd == 'east':
        east()
    elif cmd == 'west':
        west()
    elif cmd == '/lookaround':
        look_around()

def west():
    if room == 1:
        print("You head on over to the lab, to get some advice from Professor Andrew.")
        return 2 #LINE 40 < -------
    elif room == 7:
        print("You head back to Auderban Square feeling primed for battle.")
    else:
        print("You cannot go west.")
        cmd = input(">> ")
        if isValidCMD(cmd):
            runCMD(cmd)

def main():
    while True:
        # Town 
        if room == 1:
            print("\nYou are at the centre of town, Auderban Square.".upper())
            print("\nYou look at the signpost and see 4 signs.")
            print("\t- North - Twinleaf Forest")
            print("\t- South - Store of Celestia")
            print("\t- East - Deskemon Training Ground")
            print("\t- West - Auderban's Deskemon centre")
        # Lab
        elif room == 2:
            print("You are at Auderban's Deskemon Centre")
            AndrewConv()
            print("\nYou see the exit at the door.")
            print("\t- East - Auderban Square")

        cmd = input(">> ")
        if isValidCMD(cmd):
            runCMD(cmd)
main()

Output:

But room keeps its value, 1.

Please give some advice for the future so I won't make the same mistake twice.

Was it helpful?

Solution

Replace west() function with this:

def west():
    global room
    ...

OTHER TIPS

Global variables are widely considered bad programming practice because it is extremely difficult to determine where and when they might be modified in a large program. They also make thread-safe and reentrant code almost impossible to write.

A simple approach would be to have each function accept the room as a parameter and return the “new room.” You can then always update the room in your main function every time you invoke a command.

You will probably end up keeping track of more than the room, though. Consider using a mutable data structure like a dictionary or a class to store the game state, and then passing it into your command functions. That way, it is just as simple to keep up with many state variables as one, and you still do not need global variables.

def main():
    state = {'room': 1}
    while True:
        [...]
        if isValidCMD(cmd, state):
            runCMD(cmd, state)

def west(state):
    thisroom = state['room']
    if thisroom == 1:
        print("You head on over to the lab, to get some advice from Professor Andrew.")
        state.update(room=2)
    elif thisroom == 7:
        print("You head back to Auderban Square feeling primed for battle.")
    else:
        print("You cannot go west.")
        cmd = input(">> ")
        if isValidCMD(cmd):
            runCMD(cmd)

There are some additional issues with this code. For example, you duplicate the command prompt code in each command prompt, which is brittle and error prone, and unnecessary since you will be returning to main() anyway.

Edited: Here is a minimal, runnable example:

def main():
    state = {'room': 1}
    for i in range(20):
        oldroom = state['room']
        nextroom(state)
        print("Went from room {} to room {}.".format(oldroom, state['room']))

def nextroom(state):
    state['room'] += 2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top