Python覆盖我的文件,而不是找到其他人

时间:2013-11-10 00:31:14

标签: python file python-2.7

所以我用Python制作游戏并保存,有玩家保存和自动保存。如果我尝试打开一个播放器保存它就像[Errno 2] No such file or directory: 'C:/Program Files (x86)/Legendary Forging/test.ini'那样我可以去Windows资源管理器然后打开那个目录。

当我打开自动保存文件时,它会替换其中的任何内容。 (我在检查期间和之后打开了程序之外的文件)

这是我的代码:

import os
from random import randint
import time
import threading

class Engine(object):
    loop_condition = True
    def __init__(self, scene_map):
        self.scene_map = scene_map
    def play(self):
        with open("C:\\Program Files (x86)\\Legendary Forging\\autosave.ini", 'w') as player_save:
            player_save.close()
        current_scene = self.scene_map.opening_scene()
        while self.loop_condition:
            print "\n--------"
            next_scene_name = current_scene.enter()
            current_scene = self.scene_map.next_scene(next_scene_name)
            auto_save("")
            if next_scene_name == 'none':
                print
                self.loop_condition == False

class Player(object):
    hp = 100
    mana = 100
    exp = 0
    lvl = 1
    inventory = {}
    equipped = {}
    strength = 0
    intelligence = 0
    wisdom = 0
    dexterity = 0
    location = ""
    role = ""
    name = ""

class Commands(object):
    def determine(self, command):
        self.command = command
        help_word=""
        if command[0:4] == "exit":
            print
            time.sleep(.5)
            os._exit(1)
        elif command[0:4] == "save":
            create_save(command[4:])
            print "Your game has been saved under the name: %s" % command[4:]
        elif command[0:5] == "dance":
            print
            print "You dance in joy"
        elif command[0:4] == "help":
            for x in command[4:]:
                if x == " ":
                    del x
                else:
                    help_word += x
            if help_word == "warrior":
                print "\nwarrior description"
            elif help_word == "wizard":
                print "\nwizard description"
            elif help_word == "rogue":
                print "\nrogue description"
            elif help_word == "cleric":
                print "\ncleric description"
            else:
                print "There is no help file under that name."
        elif Player.location == 'startroom':
            if command[0:7] == "warrior":
                print
                print "You have chosen to be the Warrior."
                Player.strength +=10
                Player.wisdom +=2
                Player.dexterity +=6
                Player.hp +=20
                Player.intelligence +=0
                Player.mana += -100
                Player.role = "warrior"
            elif command[0:6] == "wizard":
                print
                print "You have chosen to be the Wizard."
                Player.strength +=0
                Player.wisdom +=6
                Player.intelligence +=10
                Player.dexterity +=2
                Player.hp += -20
                Player.mana +=50
                Player.role = "wizard"
            elif command[0:5] == "rogue":
                print
                print "You have chosen to be the Rogue."
                Player.strength +=4
                Player.wisdom +=4
                Player.intelligence +=2
                Player.dexterity +=10
                Player.hp +=0
                Player.mana +=-50
                Player.role = "rogue"
            elif command[0:6] == "cleric":
                print
                print "You have chosen to be the Cleric."
                Player.strength +=6
                Player.wisdom +=10
                Player.dexterity +=6
                Player.hp +=10
                Player.intelligence +=0
                Player.mana += 0
                Player.role = "cleric"
            elif command[0:4] == "load":
                if command[5:] == "autosave":
                    open_save("autosave")
                    print "Loaded autosave."
                else:
                    open_save(command[5:].lower())
                    print "Loaded save name: %s" % command [5:]

class Scene(object):
    def enter(self):
        print "Scene info"

class StartRoom(Scene):
    role_list = ["Warrior", "Rogue", "Wizard", "Cleric"]
    def enter(self):
        Player.location = "startroom"
        print "To load a previous games auto-save, type 'load autosave'\nTo load a custom save type 'load <save name>" 
        choice_load = raw_input(">")
        command_load = Commands()
        command_load.determine(choice_load)
        if Player.location != "startroom":
            return Player.location
        print"Welcome! What is your name?"
        choice_name = raw_input(">")
        self.choice_name = choice_name
        print "Choose one of the following roles."
        print "Type \"Help <role>\" to see more info about each role."
        print
        for x in self.role_list:
            print x
        print
        choice_role = raw_input(">")
        self.choice_role = choice_role.lower()
        Player.name = self.choice_name
        Player.role = self.choice_role
        command_room1 = Commands()
        command_room1.determine(self.choice_role) 
        if self.choice_role == "warrior" or self.choice_role == "wizard" or self.choice_role == "rogue" or self.choice_role == "cleric":
            time.sleep(.5)
            return "room1"
        else:
            return 'startroom'

class Death(Scene):
    quips = [
             "Wow. Much Death, so sad. Wow.",
             "Hah you suck at this!",
             "Try Again!",
             ]
    def enter(self):
        Player.location = "death"
        print Death.quips[randint(0, len(self.quips)-1)]
        print
        print "Game Over"
        return 'none'

class Room1(Scene):
    def enter(self):
        Player.location = "room1"
        print "Room 1"
        choice_i = raw_input("\n >")
        choice=choice_i.lower()
        self.choice = choice
        if self.choice == "left" or self.choice == "l":
            return "death"
        elif self.choice == "right" or self.choice == "r":
            return "room2"
        else:
            command_room1 = Commands()
            command_room1.determine(self.choice) 
            time.sleep(.5)
            return "room1"

class Room2(Scene):
    def enter(self):
        Player.location = "room2"
        print "Room 2"

class Map(object):
    scenes = {
        'room1': Room1(),
        'death': Death(),
        'room2': Room2(),
        'startroom': StartRoom()
    }
    def __init__(self, start_scene):
        self.start_scene = start_scene
    def next_scene(self, scene_name):
        return Map.scenes.get(scene_name)
        Player.location = Map.scenes.get(scene_name)
    def opening_scene(self):
        return self.next_scene(self.start_scene)

class Saving(object):
    savepath = "C:\\Program Files (x86)\\Legendary Forging"
    global auto_save
    global open_save
    global create_save
    def create_dir(self):
        if os.path.exists("C:\\Program Files (x86)\\Legendary Forging") == False:
           os.makedirs("C:\\Program Files (x86)\\Legendary Forging")
    def create_save(save_name):
        with open("C:/Program Files (x86)/Legendary Forging/%s.ini" % (save_name), 'w') as player_save:
            player_save.close()
        with open("C:/Program Files (x86)/Legendary Forging/%s.ini" % (save_name), 'r+') as player_save:
            player_save.write(    #not sure how to do inventory or equipped yet
"""player.name = %s
player.role = %s
player.hp = %d
player.mana = %d
player.exp = %d
player.lvl = %d
strength = %d
intelligence = %d
wisdom = %d
dexterity = %d
location = %s""" % (Player.name, Player.role, Player.hp, Player.mana, Player.exp, Player.lvl, Player.strength, Player.intelligence, Player.wisdom, Player.dexterity, Player.location))
            player_save.close()
    def auto_save(self):
            with open("C:/Program Files (x86)/Legendary Forging/autosave.ini", 'w') as player_save:
                player_save.write(    #not sure how to do inventory or equipped yet
"""player.name = %s
player.role = %s,
player.hp = %d,
player.mana = %d,
player.exp = %d,
player.lvl = %d,
strength = %d,
intelligence = %d,
wisdom = %d,
dexterity = %d,
location = %s,""" % (Player.name, Player.role, Player.hp, Player.mana, Player.exp, Player.lvl, Player.strength, Player.intelligence, Player.wisdom, Player.dexterity, Player.location))
    def open_save(file_name):
        with open("C:/Program Files (x86)/Legendary Forging/%s.ini" % (file_name),"r") as player_save:
            print player_save.read
            player_save.close()

a_map = Map('startroom')
a_game = Engine(a_map)
a_save = Saving()
a_save.create_dir()
a_game.play()

我不知道为什么会这样,因为今天早上工作正常。我认为在将保存文件名的输入更改为全部小写后,它发生了变化。

修改 我发现在print player_save.read之后忘记了一对括号 除了自动保存文件,我仍然无法加载任何其他文件

编辑我发现为什么它不会加载!

elif command[0:4] == "save":
            create_save(command[4:])

4应该是5,它占用了load和文件名之间的空格。

1 个答案:

答案 0 :(得分:1)

with open("C:\\Program Files (x86)\\Legendary Forging\\autosave.ini", 'w') as player_save:
    player_save.close()

我不确定您认为这段代码在做什么,但它的作用是以覆盖模式打开您的文件(删除现有内容),然后立即关闭它。我只是简单地瞥了一眼你的代码,但是每次你开始游戏时都会在游戏开始时这样做,这似乎不是你想做的事情吗?