【发布时间】:2018-02-25 01:45:47
【问题描述】:
所以我想做的事情有点难以在标题中描述。
这是我想做的: 在下面的代码中,我想要一些可以在 Room 类(例如 Search、Loot)和 Player 类(例如 quit、heal)上调用的通用方法。我希望发生这种情况的方式是玩家在输入中输入他们想要做的事情,python 将在 dict 中查找该选择,该选择与方法相匹配。
我已经通过房间的出口成功地做到了这一点。我可能可以通过创建一个子类并在其中列出方法来做到这一点,但我真的不想这样做,因为这看起来很混乱。
当我运行下面的代码时,它只是自动退出。如果我在第一个字典被注释掉的情况下运行它,我会收到一条错误消息,指出 __init__() 缺少必需的位置参数。
from textwrap import dedent
from sys import exit
class Player(object):
actions = {
'QUIT': quit
}
def __init__(self, actions):
self.actions = actions
# Want actions to be a list of actions like in the Room Class
#
def quit(self):
# Quits the game
exit(0)
class Room(object):
# Description is just a basic room description. No items needed to be added here.
def __init__(self, desc, exits, exitdesc):
self.desc = desc
self.exits = exits
self.exitdesc = exitdesc
# Also want list of general actions for a room here.
def enterroom(self):
#First print the description of the room
print(self.desc)
#Then print the list of exits.
if len(self.exits) > 1:
print(f"You see the following exits:")
for exd in self.exitdesc:
print(self.exitdesc[exd])
elif len(self.exits) == 1:
print(f"There is one exit:")
for exd in self.exitdesc:
print(self.exitdesc[exd])
else:
print("There are no exits.")
# Then allow the player to make a choice.
self.roomactivity()
# Here's what I mean about calling the methods via a dictionary
def roomactivity(self):
while True:
print("What do you want to do?")
choice = input("> ").upper()
if choice in self.exits:
self.exits[choice].enterroom()
#And here's where I want to call actions other than directions.
elif choice in player.actions:
player.actions[choice]
else:
print("I don't understand.")
class VoidRoom(Room):
def __init__(self):
super().__init__(
desc = "ONLY VOID.",
exits = {},
exitdesc = {})
class TestRoom(Room):
def __init__(self):
super().__init__(
desc = dedent("""
This room is only a test room.
It has pure white walls and a pure white floor.
Nothing is in it and you can hear faint echoes
of some mad sounds."""),
exitdesc = {
'NORTH': 'To the NORTH is a black door.',
'SOUTH': 'To the SOUTH is a high window.',
'EAST': 'To the EAST is a red door.',
'WEST': 'To the WEST is a blue door.'},
exits = {
'NORTH': void_room,
'SOUTH': void_room,
'EAST': void_room,
'WEST': void_room})
void_room = VoidRoom()
test_room = TestRoom()
player = Player()
test_room.enterroom()
我希望我已经清楚地解释了这个问题。还在学习这门语言,我现在可能已经吃不消了。
编辑:下面的新代码:
我已经改变了一些东西,我将播放器命令和内容放在一个单独的 py 文件中,这样我就可以扩展播放器范围而不会弄乱 rooms.py 文件。
from textwrap import dedent
from sys import exit
from player import *
from enemies import *
# This is the base class for a room.
class Room(object):
# Description is just a basic room description. No items needed to be added here.
def __init__(self, desc, exits, exitdesc, inventory):
self.desc = desc
self.exits = exits
self.exitdesc = exitdesc
self.inventory = inventory
def enterroom(self):
#First print the description of the room
Player.currentroom = self
print(self.desc)
for item in self.inventory:
print(self.inventory[item].lootdesc)
#Then print the list of exits.
if len(self.exits) > 1:
print(f"You see the following exits:")
for exd in self.exitdesc:
print(exd)
elif len(self.exits) == 1:
print(f"There is one exit:")
for exd in self.exitdesc:
print(exd)
else:
print("There are no exits.")
# Then allow the player to make a choice.
self.roomactivity()
def roomactivity(self):
while True:
print("What do you want to do?")
choice = input("> ").upper()
if choice in self.exits:
self.exits[choice]().enterroom()
elif choice in Player.actions:
Player.actions[choice]()
else:
print("I don't understand.")
#Player.actions[choice]()
class Room3(Room):
def __init__(self):
super().__init__(
desc = dedent("""
You are in a large, dimly lit room.
Torches sit in empty alcoves, giving off an eerie red glow.
You hear scratching and squeaking from behind the walls."""),
exits = {
'NORTHEAST': StartRoom
},
exitdesc = [
'A sturdy looking door leads to the NORTHEAST'
],
inventory = {})
class Room1(Room):
def __init__(self):
super().__init__(
desc = dedent("""
You are in a medium sized, dimly lit room.
Busts of dead men you don't know sit atop web-strewn pedestals."""),
exits = {
'EAST': StartRoom
},
exitdesc = [
'An arch leading into a dimly lit hall lies to the EAST.'
],
inventory = {'IRON SWORD': iron_sword}
)
class StartRoom(Room):
def __init__(self):
super().__init__(
desc = dedent("""
PLACEHOLDER LINE 49"""),
exits = {
'SOUTHWEST': Room3,
'WEST': Room1
},
exitdesc = [
'An arch leading into a dimly lit room lies to the WEST',
'A sturdy looking door lies to the SOUTHWEST'],
inventory = {}
)
class HelpPage(Room):
def __init__(self):
super().__init__(
desc = dedent("""
All actions will be listed in all caps
When asked for input you may:
QUIT the game
Check your INVENTORY
Check your player STATUS
SEARCH the room
EXAMINE an object or point of interest
USE an item from your inventory or the room
ATTACK a creature
GET an item from the room
or pick a direction (listed in caps)"""),
exits = {},
exitdesc = [
'Press ENTER to return to the Main Menu'],
inventory = []
)
def enterroom(self):
print(self.desc)
for exd in self.exitdesc:
print(exd)
self.roomactivity()
def roomactivity(self):
input()
MainMenu.enterroom()
help_page = HelpPage()
# Main menu, lil bit different from a regular room
class MainMenu(Room):
def __init__(self):
super().__init__(
desc = dedent("""
THE DARK DUNGEON OF THE VAMPIRE KNIGHT
A game by crashonthebeat"""),
exits = {
'START': StartRoom,
'HELP': HelpPage
},
exitdesc = [
'Press START to Start the Game',
'Or go to the HELP Menu'],
inventory = []
)
def enterroom(self):
print(self.desc)
for exd in self.exitdesc:
print(exd)
self.roomactivity()
def roomactivity(self):
while True:
choice = input("Choose an Option: ")
if choice in self.exits:
self.exits[choice]().enterroom()
else:
print("I don't understand")
以及 player.py 中的相关代码
from items import *
from rooms import *
class Player(object):
@property
def actions(self):
actions_map = {
'QUIT': 'quit_',
'STATUS': 'status',
'INVENTORY': 'printinventory',
'EXAMINE': 'examine',
'USE': 'useitem',
'SEARCH': 'searchroom',
'GET': 'getitem',
'CURRENTROOM': 'getcurrentroom'
}
return actions_map
【问题讨论】:
-
我认为错误在于您正在制作类级别的变量操作。尝试制作 like` def init (self,input):` 然后在那个
self.actions = input这可能会起作用。