-3

所以我目前正在尝试编写一个简单的基于文本的游戏,并且我有一个基于文件的保存系统。我最近添加了交叉文件窃取(不要问),我测试了它。几次保存后,我注意到系统设计为只允许在从保存中加载被盗内容之间进行一次盗窃,这已停止工作。我查看了我的保存文件并看到了 这个:

又过了一会儿,这发生在另一个 保存文件上:

现在出现了代码删除保存文件内容的问题!谁能解释为什么要添加额外的字符?询问您是否需要更多代码,这只是 save 和 rob 功能。

代码:

 import os
 import time
 import random as r

def savefile(data, slot):
        if(len(data)>6):
            savef=open("savefile"+str(slot)+".txt", 'w')
            print(data[6])
            data[6][0] = data[6][0].replace("'", '')
            data[6][2] = data[6][2].replace("'", '')
            print(data[6])
            if(len(data[5])==2):
                data[5].append(0)
            savef.write(str(data[0])+"\n"+str(data[1])+"\n"+str(data[2]).replace(" ", "")+"\n"+str(data[3])+"\n"+str(data[4])+"\n"+str(data[5])+"\n"+str(data[6]))
            savef.close()
        else:
            print("the save is outdated")


 def localrob(data):
        #UNFINISHED
        print("Choose your target(enter their ID)")
        savenum=1
        data[1]=int(data[1])
        while True:
            try:
                save=open("savefile"+str(savenum)+".txt", "r")
                name=save.read().split()[0]
                print("["+str(savenum)+"] "+name)
                savenum=savenum+1
                save.close()
            except:
                break
        try:
            target=int(input())
        except:
            print("wow thats not a number idiot")
            return data
        if(target==slotr):
            print("You cant rob yourself silly!")
            return data
        else:
            targetfile=open("savefile"+str(target)+".txt")
            targetdata=targetfile.read().split()
            if(targetdata[6][0]=='False'):
                pass
            else:
                print("This mans already been stolen from! Give em a rest!")
                targetfile.close()
                return data
            targetdata[1]=int(targetdata[1])
            bounty=r.randint(int(targetdata[1]/5), int(targetdata[1]/2))
            spend=r.randint(int(targetdata[1]/15), int(targetdata[1]/5))
            ques=input(targetdata[0]+" has " + str(bounty) + " coins up for grabs, but if you get lucky, you might be able to snag more. It will cost "+str(spend)+" coins. Do you go through? (y/n)")
            if ques.lower()=='y':
                extraspent=int(input("How much extra do you want to spend?"))
                if(int(data[1])-extraspent-spend<0):
                    print("lol ur too poor to rob them")
                    return data
                chances=int(300*(spend+extraspent)/bounty)-int(data[5][2])
                if(chances>100):
                    chances=100
                chances=chances-10
                ohmy=r.randint(0, 100)
                if(data[5][1]):
                    last=input("Your chances are "+str(chances)+"%. Are you sure you want to attack? (y/n)")
                    if(last=='y'):
                        pass
                    else:
                        print("Ok.")
                        return rob(data)
                print("You invested %s coins into this, it better go well." % (str(extraspent+spend)))
                print("Stealing all of "+targetdata[0]+" possesions...")
                time.sleep(r.randint(1, 10))
                print(targetdata[6])
                if ohmy==1:
                    print("Even though you didnt think so, you were able to get BASICACLLY EVERYTHING LMAO. You earn %s coins(after paying off your investment" % (str(targetdata[1])))
                    data[1]=int(data[1])+targetdata[1]
                    targetdata[6]=[True, data[0], targetdata[1]]
                    targetdata[1]=0
                elif ohmy<5:
                    print("You were able to steal twice what you think what you could.")
                    data[1]=int(data[1])+bounty*2-spend-extraspent
                    targetdata[1]=targetdata[1]-bounty*2
                    targetdata[6]=[True, data[0], bounty*2]
                elif ohmy<chances:
                    print("You successfully stole %s from this poor man, getting a net profit of %s coins." % (str(bounty), str(bounty-extraspent-spend)))
                    data[1]=int(data[1])+bounty-extraspent-spend
                    targetdata[1]=targetdata[1]-bounty
                    targetdata[6]=[True, data[0], bounty]
                elif ohmy<90:
                    print("Oof, you failed and lost your investment.")
                    data[1]=int(data[1])-extraspent-spend
                    targetdata[6]=[False, data[0], 0]
                else:
                    print("WOW, you got caught! You paid twice your investment.")
                    data[1]=data[1]-2*extraspent-2*spend
                    targetdata[6]=[False, data[0], 0]
                savefile(targetdata, target)
                targetfile.close()
                return data
        return data
        #UNFINISHED
4

1 回答 1

1

我认为问题在于您如何将布尔值和列表转换为字符串。 str(True)将返回'True',但str([True])返回'[True]'。如果你str像这样调用两次str([str(True)]),输出将是"['True']". 该列表从不包含 bool True,仅包含 string 'True',写为str(True),并将其视为任何其他字符串(例如str(['Hello'])return "['Hello']")。

对于整数和其他非字符串数据类型也是如此。 str([str(0)]变成"['0']".

最有可能的问题是你在使用str([str(True)])and时不一致str([True]),导致有时"['True']"有时'[True]'

小心混淆字符串和布尔值。
savefile(targetdata, target)可能会给你一个AttributeError. targetdata[6][0] 的值是一个布尔值,但savefile首先调用.replace()它,这是一个字符串方法。

您还可以尝试使用 python 的内置模块 pickle 序列化数据,而不是将其写入文本文件,这样您就可以直接将变量保存到文件中。您使用 将数据写入文件并使用pickle.dump从中读取数据pickle.load,如下所示:

如果要将列表保存data到文件中saved_data.pkl

import pickle

with open("saved_data.pkl", "wb") as file:
# note the "b" in the second argument, it means you are opening the file to
# write to it in a binary format, not with text
    pickle.dump(data, file)

要从文件中加载数据:

with open("saved_data.pkl", "rb") as file:
    data = pickle.load(file)
于 2021-01-11T23:45:20.853 回答