最近我问了类似的问题,但是这个问题演变成其他问题。我正在制作文字冒险游戏,并设定了玩家的位置。您从位置“ b1”开始,然后可以选择通过键入命令“ north”或“ south”来更改它。但是,更改位置后,您会看到对区域“ b1”和您刚刚移动到的区域的描述。我需要它只是在您移动时停止显示旧位置,并且如果您返回也可以重新查看说明。这是我的代码:
alive = 1
location = 'b1'
action = 'no_action_yet'
while alive:
if location == 'b1':
print("b1 location description")
print("There is a door to the north and south, as well as paintings on the walls.")
print('idleActions')
if action == 'north':
location = 'ha1'
if action == 'south':
location = 'a1'
if action == 'west':
print("west wall description")
if action == 'east':
print("east wall description")
if action == 'inspect':
print("What would you like to inspect?")
if action == 'inspect' + ' ' + 'paintings':
desc = False
print("painting descriptions")
print("One of the paintings is just an empty frame.")
action = "no action"
if location == 'ha1':
print("ha1 stuff")
print("more ha1 stuff")
action = "no action"
if location == "a1":
print("a1 stuff")
print("more a1 stuff")
print("idleActions")
if action == 'north':
location = 'b1'
if action == 'south':
location = 'stage'
if action == 'west':
location = 'office'
if action == 'east':
print("east a1 wall stuff")
print("more east a1 wall stuff")
action = input("What would you like to do? ")
此解决方案的目的是显示您在数据结构和设计选择方面应该做的事情。
使用类将数据描述为对象,了解如何使用standard library collections来保存地图。使用pycharm调试器设置断点并测试代码(调试器中有一个名为“ Evalute expression”的图标,您必须学习如何使用它)。
我加入了Enum,因为它是完成任务的正确工具(只需学习如何使用enum.name,而enum.value不必为其余的事情担心太多)。
此代码有效,您可以对其进行更改/扩展。 (它对“描述”和“地图”使用2个字典,键为坐标“ a1”,“ b1”等。地图将带有边的列表索引到其他节点。)
from enum import Enum
your_map = """
Example map:
1 - 2 - 3
a a1--a2--a3
| |
b b1 b3
"""
print(your_map)
class Wall:
pass
class Location():
pass
class Edge:
def __init__(self, destination, direction):
self.destination = destination
self.direction = direction
class Action(Enum):
North = 1
South = 2
West = 3
East = 4
Inspect = 5
Exit = 6
Map = dict()
Map["a1"] = [Edge("a2", Action.East), Edge("b1", Action.South)]
Map["a2"] = [Edge("a1", Action.West), Edge("a3", Action.East)]
Map["a3"] = [Edge("a2", Action.West), Edge("b3", Action.South)]
Map["b1"] = [Edge("a1", Action.North)]
Map["b3"] = [Edge("a3", Action.North)]
Description = dict()
Description[("a1", Action.West)] = "West wall description."
Description[("a1", Action.North)] = "North wall description."
Description["b1"] = "b1 location description.\n " \
"There is a door to the north and south, as well as paintings on the walls."
alive = True
start_location = "b1"
def act(location):
tmp_action = input("What would you like to do? ")
if tmp_action in Action.__members__.keys():
action = Action[tmp_action]
else:
print("Illegal action.")
return
if action is Action.Inspect:
print(Description[location])
return
if action is Action.Exit:
exit(0)
direction = action
for edge in Map[location]:
if edge.direction is direction:
location = edge.destination
return location
while alive:
print("Current location:", start_location)
start_location = act(start_location)