生成可逆向工程的代码来保存游戏,python 3



所以我正在用Python制作一个基于文本的小游戏,我决定使用一个保存系统,我想使用旧的"插入代码"技巧。代码需要跟踪玩家库存(以及其他东西,但库存是我遇到麻烦的地方(。

所以我对此的思考过程是将游戏中的每个项目和事件与代码联系起来。例如,库存中的剑将被存储为"123"或类似的独特内容。

因此,对于将生成用于保存游戏的代码,假设您的库存中有一把剑和一面盾牌,并且您在军械库中。

位置(军械库(= ABC

剑 = 123

盾牌 = 456

当播放器输入命令以生成代码时,我希望输出如下:

ABC.123.456

我认为在代码中的项目之间放置句点可以在解码代码时更容易区分一个项目和另一个项目。

然后,当玩家重新启动游戏并输入他们的代码时,我希望将abc.123.456转换回您的位置,即军械库,并在您的物品栏中有剑和盾牌。

所以这里有几个问题:

  1. 如何将每个库存项目与其各自的代码相关联?
  2. 如何生成完整代码?
  3. 当播放器重新加载时如何解码?

我对 Python 很陌生,我真的不知道如何开始做这件事......任何帮助将不胜感激,谢谢!

因此,如果我没看错的话,您希望将信息序列化为无法"保存"但可以在程序中输入的字符串;

使用点是不必要的,你可以对你的应用程序进行编程,以便在没有点的情况下读取你的代码......这将为你节省一些长度。

您的游戏需要"保存"的信息越多,您的代码就越长;我建议使用尽可能短的字符串。

根据您要存储在保存代码中的位置、项目等的数量:您可能更喜欢更长或更短的选项:

  • 数字 (0-9(:将允许您保留 10 个名称,每个名称存储 1 个字符。
  • 十六进制(0-9 + a-f 或 0-9 + a-F(:将允许您保留 16 到 22 个名称(如果您使代码区分大小写,则为 22 个(
  • alphanum(0-9 + a-z,或0-9 + a-Z(:将允许您保留36到62个名称(如果区分大小写,则为62(
  • 如果您决定使用标点
  • 符号和标点符号,则可以使用更多选项,此示例不会在那里,如果需要,您需要自己覆盖该部分。

对于此示例,我将坚持使用数字,因为我不会列出超过 10 个项目或位置。

您可以在源代码中将每个清单项和每个位置定义为字典:

你可以像我一样使用单行

的地方
places = {'armory':'0', 'home':'1', 'dungeon':'2'}
# below is the same dictionary but sorted by values for reversing.
rev_places = dict(map(reversed, places.items()))

或者为了提高可读性;使用多行:

items = {
'dagger':'0',
'sword':'1',
'shield':'2',
'helmet':'3',
'magic wand':'4'
}
#Below is the same but sorted by value for reversing.
rev_items = dict(map(reversed, items.items()))

将数字存储为字符串,以便于理解,如果您使用十六进制或 alphanum 选项,也是必需的。

然后还要用字典来管理游戏中的信息,下面只是你应该如何表示你的游戏信息的示例,代码将产生或解析,这部分不应该在你的源代码中,我故意弄乱了项目顺序来测试它。

game_infos = {
'location':'armory',
'items':{
'slot1':'sword',
'slot2':'shield',
'slot3':'dagger',
'slot4':'helmet'
}
}

然后,您可以使用以下函数生成保存代码,该函数会读取您的库存和行踪,如下所示:

def generate_code(game_infos):
''' This serializes the game information dictionary into a save
code. '''
location = places[game_infos['location']] 
inventory = ''
#for every item in the inventory, add a new character to your save code.
for item in game_infos['items']:
inventory += items[game_infos['items'][item]]
return location + inventory # The string!

还有读取功能,它使用反向字典来破译您的保存代码。

def read_code(user_input):
''' This takes the user input and transforms it back to game data. '''
result = dict() # Let's start with an empty dictionary
# now let's make the user input more friendly to our eyes:
location = user_input[0]
items = user_input[1:]
result['location'] = rev_places[location] # just reading out from the table created earlier, we assign a new value to the dictionary location key.
result['items'] = dict() # now make another empty dictionary for the inventory.
# for each letter in the string of items, decode and assign to an inventory slot.
for pos in range(len(items)):
slot = 'slot' + str(pos)
item = rev_items[items[pos]]
result['items'][slot] = item
return result # Returns the decoded string as a new game infos file :-)

我建议您尝试使用此工作示例程序,创建自己的game_infos字典,其中包含库存中的更多项目,添加一些位置等。 您甚至可以在函数中添加更多行/循环,以管理 hp 或游戏所需的其他字段。

希望这有所帮助,并且您没有放弃这个项目!

最新更新