初级 Python 游戏。创建记录文件

Beginner Python Game. Create records file

我正在学习 Python 并做了这个小游戏,您可以在其中尝试猜测计算机生成的数字。

from random import randint


def guess():
    play = 0    
    while play != 'exit':    
        numbercomp = randint(1, 9)
        tries = 0
        humanno = 0    
        while numbercomp != humanno:
            humanno = int(raw_input("What is my number, from 1 to 9? "))

            if numbercomp == humanno:
                tries = tries + 1
                print('you are right, nice!')

            elif numbercomp < humanno:
                tries = tries + 1
                print('my number is smaller than yours')

            else:
                tries = tries + 1
                print('my number is bigger than yours')

        print 'you got it in', tries, 'tries'
        play = raw_input('press any key to play , type "exit" to leave')
    print "Good bye!"
    exit()


while True:
    try:
        guess()

    except ValueError:
        print('that was not a number from 1 to 9!')

我想知道有什么方法可以将最好的分数(较少尝试)和持有人的姓名保存到一个文件中,并让程序在每次启动时显示这些信息。不太重要的是以某种方式加密此文件。

此外,如果您发现可以以更优雅的方式完成,我将不胜感激。

例如你可以这样

if tries > score:
            pickle.dump( favorite_color, open( "save.p", "wb" ) )

如果尝试次数低于最高分,则更改最高分。

然后打开它

highscore = pickle.load( open( "save.p", "rb" ) )

你可以在第一个函数时打印最高分运行。