Int 转换不起作用

Int conversion not working(Int 转换不起作用)
本文介绍了Int 转换不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

I'm creating a highscore feature for my game but I cant get it to work

这是我的方法:

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 文件中读取最近的高分,并检查玩家的得分是否更高,如果是,它将新的高分写入文件

What it does is reads the most recent highscore from a .txt file and checks if the players score is higher if it is it writes the new highscore into the file

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

I convert the string from highscore into a int by using int(highscore) then and on line 10 I do print highscore + self.score as a test but I throws an error that says that I can't add a str and an int even though I converted highscore to an int and I converted self.score so for some reason one of the conversions didn't work

推荐答案

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

int() returns an integer, but you discard that result. Reassign it:

highscore = int(highscore)

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

The function does not change the variable in-place. If self.score is a string as well, you'll need to do the same thing for int(self.score), or just remove that line.

这篇关于Int 转换不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

build conda package from local python package(从本地 python 包构建 conda 包)
How can I see all packages that depend on a certain package with PIP?(如何使用 PIP 查看依赖于某个包的所有包?)
How to organize multiple python files into a single module without it behaving like a package?(如何将多个 python 文件组织到一个模块中而不像一个包一样?)
Check if requirements are up to date(检查要求是否是最新的)
How to upload new versions of project to PyPI with twine?(如何使用 twine 将新版本的项目上传到 PyPI?)
Why #egg=foo when pip-installing from git repo(为什么从 git repo 进行 pip 安装时 #egg=foo)