【问题标题】:Python- text based game not calling the correct room基于 Python 文本的游戏没有调用正确的房间
【发布时间】:2015-10-31 00:17:54
【问题描述】:

我正在编写一个基于文本的游戏,我想将每个房间链接到其他四个房间——北、南、东和西。我现在从北方开始。用户应该能够输入“向北走”并且应该调用北房间。

我使用了三个文件 - 一个用于编写主要故事,一个用于调用故事中的相应房间,另一个用于导航以避免相互导入。

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

导航.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]

当我运行 first_room.start() 时,它应该打印它所做的 'FIRST ROOM'。然后我输入“向北走”,我希望它会打印“NORTH ROOM”,但它会再次打印“FIRST ROOM”。

我一生都想不通为什么它不能按我期望的方式工作,就好像它再次调用 first_room 而不是 north_room。谁能弄清楚我做错了什么?

【问题讨论】:

  • rooms[room] 是一个声明,如果你不将它存储在某个地方,它将什么也做不了。

标签: python class oop namespaces python-import


【解决方案1】:

我的猜测是问题的出现是因为字典 rooms 的定义方式。当你这样做 -

rooms = {
    'first_room': first_room.start(),
    'north_room': north_room.start(),
    }
rooms[room]

当您定义字典本身时调用函数,而不是当您从它访问值时(因此两个函数都被调用),您希望将函数对象(不调用它们)存储为值,然后将它们调用为 - rooms[room]() 。示例 -

def rooms(room):
    rooms = {
        'first_room': first_room.start,
        'north_room': north_room.start,
        }
    rooms[room]()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多