Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.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_Python 3.x - Fatal编程技术网

用Python存储分数

用Python存储分数,python,python-3.x,Python,Python 3.x,到目前为止,我已经做了一个简短的游戏,在游戏中,你必须猜出问题形状的面积。到目前为止,只有三角形起作用,正确答案是B 我试图通过将用户的进度放入文本文件来存储它,但是当我调用函数更新分数时,它会覆盖文件,所以分数会被删除!我怎样才能避开这个问题,如果我不能,还有其他方法可以做到这一点,因为我希望用户能够从一个级别转到另一个级别 我的代码: User_Points = '0' def LoginScreen(): print("Welcome to Area Trainer")

到目前为止,我已经做了一个简短的游戏,在游戏中,你必须猜出问题形状的面积。到目前为止,只有三角形起作用,正确答案是B

我试图通过将用户的进度放入文本文件来存储它,但是当我调用函数更新分数时,它会覆盖文件,所以分数会被删除!我怎样才能避开这个问题,如果我不能,还有其他方法可以做到这一点,因为我希望用户能够从一个级别转到另一个级别

我的代码:

User_Points = '0'

def LoginScreen():
    print("Welcome to Area Trainer")
    print("Please enter the username for your account")
    global user_name
    user_name = str(input())
    save = open(user_name + '.txt', 'w')
    save.write(str(User_Points))


    PasswordCheck= True
    while PasswordCheck:
        user_password = input("Type in your password: ")
        if len(user_password) < 8:
            print("Your password must be 8 characters long")
        elif not any(i.isdigit() for i in user_password):
            print("You need a number in your password")
        elif not any(i.isupper() for i in user_password):
            print("You need a capital letter in your password")
        elif not any(i.islower() for i in user_password):
            print("You need a lowercase letter in your password")
        else:
            PasswordCheck = False


def MenuTriangle():
    global User_Points
    User_Points = ''
    print('''Here is a triangle with a height of 12 cm and a width of 29 cm
    /\     |                *Not to scale.
   /  \    |
  /    \   | 12 cm
 /      \  |
 <------->
    29 cm
    You must find out the area and select the correct answer from these options''')
    print('''A) 175
        B) 174
        C) 2000
        D) 199

           ''')
    user_input = input().upper()

    if user_input == "A":
            print("I'm sorry this is incorrect, but you still have a chance to get 1 point!")
            MenuTriangle2()

    elif user_input == "C":
            print("I'm sorry this is incorrect, but you still have a chance to get 1 point!")
            MenuTriangle2()

    elif user_input == "D":
            print("I'm sorry this is incorrect, but you still have a chance to get 1 point!")
            MenuTriangle2()

    elif user_input == "B":
            print("Congratulations! You got it right; someone's a smart cookie. Here have two points!")
            reading = open(user_name + '.txt')
            score = reading.read()
            score = score + '2'
            print("Your score is", score)
            save = open(user_name + '.txt', 'a')
            save.write(str(score))
            MenuStart()

def MenuStart():

    print("Welcome to the mathematical area game!")
    print("In this game you will be required to calculate the area of multiple shapes.")
    print("To do this you must know how to calculate the area of different shapes with increasing difficulty.")
    print('''Please select a shape you want to play,
    A) Triangle
    B) Square
    C) Circle''')
    user_input = input().upper()

    if user_input == "A":
        print("You have chosen to calculate the area of a triangle!")
        MenuTriangle()

    elif user_input == "B":
        print("You have chosen to calculate the area of a square!")
        MenuSquare()

    elif user_input == "C":
        print("You have chosen the calculate the area of a circle!")
        MenuCircle()

    else:
        print("Oops! I didn't understand that >:")
        MenuStart()


LoginScreen()
MenuStart()
User_Points='0'
def LoginScreen():
打印(“欢迎来到区域培训师”)
打印(“请输入您帐户的用户名”)
全局用户名
user_name=str(输入())
保存=打开(用户名+'.txt',w')
保存.写入(str(用户点))
PasswordCheck=True
密码检查时:
用户\密码=输入(“输入密码:”)
如果len(用户密码)<8:
打印(“您的密码长度必须为8个字符”)
elif not any(i.isdigit()表示用户密码中的i):
打印(“您的密码中需要一个数字”)
elif not any(i.isupper()表示用户密码中的i):
打印(“密码中需要大写字母”)
elif not any(i.islower()表示用户密码中的i):
打印(“密码中需要小写字母”)
其他:
PasswordCheck=False
def MenuTriangle():
全局用户点
用户_点=“”
打印(''这是一个高12厘米、宽29厘米的三角形
/\|*不按比例。
/  \    |
/\| 12厘米
/      \  |
29厘米
您必须找出该区域并从这些选项中选择正确答案“”)
印刷品(''A)175
B) 174
C) 2000年
D) 199
''')
用户输入=输入()
如果用户输入=“A”:
打印(“很抱歉,这是错误的,但您仍有机会获得1分!”)
MenuTriangle2()
elif user_input==“C”:
打印(“很抱歉,这是错误的,但您仍有机会获得1分!”)
MenuTriangle2()
elif user_input==“D”:
打印(“很抱歉,这是错误的,但您仍有机会获得1分!”)
MenuTriangle2()
elif user_input==“B”:
打印(“祝贺你!你做对了;某人是个聪明的人。这里有两点!”)
reading=open(用户名+'.txt')
分数=阅读。阅读()
分数=分数+2
打印(“您的分数为”,分数)
保存=打开(用户名+'.txt',a')
保存.写入(str(score))
梅努斯塔特()
def MenuStart():
打印(“欢迎来到数学区域游戏!”)
打印(“在这个游戏中,你需要计算多个形状的面积。”)
打印(“要做到这一点,你必须知道如何计算不同形状的面积,难度越来越大。”)
打印(''请选择要播放的形状,
A) 三角
B) 方格
C) 圈“”)
用户输入=输入()
如果用户输入=“A”:
打印(“您已选择计算三角形的面积!”)
MenuTriangle()
elif user_input==“B”:
打印(“您已选择计算正方形的面积!”)
MenuSquare()
elif user_input==“C”:
打印(“您选择了“计算圆的面积!”)
MenuCircle()
其他:
打印(“哎呀!我不明白>:”)
梅努斯塔特()
LoginScreen()
梅努斯塔特()

它不会保存,因为您从未关闭该文件。这就是为什么大多数人都同意使用open(文件名为“w+”)是最佳实践

请尝试将以下格式用于
LoginScreen()

我还注意到在
MenuTriangle()
的末尾,您尝试将字符串添加到一起,而不是添加整数。在增加分数之前,您需要将从文件中读取的字符串转换为整数。您也不提供所需的文件打开模式。它默认为
'r'
,但最好是显式的

def MenuTriangle():

    # if: ...
    # elif: ...
    # elif: ...

    elif user_input == "B":
        print("Congratulations! You got it right, someone's a smart cookie. Here have two points!")

        with open(user_name + '.txt', 'r') as f:
            score = f.read()
            new_score = int(score) + 2
            print("Your score is {}".format(new_score))

        with open(user_name + '.txt', 'w+') as w:  # Wouldn't you want to overwrite this rather than continue appending numbers?
            w.write(str(new_score))

        MenuStart()  # Call this outside of your with statements so that the file closes

你在这里做的加法

score = reading.read()
score = score + '2'
类型str
,因此您将不断获取类似
024
的值,首先将文件中的值更改为
int

    score = int(score) + '2'
同时以
w+
模式打开文件

save = open(user_name + '.txt', 'w+')

或者使用别人推荐的

为什么要发布整个游戏?我们只需要看到分数写入文件的部分。请给出一个简单但完整的例子:我不清楚你遇到的问题是什么?您似乎正在正确地打开、读取和追加文件。顺便说一下,您可能会发现
with
语句有助于打开文件-。为什么不检查答案是否正确(
B
),否则您的打印和函数调用会将代码缩短一位,我不是一个非常有经验的python用户,所以我可能在这里和那里遗漏了一些信息,对此我表示歉意,但当用户回答一个问题时,我希望用户分数存储在文件中,但因为我再次调用函数,它只是被重写了,所以文件只是空白,没有任何内容,所以很明显我的分数没有正确存储。。。再次为我的问题不够简洁表示歉意。我是新到这个网站的。非常感谢!这工作做得很好!我知道你现在做了什么!:D
save = open(user_name + '.txt', 'w+')