Python 保存到一个文件和排序后的最高分数!巨蟒游戏

Python 保存到一个文件和排序后的最高分数!巨蟒游戏,python,Python,更新: 我按你说的加了这个 class HighscoreHandler(object): HIGHSCORE_FILE = "highscores.txt" # define where to store highscores def get_highscores(self, sort=True): # return sorted by default with open(self.HIGHSCORE_FILE, "a+") as f: # open the highscor

更新: 我按你说的加了这个

class HighscoreHandler(object):

HIGHSCORE_FILE = "highscores.txt"  # define where to store highscores

def get_highscores(self, sort=True):  # return sorted by default
    with open(self.HIGHSCORE_FILE, "a+") as f:  # open the highscore file
        f.seek(0)  # rewind to the file start
        scores = [int(x) for x in f.read().split()]  # read the scores as ints
        if sort:  # sort if required
            return sorted(scores)  # add reverse=True to `sorted()` for a descending sort
        return scores

def save_highscore(self, highscore):
    highscores = set(self.get_highscores(False))  # get the current highscore list
    if highscore in highscores:  # this highscore already exists
        return  # nothing to do...
    highscores.add(highscore)  # add the highscore to a set
    with open(self.HIGHSCORE_FILE, "w") as f:  # open the highscore file for writing
        f.write(" ".join(str(score) for score in highscores))  # store the scores
然后我把
save_highscore
get_highscore
放在我的“代码”部分

#显示最终分数。
绞车(主板)
分数=getScoreOfBoard(主板)
打印('X分为%s分。O分为%s分。.%(分数['X'],分数['O']))
如果分数[playerTile]>分数[computerTile]:
打印('您以%s点击败了计算机!祝贺您!'%(分数[playerTile]-分数[computerTile]))
highscore=分数[playerTile]-分数[computerTile]
获得高分
保存高分()
elif分数[playerTile]<分数[computerTile]:
打印('您输了。计算机以%s分打败了您。'%(分数[computerTile]-分数[playerTile]))
其他:
打印(“比赛打成平局!”)
如果没有再次播放():
打破

但是,当我试图将高分保存到文件时,它告诉我,
名称“get_highscores”未定义

您可以使用列表将所有分数保存到:

  drawBoard(mainBoard, highscore)
  scores = getScoreOfBoard(mainBoard)
  print('X scored %s points. O scored %s points.' % (scores['X'],scores['O']))
  if scores[playerTile] > scores[computerTile]:
     print('You beat the computer by %s points! Congratulations!' %  (scores[playerTile] - scores[computerTile]))
     highscore =  scores[playerTile] - scores[computerTile]
     self.list.append(highscore)
  elif scores[playerTile] < scores[computerTile]:
     print('You lost. The computer beat you by %s points.' % (sc ores[computerTile] - scores[playerTile]))
  else:
    print('The game was a tie!')
排序功能:

def sort(self, list):
    list.sort()
    self.saveToFile(list)
saveToFile函数:

def saveToFile(list):
    with open ('Highscore.txt', 'r+') as file:
       for i in list:
           file.write(i) 

您可以创建两个函数-一个用于读取分数,另一个用于在需要时更新分数。最简单的方法是只存储一个简单的
集合
(清除重复项),并在需要时检索它(如果需要以排序方式显示分数,还可以选择进行排序:

HIGHSCORE_FILE = "highscores.txt"  # define where to store highscores

def get_highscores(sort=True):  # return sorted by default
    with open(HIGHSCORE_FILE, "a+") as f:  # open the highscore file
        f.seek(0)  # rewind to the file start
        scores = [int(x) for x in f.read().split()]  # read the scores and turn them to int
        if sort:  # sort if required
            return sorted(scores)  # add reverse=True to `sorted()` for a descending sort
        return scores

def save_highscore(highscore):
    highscores = set(get_highscores(False))  # get the current highscore list
    if highscore in highscores:  # this highscore already exists
        return  # nothing to do...
    highscores.add(highscore)  # add the highscore to a set
    with open(HIGHSCORE_FILE, "w") as f:  # open the highscore file for writing
        f.write(" ".join(str(score) for score in highscores))  # store space separated scores
然后,您可以使用这两个功能来管理您的高分,如下所示:

print(get_highscores())  # [], no highscores yet
save_highscore(5)  # add 5
print(get_highscores())  # [5]
save_highscore(12)  # add 12
save_highscore(6)  # add 6
save_highscore(8)  # add 8
print(get_highscores())  # [5, 6, 8, 12]
save_highscore(6)  # add 6 again
print(get_highscores())  # [5, 6, 8, 12], it doesn't save duplicate scores
UPDATE-只需添加一个
self
属性作为它们的第一个方法,并将
HIGHSCORE\u文件
作为类属性,将其称为
self.HIGHSCORE\u文件
,即可轻松地将这些函数转换为类方法,类似于:

class HighscoreHandler(object):

    HIGHSCORE_FILE = "highscores.txt"  # define where to store highscores

    def get_highscores(self, sort=True):  # return sorted by default
        with open(self.HIGHSCORE_FILE, "a+") as f:  # open the highscore file
            f.seek(0)  # rewind to the file start
            scores = [int(x) for x in f.read().split()]  # read the scores as ints
            if sort:  # sort if required
                return sorted(scores)  # add reverse=True to `sorted()` for a descending sort
            return scores

    def save_highscore(self, highscore):
        highscores = set(self.get_highscores(False))  # get the current highscore list
        if highscore in highscores:  # this highscore already exists
            return  # nothing to do...
        highscores.add(highscore)  # add the highscore to a set
        with open(self.HIGHSCORE_FILE, "w") as f:  # open the highscore file for writing
            f.write(" ".join(str(score) for score in highscores))  # store the scores
然后,您可以通过引用它的实例以相同的方式运行它:

handler = HighscoreHandler()
print(handler.get_highscores())  # [], no highscores yet
handler.save_highscore(5)  # add 5
print(handler.get_highscores())  # [5]
handler.save_highscore(12)  # add 12
handler.save_highscore(6)  # add 6
handler.save_highscore(8)  # add 8
print(handler.get_highscores())  # [5, 6, 8, 12]
handler.save_highscore(6)  # add 6 again
print(handler.get_highscores())  # [5, 6, 8, 12], it doesn't save duplicate scores

你能举一个你想排序的例子吗?我只是想对高分进行排序,这意味着用户分数之间的差异——计算机分数越高,文件越高。为什么不把分数保存在一个列表中,然后用内置的排序功能对其进行排序,最后将其插入文件?是的当然可以,但我不知道如何…它告诉我,
“this”没有定义
我把
this.list()
改为
self.list()
,它仍然告诉我“this not defined”你的意思是
this
改为
self
?它告诉我
类型错误:\uu init接受0个位置参数,但给出了1个
好吧,我把它留给你来放在参数中。从_init__(self,…)开始无法以任何方式将此解决方案链接到类对象?一切都进行得很顺利,但当我运行程序时,文本文件上没有高分!@Pythongirl-检查更新以了解如何将其用作类的一部分。至于为什么它不起作用,只要您提供整数和有效的写入路径,我就看不出为什么它会起作用不是。错误很可能发生在代码的其他地方。好吧,我明白了。我有一个问题,我应该把这两个定义添加到我当前的代码中吗?我不知道你的
drawboard
是什么,也不知道你的其余代码是如何构造的-从技术上讲,只要你能调用这两个函数来读取/保存你的高分,就不会有问题试着把它们放在什么样的结构下。这是风格和设计的问题。
class HighscoreHandler(object):

    HIGHSCORE_FILE = "highscores.txt"  # define where to store highscores

    def get_highscores(self, sort=True):  # return sorted by default
        with open(self.HIGHSCORE_FILE, "a+") as f:  # open the highscore file
            f.seek(0)  # rewind to the file start
            scores = [int(x) for x in f.read().split()]  # read the scores as ints
            if sort:  # sort if required
                return sorted(scores)  # add reverse=True to `sorted()` for a descending sort
            return scores

    def save_highscore(self, highscore):
        highscores = set(self.get_highscores(False))  # get the current highscore list
        if highscore in highscores:  # this highscore already exists
            return  # nothing to do...
        highscores.add(highscore)  # add the highscore to a set
        with open(self.HIGHSCORE_FILE, "w") as f:  # open the highscore file for writing
            f.write(" ".join(str(score) for score in highscores))  # store the scores
handler = HighscoreHandler()
print(handler.get_highscores())  # [], no highscores yet
handler.save_highscore(5)  # add 5
print(handler.get_highscores())  # [5]
handler.save_highscore(12)  # add 12
handler.save_highscore(6)  # add 6
handler.save_highscore(8)  # add 8
print(handler.get_highscores())  # [5, 6, 8, 12]
handler.save_highscore(6)  # add 6 again
print(handler.get_highscores())  # [5, 6, 8, 12], it doesn't save duplicate scores