在学校的一个项目中,我们需要编写一个使用类和图形用户界面的程序。因为我去年完成了一个类似的非面向对象版本,所以我正在使用 tkinter 重新创建一个基于文本的 RPG 游戏。
我的问题是如何设计房间和地牢,以及如何将它们组合在一起。我之前的版本过于简单,遵循如下方式:
if currentRoom == 1:
print('<Room description>')
print('1] <Option one>')
print('2] <Option two>')
etc...
userinput = int(input('>>_:'))
if userinput = 1:
# Do stuff
玩家在世界中的位置由一个数字表示,该数字对应于旧 D&D 地图上的房间编号。选项是特定于房间的,并且针对每个房间重新编写,程序不断循环,直到被告知停止(当“while running”为 false 时)。
命令输入由一个 App 类处理;当用户按回车键时,它检查 tkinter 输入小部件的内容并对其进行过滤,查找预定义的短语(go、talk、equip 等)。输出被写入临时文件,然后通过标签小部件从中读取并显示。
我想知道当房间是一个对象时你将如何做到这一点,以及你将如何知道哪些房间彼此相连,以及到达那里必须旅行的方向(例如:“向北走”)。
2、解决方案
要使用面向对象的方法设计 RPG 游戏中的房间和地牢,可以按照以下步骤操作:
- 创建一个 Room 类,该类包含房间的描述、可用的选项以及通往其他房间的方向。
- 创建一个 Dungeon 类,该类包含所有房间的列表。
- 创建一个 Player 类,该类包含玩家当前所在房间的位置。
- 在 App 类的 init 方法中,创建一个 Dungeon 类并创建一个 Player 类。
- 在 App 类的 handle_command 方法中,检查用户输入的命令。如果命令是“go”,则获取用户输入的方向并查找该方向对应的房间。如果找到,则将玩家当前所在房间的位置更新为新房间。
- 在 App 类的 update_ui 方法中,从玩家当前所在房间获取描述和选项,并将它们显示在图形用户界面上。
以下是代码示例:
class Room:
def __init__(self, description, options, directions):
self.description = description
self.options = options
self.directions = directions
class Dungeon:
def __init__(self):
self.rooms = []
def add_room(self, room):
self.rooms.append(room)
class Player:
def __init__(self, current_room):
self.current_room = current_room
class App:
def __init__(self):
self.dungeon = Dungeon()
self.player = Player(self.dungeon.rooms[0])
def handle_command(self, command):
if command.startswith("go"):
direction = command.split()[1]
new_room = self.player.current_room.directions.get(direction)
if new_room:
self.player.current_room = new_room
def update_ui(self):
description = self.player.current_room.description
options = self.player.current_room.options
# 更新图形用户界面上的文本和按钮
# 创建房间
room1 = Room("You are in a dark room.", ["Look around", "Go north"], {"north": room2})
room2 = Room("You are in a large room with a door to the east.", ["Open the door", "Go east"], {"east": room3})
room3 = Room("You are in a small room with a chest.", ["Open the chest", "Go south"], {"south": room2})
# 创建地牢
dungeon = Dungeon()
dungeon.add_room(room1)
dungeon.add_room(room2)
dungeon.add_room(room3)
# 创建玩家
player = Player(room1)
# 创建应用程序
app = App()
# 运行应用程序
app.mainloop()
通过使用面向对象的方法,我们可以将房间、地牢和玩家建模为对象,并使用对象属性和方法来处理游戏逻辑。这使得代码更易于维护和扩展。