Python text game not calling the correct number
I am writing a text game and I want to link each room to four other rooms - north, south, east and west. Now I start from the north. The user should be able to enter "walk north" and the north room should be called up.
I used three files - one where I will write the main story, one to bring up the corresponding room in the story, and the other to navigate to avoid cross-imports.
rooms.py:
import actions
class FirstRoom(object):
room_name = 'FIRST ROOM'
north = 'north_room'
def __init__(self):
pass
def start(self):
print self.room_name
while True:
next = raw_input('> ')
actions.walk(next, self.north)
actions.command(next)
class North(object):
room_name = "NORTH ROOM"
def __init__(self):
pass
def start(self):
print self.room_name
actions.py:
import navigation
def walk(next, go_north):
"""Tests for 'walk' command and calls the appropriate room"""
if next == 'walk north':
navigation.rooms(go_north)
else:
pass
navigation.py:
import rooms
first_room = rooms.FirstRoom()
north_room = rooms.North()
def rooms(room):
rooms = {
'first_room': first_room.start(),
'north_room': north_room.start(),
}
rooms[room]
When I run first_room.start () it should print "FIRST ROOM" which it does. Then I type "walk north" and I expect it to print "NORTH ROOM" but instead print "FIRST ROOM" again.
I can't figure out all my life why this doesn't work the way I expect it to be, as if it were calling first_room again instead of north_room. Can anyone understand what I am doing wrong?
source to share
I am guessing the problem is due to how the dictionary is defined rooms
. When you do -
rooms = {
'first_room': first_room.start(),
'north_room': north_room.start(),
}
rooms[room]
Functions are called when you define the dictionary itself, not when you access values ββfrom it (which is why both functions are called), you want to store the function objects (without calling them) as values ββand then call them like - rooms[room]()
. Example -
def rooms(room):
rooms = {
'first_room': first_room.start,
'north_room': north_room.start,
}
rooms[room]()
source to share