首页 文章

Int转换不起作用[重复]

提问于
浏览
0

这个问题在这里已有答案:

我正在为我的游戏创建一个高分特色,但我无法让它发挥作用

这是我的方法:

def game_over(self):
    # Game over Screen
    keys = pygame.key.get_pressed()
    self.gameover = pygame.image.load('resources/screen/game_over.png')
    screen.blit(self.gameover,(0,0))

    high_filer = open('highscores.txt', 'r')
    highscore = high_filer.read()
    high_filer.close()
    int(highscore)
    int(self.score)
    print highscore + self.score

    if self.score > highscore: 
        high_filew = open('highscores.txt', 'w')
        high_filew.write(str(self.score))
        high_filew.close()

    if (keys[K_RETURN]):
        self.state = 1

它的作用是从.txt文件中读取最新的高分,并检查玩家得分是否更高,如果它将新的高分数写入文件

我使用 int(highscore) 将字符串从 highscore 转换为int然后在第10行我做 print highscore + self.score 作为测试但我抛出一个错误,说我无法添加str和int,即使我将 highscore 转换为int并且我转换了self.score所以由于某种原因,其中一个转换不起作用

1 回答

  • 7

    int() 返回一个整数,但您丢弃该结果 . 重新分配:

    highscore = int(highscore)
    

    该函数不会就地更改变量 . 如果 self.score 也是一个字符串,你需要为 int(self.score) 执行相同的操作,或者只删除该行 .

相关问题