【问题标题】:File writing in python failure在 python 中写入文件失败
【发布时间】:2015-02-05 01:01:32
【问题描述】:

我在一个简单的无尽隧道赛车类型游戏中写入高分文件时遇到了一个小问题。

如果在我开始游戏之前,文件中没有任何内容,它将写入高分。但是在文件中有一个数字之后,它就完全忽略了:

if score > hs:
    hs = score
    hsfile = open("hs.txt", "w")
    hsfile.write(str(hs))
    hsfile.close()

要打开文件并检查是否写了一些东西,我有代码:

hf = open("hs.txt", "r")

h = hf.readline()

if len(h) > 0:
    hs = h 
else:
    hs = 0

重述:

如果 hs.txt 中没有写入任何内容,则将高分添加到 txt 文件中,然后写入 txt 文件。

如果写入了某些内容(在第一次播放和重新启动应用程序之后),分数将保持在文件中写入的内容。帮忙?

如果需要完整代码:

import pygame, sys, time, random

pygame.init()

disw = 640
dish = 480

white = (255,255,255)
black = (  0,  0,  0)
brown = (193,125, 58)
green = (  0,220,  0)

gameExit = False

score = 0

speed = -2

spawned = False

hf = open("hs.txt", "r")

h = hf.readline()

if len(h) > 0:
    hs = h 
else:
    hs = 0

if gameExit == True:
    h.close()

rockx = 640

rocky = random.randint(0, dish)

rockw = random.randint(10,150)

rockh = random.randint(10,150)

ship = pygame.image.load("ship.png")

bg = pygame.image.load("bg.png")

gameOver = False

def rock(thingx,thingy,thingw,thingh,color):
    pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])

def rockhit():
    global score, spawned, speed, rockx, rocky, rockw, rockh
    rockx = 640
    rocky = random.randint(0, dish)
    rockw = random.randint(10,150)
    rockh = random.randint(10,150)
    score += 1
    spawned = False
    speed -= 1

class Ship():
    def __init__(self, x, y, w, h):
        self.x = x 
        self.y = y 
        self.w = w 
        self.h = h

gameDisplay = pygame.display.set_mode((disw,dish))
pygame.display.set_caption("Tunnel")
Clock = pygame.time.Clock()

def main():
    global gameOver, score, spawned, speed, rockx, rocky, rockw, rockh, hs, gameExit
    shipdimensions = Ship(200, 10, 60, 40)
    xc = 0
    yc = 0
    def startGame():
        gameDisplay.blit(bg, (0, 0))
        gameDisplay.blit(ship, (shipdimensions.x, shipdimensions.y))

    while not gameExit:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w:
                    yc = -6
                if event.key == pygame.K_s:
                    yc = 6
                if event.key == pygame.K_SPACE:
                    if gameOver == True:
                        startGame()
                        gameOver = False
                        speed = -2

            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_w or event.key == pygame.K_s:
                    yc = 0

        shipdimensions.y += yc
        rockx += speed  

        gameDisplay.fill(black)
        gameDisplay.blit(bg, (0, 0))
        gameDisplay.blit(ship, (shipdimensions.x, shipdimensions.y))

        font = pygame.font.SysFont(None, 25)
        text = font.render("Score: " + str(score), True, green)
        gameDisplay.blit(text, (1,1))

        font = pygame.font.SysFont(None, 25)
        text = font.render("High Score: " + str(hs), True, green)
        gameDisplay.blit(text, (1,20))

        if gameOver == True:
            font = pygame.font.SysFont(None, 25)
            text = font.render("Game Over, press 'Space' to restart.", True, green)
            gameDisplay.blit(text, (100,200))

        if shipdimensions.y < rocky + rockh:
            if shipdimensions.y + shipdimensions.h < rocky:
                pass    
            elif shipdimensions.x > rockx and shipdimensions.x < rockx + rockw or shipdimensions.x + shipdimensions.w > rockx and shipdimensions.x + shipdimensions.w < rockx + rockw:              
                rockx = 640
                rocky = random.randint(0, dish)
                rockw = random.randint(10,150)
                rockh = random.randint(10,150)
                speed = 0
                gameOver = True
                score = 0

        if gameOver == False and spawned == False:
            rock(rockx,rocky,rockw,rockh,brown)

        if shipdimensions.y <= 0:
            shipdimensions.y = 0

        if shipdimensions.y + shipdimensions.h >= dish:
            shipdimensions.y = dish - shipdimensions.h

        if rockx <= 0:
            rockhit()

        if score > hs:
            hs = score
            hsfile = open("hs.txt", "w")
            hsfile.write(str(hs))
            hsfile.close()


        pygame.display.update()
        Clock.tick(60)

if '__main__' == __name__:
    main()

【问题讨论】:

  • 请注意,此代码永远不会执行:if gameExit == True: h.close(),因为您在程序的前面将gameExit 设置为False。要真正关闭您的文件,您需要hf.close()。是的,如果你用'r' 打开一个文件,你需要先关闭它,然后再用'w' 打开它。
  • gameExit = False 当我退出游戏时,它在关闭前运行。它现在可以与其他人的修复一起使用。

标签: python file input pygame output


【解决方案1】:

在打开同一个文件进行写入之前,您可能必须关闭 hf。

【讨论】:

  • 没用!我认为这与顶部的 if 和 else 语句有关,但我不知道如何解决。
  • 您是否尝试过以读写模式打开文件?使用“r+”而不是“r”或“w”,这样你只需要处理一次打开文件
  • 同样的错误,我很困惑为什么会这样
【解决方案2】:

在读取时尝试将 hs 转换为 int(否则它将是字符串)?

if len(h) > 0:
    hs = int(h)
else:
    hs = 0

例如比较字符串和整数会很奇怪..即:

>>> 12 > "10"
False

在 python 解释器中。 (Python 可能应该抛出一个异常。我想不出你想要比较一个 int 和一个字符串的时间)。

【讨论】:

  • 谢谢,它成功了,我想我可以自己修复一个小错误。
  • 是的,修复了它写出每个数字的错误,感谢您的回答!不敢相信就这么简单。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-19
  • 1970-01-01
相关资源
最近更新 更多