你的想法有几个优点和缺点:
如果您想要经典的“roguelike-ish”动作(在带有某种图块的 2d 网格中),您将在图形地牢表示方面遇到很多问题(实际上您现在正在使用图形)。让我们看看这个地牢:
ROOM1 > ROOM2 > NORTH
ROOM2 > ROOM3 > NORTH
ROOM3 > ROOM1 > NORTH
你会得到一个房间戒指。这不好,但你可以做类似的事情:
ROOM1 > ROOM2 > NORTH
ROOM1 > ROOM2 > SOUTH
这真的很令人困惑,因为您可以朝不同的方向移动并进入一个房间。为了通过设计防止这些情况,您可以将您的地牢表示为一个公平的 2d 网格,如下所示:
rooms_mask = [
[0,1,0,0,1],
[1,1,1,0,1],
[0,0,1,1,1],
[1,1,1,0,0],
[1,0,0,0,0]
]
您的操作只会从当前位置的 x 或 y 坐标添加或减去 1。这是简单的示例代码:
class Room(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
if self.y < 3:
return 'It is a dark and gloomy room: ({}, {})'.format(self.x, self.y)
else:
return 'It is a light and shining room: ({}, {})'.format(self.x, self.y)
rooms_mask = [
[0,1,0,0,1],
[1,1,1,0,1],
[0,0,1,1,1],
[1,1,1,0,0],
[1,0,0,0,0]
]
rooms = [[Room(j, i) for j, _ in enumerate(rm)] for i, rm in enumerate(rooms_mask)]
x = 2
y = 2
while True:
action = input()
if action == 'q':
break
elif action == 'n':
if y > 0 and rooms_mask[y-1][x] == 1:
y -= 1
print(rooms[y][x])
elif action == 's':
if y < len(rooms_mask) - 1 and rooms_mask[y+1][x] == 1:
y += 1
print(rooms[y][x])
elif action == 'e':
if x < len(rooms[0]) - 1 and rooms_mask[y][x+1] == 1:
x += 1
print(rooms[y][x])
elif action == 'w':
if x > 0 and rooms_mask[y][x-1] == 1:
x -= 1
print(rooms[y][x])
但如果你真的想用图形来表示你的地牢,你可以使用这个代码:
from collections import defaultdict
raw_rooms = [
[1,2,'n'],
[2,3,'w'],
[1,4,'s']
]
rooms = defaultdict(list)
for source, target, direction in raw_rooms:
rooms[source].append([target, direction])
current_room = 1
while True:
action = input()
if action == 'q':
break
else:
for target, direction in rooms[current_room]:
if direction == action:
print('I am in room {}'.format(target))
current_room = target
此代码使用defaultdicts 来存储房间图。您也可以使用networkx 来使用真实的图表并使用它们。