使用 json 保存/加载 textRPG
Posted
技术标签:
【中文标题】使用 json 保存/加载 textRPG【英文标题】:save/load for textRPG with json 【发布时间】:2020-09-15 21:45:08 【问题描述】:我正在尝试为我的文本 RPG 创建一个保存加载功能,它将在打开时保存并加载单个加载并在关闭时保存。这个 textRPG 是我的第一个真正的项目。现在我只是想让文件转储到 json。
我使用的代码是这样的
def saveload():
player_Stats =
player.hp,
player.gold,
player.lvl,
player.current_location()
filename = 'save.json'
with open(filename, 'w') as f:
json.dump(player_Stats)
这是整个播放器脚本。我计划稍后使用 json.load 将数据加载到保存函数中的各个变量中,iv 只保存了几个玩家统计数据以用于测试目的。任何帮助表示赞赏。
import items
import world
import enemies
import magic
class Player:
def __init__(self):
self.inventory = [items.Dagger(),items.Rock(),items.CrustyBread()]
self.spell_book = [magic.magic_missle(), magic.fire_ball()]
self.x = world.start_tile_location[0]
self.y = world.start_tile_location[1]
self.hp = 100
self.gold = 5
self.victory = False
self.exp = 199
self.player_lvl = 1
self.mana = 100
def is_alive(self):
return self.hp > 0
def move(self,dx,dy):
self.x += dx
self.y += dy
def move_north(self):
self.move(dx=0, dy=-1)
def move_south(self):
self.move(dx=0, dy=1)
def move_east(self):
self.move(dx=1, dy=0)
def move_west(self):
self.move(dx=-1, dy=0)
def player_stats(self):
print("Level: ".format(self.player_lvl), "HP: ".format(self.hp),"Mana:".format(self.mana),"Gold: ".format(self.gold), "EXP: ".format(self.exp))
def print_spellbook(self):
print('\n Spell Book')
for magic in self.spell_book:
print('*'+str(magic))
def print_inventory(self):
print("\n Inventory:")
for item in self.inventory:
print('* ' + str(item))
print("Gold: ".format(self.gold))
'''
def check_lvl_up(self,enemy):
new_exp = self.exp + enemy.exp
levels = [0,200,450,1012]
if True:
current_level = sum(1 for x in levels if x<= total_exp)
self.player_lvl = current_level
'''
def most_powerful_weapon(self):
max_damage = 0
best_weapon = None
for item in self.inventory:
try:
if item.damage > max_damage:
best_weapon = item
max_damage = item.damage
if self.player_lvl >= 2:
item.damage = item.damage + 1
except AttributeError:
pass
return best_weapon
def attack(self):
spell = [magic_spell for magic_spell in self.spell_book if isinstance(magic_spell,magic.Spell)]
if not spell:
print("You have no spells to cast!")
user_input = input('What do you want to attack with? Melee or Magic: ')
if user_input == str('magic'):
for i, magic_spell in enumerate(spell, 1):
print("Choose a spell to cast: ")
print(". ".format(i,magic_spell))
valid =False
while not valid:
choice = input("")
try:
if self.mana == 0:
print("You dont have enough mana")
else:
room = world.tile_at(self.x,self.y)
enemy = room.enemy
print("You use against !".format(magic_spell,enemy.name))
enemy.hp -= magic_spell.damage
self.mana = self.mana - magic_spell.mana
if not enemy.is_alive():
print("You killed !".format(enemy.name))
else:
print(" HP is .".format(enemy.name,enemy.hp))
except(ValueError,IndexError):
print("Invalid choice, try again")
break
elif user_input == str('melee'):
best_weapon = self.most_powerful_weapon()
room = world.tile_at(self.x,self.y)
enemy = room.enemy
print("You use against !".format(best_weapon.name,enemy.name))
enemy.hp -= best_weapon.damage
if not enemy.is_alive():
print("You killed !".format(enemy.name))
else:
print(" HP is .".format(enemy.name,enemy.hp))
def heal(self):
consumables = [item for item in self.inventory if isinstance(item,items.Consumables)]
if not consumables:
print("You dont have any items to heal you!")
return
for i, item in enumerate(consumables, 1):
print("Choose an item to use to heal: ")
print(". ".format(i, item))
valid = False
while not valid:
choice = input("")
try:
to_eat = consumables[int(choice)-1]
self.hp = min(100,self.hp + to_eat.healing_value)
self.inventory.remove(to_eat)
print("Current HP: ".format(self.hp))
valid = True
except (ValueError,IndexError):
print("Invalid choice, try again")
def trade(self):
room = world.tile_at(self.x,self.y)
room.check_if_trade(self)
def current_locaton(self):
room = world.tile_at(self.x,self.y)
self.current_location = room
def saveload(self):
player_Stats =
self.player.hp,
self.player.gold,
self.player.lvl,
self.player.current_location(),
filename = 'save.json'
with open(filename, 'w') as f:
json.dump(player_Stats)
【问题讨论】:
【参考方案1】:编辑 19:42:15 22-09-2020
您没有指向要保存它的文件/流。
with open(filename, 'w') as f:
json.dump(player_Stats, f)
或
with open(filename, 'w') as f:
f.write(json.dumps(player_Stats))
如果有帮助,请告诉我们。
【讨论】:
在底部我有一个名为 LoadSave() 的函数,现在我只是试图让它保存一些参数,看看它是否会生成 json。以上是关于使用 json 保存/加载 textRPG的主要内容,如果未能解决你的问题,请参考以下文章
如何在线保存/加载数据(使用 AJAX 和 JSON 存储数据)和离线(本地)
在顶部/使用 Spark 保存和加载 JSON 和 scala 的对象
如何将输入/选择值从网站保存到 XML/JSON 文件并使用 JavaScript 自动加载再次填充它们
如何在 Flutter 中使用 json 或其他内容保存我当前的状态