【问题标题】:Python text game: how to make a save feature?Python文字游戏:如何制作保存功能?
【发布时间】:2013-09-07 12:05:03
【问题描述】:

我正在用 Python 制作一个基于文本的游戏,我已经大致了解了。但我要让游戏深入到这样的地步,完成它需要的时间比坐下来要长。所以我希望能够让游戏在退出时将变量列表(玩家健康、金币、房间位置等)保存到文件中。然后如果玩家想加载文件,他们就去加载菜单,它会加载文件。

我目前使用的是 2.7.5 版的 Python,并且在 Windows 上。

【问题讨论】:

  • 你到底遇到了什么问题?
  • 基本上,我如何添加一个保存功能,该功能将在退出时将变量列表保存到文件中。如果玩家重新打开游戏,他们会转到“加载”部分(即:输入“3”,它会加载他们的游戏存档)。
  • this answer 会有帮助吗?
  • 在头疼之后,我想出了一种将数据写入文本文件的方法,然后当程序打开时,它会打开文件并检查文件中是否有某些数据值。如果这没有多大意义,我会更深入。 :)

标签: python save


【解决方案1】:

我在我的游戏中也使用了类似的东西:

with open("game_data.txt", "w") as f:
    f.write(str(amount_of_gold) + "\n")

现在这将返回一个list()。 然后,你想在里面写点东西。您可以使用 write() 函数执行此操作。注意:不要忘记str() 并在每行之后添加\n。 这是保存数据。 正在阅读:

import os
if os.path.getsize("game_data.txt") > 0:
    with open("game_data.txt", "r") as f:
            data = f.read().splitlines()
            amount_of_gold = int(data[0])

等等... 注意:不要忘记使用int()。您必须使用os.path.getsize(),否则游戏将读取一个空文件(即当玩家第一次启动游戏时),您将获得Index Error

【讨论】:

    【解决方案2】:

    嗯,我用 Python 制作了一个点击游戏,没有使用 pickle 或其他东西。 1. 制作一个关卡开始时变化的关卡变量。

    def level1():
        level = 1
    
    1. 将该变量插入文本文件。
        #this is the level1 command part
        with open ("level.txt", "w") as level_data:
            level_data.write(str(level))
    
    1. 游戏开始时,必须检查文本文件。
    #not the level1 command part
    import os
    
    data_check = os.path.exists("level.txt")
    
    if data_check == True:
        data_load = open("level.txt", "r")
        level = int(data_load.read())
    else:
        level = 0
    

    【讨论】:

      【解决方案3】:
      def cache (filename):
          global c,code
          try:
              c = open(filename + " cache.txt", "rt")
              code = eval(c.read())
              c.close()
          except:
              c = open(filename + " cache.txt", "wt")
              c.write("{'': ''}")
              c.close()
      
              c = open(filename + " cache.txt", "rt")
              code = eval(c.read())
              c.close()
      
      def find(filename,variable):
          global c,code
          c = open(filename + " cache.txt", "rt")
          code = eval(c.read())
          c.close()
          variable2 = code.get(variable)
          return variable2
      
      def store(filename,variable,info):
          global c,code
          code[variable] = info
          c = open(filename + " cache.txt", "wt")
          c.write(str(code))
          c.close()
      
      def clearcache(filename):
          c = open(filename + " cache.txt", "w")
          c.write("{'': ''}")
          c.close()
      
      file = "DungeonQuest"
      
      #Creates the file for storage
      cache (file);
      
      #Stores a variable for later use
      x = 15
      store(file,"x",x);
      
      #Finds a stored variable
      x = find(file,"x");
      
      #Clears all stored variables in the cache
      clearcache(file);
      

      这是我自己的一些代码,用于将变量存储到外部文本文件。唯一的问题是您必须单独存储每一个并单独查找每一个。我将它用于我自己的 python 游戏地牢任务,它似乎工作得很好

      【讨论】:

        【解决方案4】:

        我一直在做这样的事情。它使用 JSON 来实现易用性和可扩展性。在这里:

           import json
        //save files below
        def save_file():
        //to enter a name for your file
        //if you don't want to just make it a string
            save_name = input("savename: ")
            path = 'path_to_dir{0}.json'.format(save_name)
            data = {
                'name': save_name
            }
            with open(path, 'w+') as f:
                json.dump(data, f)
        
        
        def load_file():
            load_name = save_name
           path_two = 'path_to_dir{0}.json'.format(load_name)
            with open(path_two, 'r') as f:
                j = json.load(f)
                name = str(j['name'])
        

        这是我在所有项目中使用的文件保存系统。 希望对你有帮助

        【讨论】:

          【解决方案5】:

          添加到 Bogdan 的答案中,一种更易于理解的方法是将包含所有数据的字典存储起来。所以如果你有这个:

          import pickle
          data = {'health':100, 'gold': 1560, 'name': 'mariano'}
          

          你会这样做:

          with open('savefile', 'w') as f:
              pickle.dump(data, f)
          
          with open('savefile') as f:
              data = pickle.load(f)
          

          它应该加载。

          【讨论】:

            【解决方案6】:

            如果我正确理解了这个问题,那么您是在询问一种序列化对象的方法。最简单的方法是使用标准模块pickle

            import pickle
            
            player = Player(...)
            level_state = Level(...)
            
            # saving
            with open('savefile.dat', 'wb') as f:
                pickle.dump([player, level_state], f, protocol=2)
            
            # loading
            with open('savefile.dat', 'rb') as f:
                player, level_state = pickle.load(f)
            

            可以通过这种方式存储标准 Python 对象和具有任何嵌套级别的简单类。如果您的类有一些重要的构造函数,则可能需要使用相应的 protocol 提示 pickle 实际需要保存的内容。

            【讨论】:

            • 你可以使用import cPickle as pickle...protocol=pickle.HIGHEST_PROTOCOL
            • 只要确定:你在哪里,例如,“player = Player(...)”。括号中的句号只是一个占位符,对吧?实际上,我会在那里放置适当的属性,是吗?
            • 是的。我只是把它们放在那里有一些具体的东西来说明存储/加载。有关更具体的示例,请参阅@Mariano 的答案)
            【解决方案7】:

            首先,不要想太多。你不需要使用任何复杂的东西。作为初步步骤,研究python中的基本文件输入/输出。

            其次,我假设你的游戏中有一个玩家类?或者可能是一个跟踪游戏状态的整体类。那么让该类存储您的变量(如健康、黄金等)的默认值。然后有一个可以修改此类的方法,例如def load_stats(player):def load_stats(game): 之类的东西。并从保存文件中读取它,该文件可以具有您喜欢的任何格式并修改您的播放器/游戏状态的变量。

            首先测试加载游戏文件并确保您可以获取它以便修改您的播放器类。

            然后您所要做的就是添加一个保存游戏功能,让您可以将这些变量输出回目录系统中某处的文件中。

            尝试这样做,之后如果您需要任何帮助,请告诉我。

            【讨论】:

              【解决方案8】:

              我认为你可以只使用一个txt文件来记录你在游戏中需要的东西,只需使用file()和open()函数。或者你可以使用python中的sqlite3模块来保存你的记录。 试试看:

              导入 sqlite3

              帮帮忙。 :)

              这是一个在 python 中使用 sqlite3 的示例:

              只要改变你想保存到文件:

                  import sqlite3
                  cx=sqlite3.connect("stu.db") # get a connect object
                  cu=cx.cursor() # get a cursor
              
              
                  cu.execute("""create table stu
                  (
                          number char(10) primary key not null,
                          name char(10) not null,
                          sex int not null default 1 check (sex in (1,0)),
                          major char(5) not null,
                          mark int not null,
                          birthday datetime not null
                  )""")
              
                  cu.execute("insert into stu values ('010011','Jim',1,'computer',58,'1989-01-01')")
                  cu.execute("insert into stu values ('080011','Jimmy',1,'computer',59,'1990-02-25')")
                  cu.execute("insert into stu values ('080001','Jack',1,'computer',58,'1989-10-01')")
                  cu.execute("insert into stu values ('081102','Zimmer',1,'computer',60,'1990-01-01')")
                  cu.execute("insert into stu values ('081103','Hans',1,'computer',58,'1991-2-08')")
                  cu.execute("insert into stu values ('090210','Lily',0,'computer',58,'1990-05-31')")
                  cu.execute("insert into stu values ('090125','Mary',0,'computer',59,'1992-07-08')")
                  cu.execute("insert into stu values ('080136','Tom',1,'computer',58,'1989-01-01')")
                  cu.execute("insert into stu values ('090012','Lisa',0,'software',59,'1990-04-05')")
                  cu.execute("insert into stu values ('080028','Lee',0,'software',58,'1990-05-07')")
              
                  cx.commit()# commit the sql
              
                  cu.execute("select * from stu") #get the all records
                  cu.fetchone() # fetch one
                  cu.execute("select mark from stu where name='Jim'")
              
                  cu.execute("""select name=
                          case
                                  when mark >55 and mark<60 then 'ok'
                                  when mark=60 then 'good'
                                  else 'unkown'
                          end
                          from stu""")
              
                  cu.execute("""update stu      
                          set major='software'
                                  where name='Jim'
                  """)# update one
              
                  cu.execute("""select min(mark) from stu""")#get the min
                  cu.execute("select count(*) from stu") #get the number of stu
                  cu.execute("select avg(mark) from stu") #get ave
                  cu.execute("select * from stu where name='Jim'")#look jim
                  cu.execute("select * from stu where mark=60")
                  cu.execute("select * from stu where name like 'Li__'")
                  cu.execute("select * from stu where Birthday not between '1989-01-01' and '1989-12-31'") 
              
              
                  cx.commit()
              
                  res=cu.fetchall()#get all 
                  #cu.fetchone()
                  for i in res:
                          print i
              
                  cu.close()
                  cx.close()
              

              或者我认为,如果您的游戏不是很复杂,只需使用 file() 函数即可。

              【讨论】:

              • 这仍然不能回答我的问题(对不起,应该提到我对 Python 还比较陌生)。如果我确实使用了 sqlite3,我将如何将变量保存到数据库中,并在用户加载游戏保存时重用它们?
              猜你喜欢
              • 2023-03-09
              • 2011-09-19
              • 2014-12-01
              • 1970-01-01
              • 1970-01-01
              • 2020-01-04
              • 2020-06-29
              • 1970-01-01
              相关资源
              最近更新 更多