Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 尝试在程序上加载上一次保存时出错_Python - Fatal编程技术网

Python 尝试在程序上加载上一次保存时出错

Python 尝试在程序上加载上一次保存时出错,python,Python,每当我试图在这个程序上加载以前的游戏时,我都会出错。菜单中的保存功能用于加载游戏中的值,如黄金金额、胸围金额和强盗金额,这些值将在会话中用作“加载”前一个游戏的原因。我也不确定pickle模块是否适用于此,因为应该有另一种方法来实现这一点,但我想尝试pickle,因为它被推荐用于此类函数 import random import sys import time import os import pickle #module used to serielize objects boardeasy=

每当我试图在这个程序上加载以前的游戏时,我都会出错。菜单中的保存功能用于加载游戏中的值,如黄金金额、胸围金额和强盗金额,这些值将在会话中用作“加载”前一个游戏的原因。我也不确定pickle模块是否适用于此,因为应该有另一种方法来实现这一点,但我想尝试pickle,因为它被推荐用于此类函数

import random
import sys
import time
import os
import pickle #module used to serielize objects
boardeasy=[]
boardmed=[]
boardhard=[]
current=[0,0]
treasures = [(random.randint(0,8), random.randint(0,8)) for i in range(12)]
bandits = [(random.randint(0,8), random.randint(0,8)) for i in range(12)]
Coins = 0
Chest = 10
Bandit1 = 5
Bandit2 = 7
Bandit3 = 10

class user():
    def __init__(self, username, userscore, usertime):
        self.username = username
        self.userscore = userscore
        self.usertime = usertime

#For loop prints a new 8*8 grid after every move
boardeasy = [[' ' for j in range(8)] for i in range(8)]
def table_game_easy():
    print("  1   2   3   4   5   6   7   8")
    print("---------------------------------")
    for row in range(8):
        print ('| ' + ' | '.join(boardeasy[row][:8]) + ' | ' + str(row + 1))
        print("---------------------------------")
    treasures_row = [random.randint(0,8) for i in range(10)]
    treasures_col = [random.randint(0,8) for i in range(10)]
    bandits_row = [random.randint(0,8) for i in range(5)]
    bandits_col = [random.randint(0,8) for i in range(5)]

# For loop prints a new 10*10 grid after every move
boardmed = [[' ' for j in range(10)] for i in range(10)]

def table_game_meduim():
    print("  1   2   3   4   5   6   7   8   9   10")
    print("------------------------------------------")
    for row in range(10):
        print ('| ' + ' | '.join(boardmed[row][:10]) + ' | ' + str(row + 1))
        print("------------------------------------------")
    treasures_row = [random.randint(0,10) for i in range(10)]
    treasures_col = [random.randint(0,10) for i in range(10)]
    bandits_row = [random.randint(0,10) for i in range(7)]
    bandits_col = [random.randint(0,10) for i in range(7)]

# For loop prints a new 12*12 grid after every move
boardhard = [[' ' for j in range(12)] for i in range(12)]
def table_game_hard():
    print("  1   2   3   4   5   6   7   8   9   10   11   12")
    print("----------------------------------------------------")
    for row in range(12):
        print ('| ' + ' | '.join(boardhard[row][:12]) + ' | ' + str(row + 1))
        print("----------------------------------------------------")
    treasures_row = [random.randint(0,10) for i in range(10)]
    treasures_col = [random.randint(0,10) for i in range(10)]
    bandits_row = [random.randint(0,10) for i in range(10)]
    bandits_col = [random.randint(0,10) for i in range(10)]

#this function is in charge of downwards movement
def down(num,lev):
    num=(num+current[0])%lev#The % formats this equation
    current[0]=num
#this function is in charge of downwards movement
def right(num,lev):
    num=(num+current[1])%lev #The % formats this equation
    current[1]=num
#this function is in charge of downwards movement
def left(num,lev):
    if current[1]-num>=0:
        current[1]=current[1]-num
    else:
        current[1]=current[1]-num+lev
#this function is in charge of downwards movement
def up(num,lev):
    if current[0]-num>=0:
        current[0]=current[0]-num
    else:
        current[0]=current[0]-num+lev

def easy_level(Coins, Chest, Bandit1):
    #This function is for the movement of the game in easy difficulty
    while  True and Chest > 0:
        oldcurrent=current
        boardeasy[oldcurrent[0]][oldcurrent[1]]='*' 
        table_game_easy()
        boardeasy[oldcurrent[0]][oldcurrent[1]]=' '
        n = input('Enter the direction followed by the number Ex:Up 5 , Number should be < 8 \n')
        n=n.split()
        if n[0].lower() not in ['up','left','down','right']:#Validates input
            print('Wrong command, please input again')
            continue
        elif n[0].lower()=='up':
            up(int(n[1].lower()),8)#Boundary is set to 8 as the 'easy' grid is a 8^8
        elif n[0].lower()=='down':
            down(int(n[1].lower()),8)
        elif n[0].lower()=='left':
            left(int(n[1].lower()),8)
        elif n[0].lower()=='right':
            right(int(n[1].lower()),8)

        print(Chest,"chests left")
        print(Bandit1,"bandits left")
        print("Coins:",Coins)#Acts as a counter, displays the number of coins that the player has
        if (current[0], current[1]) in treasures[:8]:
            Chest = Chest - 1
            print("Hooray! You have found booty! +10 gold")
            Coins = Coins + 10 #Adds an additional 10 points
            print("Coins:",Coins)


        if (current[0], current[1]) in bandits[:8]:
            Bandit1 = Bandit1 - 1
            print("Oh no! You have landed on a bandit...they steal all your coins!")
            Coins = Coins-Coins #Removes all coins
            print("Coins:",Coins)

        boardeasy[current[0]][current[1]]='*'#sets value to players position

    username = input("Please enter a username:")    
    with open("high_scores.txt","a") as f:
        f.write(str(Coins)+ os.linesep)
        f.write(username + os.linesep)
        f.close()

def med_level(Coins, Chest, Bandit2):
#This function is for the movement of the game in medium difficulty
    while  True:
        oldcurrent=current

        boardmed[oldcurrent[0]][oldcurrent[1]]='*'
        table_game_meduim()
        boardmed[oldcurrent[0]][oldcurrent[1]]=' '
        n = input('Enter the direction followed by the number Ex:Up 5 , Number should be < 10 \n')
        n=n.split()
        if n[0].lower() not in ['up','left','down','right']:
            print('wrong command')
            continue
        elif n[0].lower()=='up':
            up(int(n[1].lower()),10)#Boundary is set to 10 as the 'easy' grid is a 10^10
        elif n[0].lower()=='down':
            down(int(n[1].lower()),10)
        elif n[0].lower()=='left':
            left(int(n[1].lower()),10)
        elif n[0].lower()=='right':
            right(int(n[1].lower()),10)
        print(Chest,"chests left")
        print(Bandit2,"bandits left")
        print("Coins:",Coins)#Acts as a counter, displays the number of coins that the player has
        if (current[0], current[1]) in treasures[:10]:
            Chest = Chest - 1
            print("Hooray! You have found booty! +10 gold")
            Coins = Coins+10 #Adds an additional 10 points
            print("Coins:",Coins)

        if (current[0], current[1]) in bandits[:10]:
            Bandit2 = Bandit2 - 1
            print("Oh no! You have landed on a bandit...they steal all your coins!")
            Coins = Coins-Coins #Removes all coins
            print("Coins:",Coins)
        boardmed[current[0]][current[1]]='*'

def hard_level(Coins, Chest, Bandit3):
#This function is for the movement of the game in hard difficulty
    while  True:
        oldcurrent=current
        boardhard[oldcurrent[0]][oldcurrent[1]]='*'
        table_game_hard()
        boardhard[oldcurrent[0]][oldcurrent[1]]=' '
        n = input('Enter the direction followed by the number Ex:Up 5 , Number should be < 12 \n')
        n=n.split()
        if n[0].lower() not in ['up','left','down','right']:
            print('wrong command')
            continue
        elif n[0].lower()=='up':
            up(int(n[1].lower()),12)#Boundary is set to 12 as the 'hard' grid is a 12^12
        elif n[0].lower()=='down':
            down(int(n[1].lower()),12)
        elif n[0].lower()=='left':
            left(int(n[1].lower()),12)
        elif n[0].lower()=='right':
            right(int(n[1].lower()),12)

        print(Chest,"chests left")
        print(Bandit3,"bandits left")
        print("Coins:",Coins)#Acts as a counter, displays the number of coins that the player has
        if (current[0], current[1]) in treasures[:12]:
            Chest = Chest - 1
            print("Hooray! You have found booty! +10 gold")
            Coins = Coins+10 #Adds an additional 10 points
            print("Coins:",Coins)

        if (current[0], current[1]) in bandits[:12]:
            Bandit2 = Bandit2 - 1
            print("Oh no! You have landed on a bandit...they steal all your coins!")
            Coins = Coins-Coins #Removes all coins
            print("Coins:",Coins)

        boardhard[current[0]][current[1]]='*'
def instruct():
    difficulty = input("""Before the game starts, please consider what difficulty
would you like to play in, easy, medium or (if you're brave) hard.
""")
    if difficulty == "easy":
        print("That's great! Lets continue.")
        time.sleep(1)#Allows the user time to get ready
        print("initiating game in...")
        time.sleep(1)
        print()
        print("3")
        time.sleep(1)
        print("2")
        time.sleep(1)
        print("1")
        time.sleep(1)
        for i in range(3):
            print("")
        easy_level(Coins, Chest, Bandit1)

    elif difficulty == "medium":
        print("That's great! Lets continue.")
        time.sleep(1)#Allows the user time to get ready
        print("initiating game in...")
        time.sleep(1)
        print()
        print("3")
        time.sleep(1)
        print("2")
        time.sleep(1)
        print("1")
        time.sleep(1)
        for i in range(3):
            print("")
        med_level(Coins, Chest, Bandit2)

    elif difficulty == "hard":
        print("That's great! Lets continue.")
        time.sleep(1)#Allows the user time to get ready
        print("initiating game in...")
        time.sleep(1)
        print()
        print("3")
        time.sleep(1)
        print("2")
        time.sleep(1)
        print("1")
        time.sleep(1)
        for i in range(3):
            print("")
        hard_level(Coins, Chest, Bandit3)
    else:
       print("Sorry, that is an invalid answer. Please restart the programme")

def menu():
    #This function lets the user quit the application or progress to playing.
    print("")
    print ("Are you sure you wish to play this game? Please answer either yes or no.")
    choice1 = input() # Sets variable to user input
    if choice1.lower().startswith('y'): 
       print("Okay lets continue then!")
       print("")
       print("")
       print("""~~~~~~~~~~MENU~~~~~~~~~~
             1). Load a previous game
             2). Display the high score table
             3). Continue

             """)
       choice2 = input(">")
       while choice2 != '3':
           print("")
           print("")
           print("""~~~~~~~~~~MENU~~~~~~~~~~
             1). Load a previous game
             2). Display the high score table
             3). Continue

             """)
           choice2 = input(">")
           if choice2 == "1":
               with open('savefile.dat', 'rb') as f:
                   (Coins, Chest, Bandit1) = pickle.load(f)

           elif choice2 == "2":
               with open("high_scores.txt") as f:
                   for line in f:
                       print(line)
                       print("")

    elif choice1.lower().startswith('n'):
        print("Thank you, I hope you will play next time!")
        print("")
        quit("Thank you for playing!")#Terminates the programme
    else:
        print("Sorry, that is an invalid answer. Please restart the programme")
        print("")
        quit()

    instruct()

def showInstructions():
    time.sleep(1.0)
    print("Instructions of the game:")
    time.sleep(1.0)
    print("""
You are a treasure hunter, your goal is to collect atleast 100 gold by the end
of the game from treasure chests randomly scattered across the grid. There are
10 chests within a grid (this can be changed based on difficulty) and  each
treasure chest is worth 10 gold but can only be reclaimed 3 times before it is
replaced by a bandit. Landing on a bandit will cause you to lose all of your
gold and if all the chests have been replaced by bandits and you have less then
100 gold this means you lose!
Press enter to continue...""")
    input()

    print("""
At the start of the game, you always begin at the top right of the grid.
Below is a representation of the game:

 * 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0
Press enter to continue...""")
    input()

    print("""
When deciding where to move, you should input the direct co-ordinates of your
desired location. For instance:
Enter the direction followed by the number Ex: Up 5 , Number should be < 8
right 3
 0 0 0 * 0 0 0 0
 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0
Unlucky move! You have found nothing!
If nothing on the grid changes , this means that your move was a bust! Landing
on nothing isn't displayed on the grid.
Press enter to continue...""")
    input()
    print("""
Enter the direction followed by the number Ex: Up 5 , Number should be < 8
down 4
 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0
 * 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0
Hooray! You have found booty! +10 gold
Here you can see that the use has landed on a chest!
As you land on chest, they get replaced by bandits. Be sure to remember the
previous locations so you don't accidently land on a bandit and lose all
your gold!
Press enter to continue...""")
    input()

#Introduces the user
print('Welcome to the Treasure hunt!')
time.sleep(0.3)
print()
time.sleep(0.3)
print('Would you like to see the instructions? (yes/no)')
if input().lower().startswith('y'):#If function checks for the first letter
    showInstructions()
elif input == 'no' or 'No':
    print("Lets continue then!")#Calls the function which displays instructions
else:
   print("Please check your input and try again.")

menu()
随机导入
导入系统
导入时间
导入操作系统
导入用于序列化对象的pickle#模块
boardeasy=[]
boardmed=[]
boardhard=[]
当前=[0,0]
珍宝=[(random.randint(0,8),random.randint(0,8))表示范围(12)内的i]
bandits=[(random.randint(0,8),random.randint(0,8))用于范围(12)内的i]
硬币=0
胸围=10
1=5
2=7
3=10
类用户():
定义初始化(self、用户名、用户分数、用户时间):
self.username=用户名
self.userscore=userscore
self.usertime=usertime
#For loop在每次移动后打印一个新的8*8网格
boardeasy=[[''表示范围(8)中的j]表示范围(8)中的i]
def table_game_easy():
印刷品(“12345678”)
打印(-------------------------------------)
对于范围(8)中的行:
打印('|'+'|'.join(boardeasy[row][:8])+'|'+str(row+1))
打印(-------------------------------------)
珍宝_行=[random.randint(0,8)表示范围(10)内的i]
宝藏_col=[random.randint(0,8)表示范围(10)内的i]
bandits_row=[random.randint(0,8)表示范围(5)内的i]
bandits_col=[random.randint(0,8)表示范围(5)内的i]
#For loop在每次移动后打印一个新的10*10网格
boardmed=[''表示范围(10)中的j]表示范围(10)中的i]
def table_game_meduim():
印刷品(“12345678910”)
打印(“-------------------------------------------------”)
对于范围(10)中的行:
打印('|'+'|'.join(boardmed[row][:10])+'|'+str(row+1))
打印(“-------------------------------------------------”)
珍宝_行=[random.randint(0,10)表示范围(10)内的i]
珍宝_col=[random.randint(0,10)表示范围(10)内的i]
bandits_row=[random.randint(0,10)表示范围(7)内的i]
bandits_col=[random.randint(0,10)表示范围(7)内的i]
#For loop在每次移动后打印一个新的12*12网格
boardhard=[''表示范围(12)中的j]表示范围(12)中的i]
def table_game_hard():
印刷品(“123456789910112”)
打印(------------------------------------------------------------)
对于范围(12)中的行:
打印('|'+'|'.join(boardhard[row][:12])+'|'+str(row+1))
打印(------------------------------------------------------------)
珍宝_行=[random.randint(0,10)表示范围(10)内的i]
珍宝_col=[random.randint(0,10)表示范围(10)内的i]
bandits_row=[random.randint(0,10)表示范围(10)内的i]
bandits_col=[random.randint(0,10)表示范围(10)内的i]
#此功能负责向下移动
def下降(数值,水平):
num=(num+current[0])%lev#此公式的格式为%
当前[0]=num
#此功能负责向下移动
def右侧(数字、级别):
num=(num+current[1])%lev#该%格式化此等式
当前[1]=num
#此功能负责向下移动
def左(数值,水平):
如果当前[1]-num>=0:
当前[1]=当前[1]-num
其他:
电流[1]=电流[1]-num+lev
#此功能负责向下移动
def up(数值、液位):
如果当前[0]-num>=0:
当前[0]=当前[0]-num
其他:
当前[0]=当前[0]-num+lev
def easy_液位(硬币、箱子、1):
#这个功能是为游戏中的运动提供简单的难度
如果为True且胸部>0:
电流=电流
boardeasy[oldcurrent[0]][oldcurrent[1]]='*'
表\u游戏\u简单()
boardeasy[oldcurrent[0]][oldcurrent[1]]=''
n=输入('输入方向后接数字Ex:Up 5,数字应<8\n')
n=n.split()
如果n[0].lower()不在['up'、'left'、'down'、'right']中:#验证输入
打印('命令错误,请重新输入')
持续
elif n[0]。lower()=“向上”:
up(int(n[1].lower()),8)#边界设置为8,因为“easy”网格是8^8
elif n[0]。lower()=='down':
向下(int(n[1].lower()),8)
elif n[0]。lower()=='left':
左(int(n[1].lower()),8)
elif n[0]。lower()=“右”:
右(int(n[1].lower()),8)
打印(胸部,“胸部左侧”)
打印(Bandit1,“bandits left”)
打印(“硬币:,硬币)#作为计数器,显示玩家拥有的硬币数量
如果宝藏[:8]中的(当前[0],当前[1]):
胸部=胸部-1
打印(“万岁!你找到战利品了!+10金币”)
硬币=硬币+10#额外增加10分
打印(“硬币:”,硬币)
如果(当前[0],当前[1])在bandits[:8]:
班迪特1=班迪特1-1
打印(“哦,不!你落到了一个强盗身上……他们偷走了你所有的硬币!”)
硬币=硬币硬币#移除所有硬币
打印(“硬币:”,硬币)
boardeasy[current[0]][current[1]]='*'#将值设置为玩家位置
用户名=输入(“请输入用户名:”)
以open(“high_scores.txt”,“a”)作为f:
f、 书写(str(硬币)+os.linesep)
f、 写入(用户名+os.linesep)
f、 关闭()
def med_液位(硬币、箱子、2):
#此功能用于中等难度的游戏移动
尽管如此:
电流=电流
boardmed[oldcurrent[0]][oldcurrent[1]]='*'
表(游戏)
boardmed[oldcurrent[0]][oldcurrent[1]]=''
n=输入('输入方向后接数字Ex:Up 5,数字应<10\n')
n=n.split()
如果n[0]。lower()不在['up'、'left'、'down'、'right']中:
打印('错误命令')
持续
elif n[0]
with open('somefile.sav', 'w') as f:
    json.dump([coins, chests, bandits], f)
with open('somefile.sav') as f:
    coins, chests, bandits = json.load(f)