【问题标题】:Linking rooms using dictionaries from a random text file - Adventure game使用随机文本文件中的字典链接房间 - 冒险游戏
【发布时间】:2019-05-14 21:07:30
【问题描述】:

我目前正在创建一个冒险游戏,您可以在其中通过在输入中输入命令(“NORTH”、“SOUTH”...)来穿越地牢的房间。所以我试图使用字典将每个房间链接在一起,这样我就可以使用“北”、“南”等键来移动这些房间。但我似乎无法弄清楚。有什么想法吗?

【问题讨论】:

  • 不清楚你被困在什么地方。每个房间是否都有一本字典,说明它所链接的内容,使用“North”之类的键指向另一个房间的值?
  • 是的,抱歉,每个房间都有一个字典,说明它所链接的内容,以及通往其他房间的出口方向。该文件以“START > DIRECTION > DESTINATION”的格式给出,每个单独的路径(“START > DIRECTION > DESTINATION”)在单独的行上给出
  • 把所有有问题的信息,而不是评论。它们将更具可读性,并且 yoi 可以格式化它们。

标签: python class dictionary


【解决方案1】:

你的想法有几个优点和缺点:

如果您想要经典的“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 来使用真实的图表并使用它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-25
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    相关资源
    最近更新 更多