我的游戏有问题,让我们说游戏中的得分为3,然后我尝试写出高于10的分数。它没有写出我试图修复的文件但它没有工作..请帮忙。以下只是代码的一部分
# Variables within loop
loop = True
over = False
# car
carx = int(display_w/2 - 20)
cary = 500
carwidth = 40
carheight = 70
cxchange = 0
# obstacle
obx = carx - carwidth
oby = -200
obwidth = random.randint(200, 450)
obheight = random.randint(100, 200)
obychange = 0
obstacle_speed = 7
# score appending
readhighscore = open("score.txt", "r")
highscore = readhighscore.read()
while loop:
if over == True:
message_to_screen("Game over!", black, -200, "large")
message_to_screen("Final Score: " + str(score), black, -130, "small")
fire_explosion(carx + int(carwidth / 2), cary)
if str(score) > str(highscore):
writehighscore = open("score.txt", "w")
writehighscore.write(str(score))
pygame.display.update()
while over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
cxchange += 4
elif event.key == pygame.K_LEFT:
cxchange -= 4
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
cxchange = 0
elif event.key == pygame.K_LEFT:
cxchange = 0
# Movement
carx += cxchange
oby += obychange
obychange = obstacle_speed
# If Statements
# end of map and if the car successfully dodges the obstacle
if carx >= display_w - carwidth:
carx = display_w - carwidth
elif carx <= 0:
carx = 0
if oby > display_h:
if score > 16:
obwidth = random.randint(300, 450)
else:
obwidth = random.randint(200, 450)
obx = carx - random.randint(0, 100)
oby = random.randint(-1000, -500)
score += 3
# obstacle collision with the car
if oby+obheight >= cary and oby <= cary+carheight:
if carx+carwidth >= obx and carx <= obx + obwidth:
over = True
obychange = 0
# score concept
print(highscore)
# Drawing
# background color
gameDisplay.fill(white)
# car
gameDisplay.blit(car1, [carx, cary])
# obstacle
drawobjects(obx, oby, obwidth, obheight, blue)
# score
drawScore(score)
pygame.display.update()
clock.tick(FPS)
答案 0 :(得分:1)
New Anwser: 对不起,我有点不活跃,但无论如何...... 问题出在这一行:
if str(score) > str(highscore):
或者,换句话说,您正在比较字符串。而不是str,做int,你会没事的。在这种情况下你不能比字符串更大的原因是复杂的。但如果您想要解释,请参阅:String Comparison Technique Used by Python
答案 1 :(得分:0)
以下代码应完全适用,但我不太清楚问题是什么。
with open("score.txt", "w") as f:
f.write(str(score))
这只是我的头脑。
编辑:还有很多不必要的代码。阅读https://stackoverflow.com/help/mcve,关键字为 minimal 。