我正在创建一个基于文本的游戏,当我尝试添加一把刀传递到森林时遇到问题。我的想法是,玩家需要使用'C'
选项将Knife
添加到库存中。并使用Knife
传递到'B'
选项中的森林。请问有什么解决办法吗?
a1 = input('What you want to do? \nCheck some rock around you(A) \nGo to the Forest(B) \nSee around of the beach in the island(C) \n\n')
obj = []
def addknife():
obj.append('Knife')
if a1.capitalize() == 'A':
print()
print('It is nothing else than a rock.')
elif a1.capitalize() == 'C':
print()
print('Walking for the beach, you encountered a Knife.')
addknife()
print(obj)
elif a1.capitalize() == 'B':
if 'Knife' in obj:
print('You can go to the forest.')
else:
print('The plants do not allow you to pass.')
最佳答案
一个简单的方法是创建一个数据结构来保存所有游戏位置,然后维护一个玩家位置,这是该结构的某种索引。我试图让这个答案非常简单,所以我省略了更复杂的细节,这些细节也许可以提高效率。
也许只是从位置列表以及该列表中的整数索引开始:
# index 0 index 1 index 2 index 3
locations = [ "Rocky End of The Beach", "On The Beach", "Edge of The Forest", "In The Forest" ]
player_location = 0
所以一开始,播放器可以显示locations[ player_location ]
,这将是“海滩的岩石尽头”。
类似于locations
,也许可能有一个位于每个位置的对象列表:
objects = [ [ ], [ "Knife" ], [ "Coconut", "Banana" ], [ ] ]
显然我们有一个列表列表,所以如果player_location
是2
,可用对象为 [ "Coconuts", "Bananas" ]
因此,为了向玩家显示位置的描述,它现在是位置和对象的组合:
def showLocation( player_location ):
global locations, objects
# show the location description
print( locations[ player_location ], end='. ' )
# show the location's objects
if ( len( objects[ player_location ] ) > 0 ):
print( "There is: " )
for item in objects[ player_location ]:
print( item, end=", " )
print("") # end-of-line
因此,在“海滩”位置( player_location
是 1
),此位置文本将变为:
On The Beach. There is: Knife
另一个导出列表可以控制玩家从当前位置移动的方式,另一个列表可以指示需要哪个“ key ”。因此,如果玩家位于位置 0
,他们可以移至1
=海滩,2
=森林边缘。如果玩家“在海滩上”,他们只能移回索引 = 0(岩石末端)等。
exits = [ [ 1, 2 ], [ 0 ], [ 0, 2 ], [ 1 ] ] # numbers of joined locations
keys = [ [ ], [ ], [ ], [ "Knife" ] ] # objects needed to enter
keys
指示玩家需要拥有哪些元素才能进入该位置。因此对于前 3 个位置,不需要任何对象。但要进入森林(只能从“森林边缘”进入),玩家需要拥有“刀”。
像这样的简单列表系统可以定义一组有关您的位置的规则。然后相同的代码可以循环询问玩家命令。该命令将与位置进行比较。因此,例如,“获取香蕉”仅在 objects
时才有效。列表在该特定 player_location
处有一个“香蕉”项目索引。
从一组简单的规则数据开始,甚至可能只是位置名称,然后不断向其中添加越来越多的功能。
编写一些伪代码:
# Do Forever:
# Show player the location description
# Get input from player
# if a movement command
# if player has key-object to move, or no object needed
# change the `player_location` index
# else
# Show "You need object XXX" to player
# if a get/drop command and item valid
# change the player & location objects list
关于python-3.x - 如何在列表中追加项目以供稍后在 If 语句中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59956161/