【问题标题】:pickle.dump(stats, items, outfile) TypeError: an integer is required (got type _io.BufferedWriter)pickle.dump(stats, items, outfile) TypeError: an integer is required (got type _io.BufferedWriter)
【发布时间】:2020-11-13 18:55:18
【问题描述】:
#!Python 3.8.3
#Dungeon Game Similar to dungeons and dragons, turn fight game

import pickle, time, sys, random
filename = "Save_File"

load = input("Would you like to load a save? y/n")
if load == "y":
    try:
        infile = open(filename, "rb")
        pickle.load(infile)
        infile.close()
    except:
        print("It seems you typed your save name wrong. Resart the program to try again")
        pass
        
NameInput = input("Enter Your Characters Name Here To Start Your Journey:")
ClassType = input("What Class Do You Choose? Mage, Healer, Barbarian, Archer, Warrior?")


stats = {
    "Health" : "100",
    "Gold" : "50",
    "Name" : NameInput,
    "ClassType" : ClassType,
    "melee" : "10",
    "defence" : "0"
    }
items = {
    "Healing Potion" : "0",
    "Amber" : "0",
    "Amethyst" : "0",
    "Arrows" : "0",
    "Azurite" : "0",
    "Backpack" : "0"
    }

outfile = open(filename, "wb")
pickle.dump(stats, items, outfile)
outfile.close()

所以我有这个问题有人知道如何解决吗?错误在标题中。我制作了一款回合制游戏,我将使用保存功能来保存您的进度。有人可以解释一下这个错误以及如何解决它。

【问题讨论】:

  • 顺便说一句,我现在只是保存以检查保存功能是否有效
  • 你能告诉我们你的确切错误是什么吗?

标签: python python-3.8


【解决方案1】:

我在另一个问题中回答了这个问题。 Store Python function in JSON

Python 有一个内置的模块名称 marshal 可以处理这个问题。

import marshal, ujson as json

def multiplier(a, b):
    return a * b

x = {
  "x":5,
  "y":4,
  "func" : marshal.dumps(multiplier.func_code)
}

x = json.dumps(x)
print(x)

然后把它拿回来......

x = json.loads(x)
x = marshal.loads(x['func'])
# maybe save the function name in dict
func = types.FunctionType(x, globals(), "some_func_name") 

print(func(2,4))

【讨论】:

    猜你喜欢
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 2016-11-17
    • 2022-01-08
    • 2018-06-24
    相关资源
    最近更新 更多