Snake Game event.type == KEYUP:游戏崩溃

时间:2015-08-19 00:37:03

标签: pygame

当我为一个事件编写代码时,我的代码出现错误,当密钥是UP或未按下时,我的空闲运行游戏然后在几秒钟后崩溃,有人能发现我不知道的错误吗?

显然还有更多的代码,但在循环中是我收到错误的地方。

while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                lead_x_change = - 10
            if event.key == pygame.K_RIGHT:
                lead_x_change =  10
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == event.K_RIGHT:
                lead_x_change = 0

    lead_x += lead_x_change
    gameDisplay.fill(white)
    pygame.draw.rect(gameDisplay, black, [lead_x,lead_y,10,10])
    pygame.display.update()

3 个答案:

答案 0 :(得分:0)

从我可以对您的代码进行的操作,您发布了一个if语句而没有任何语句继续。这会产生语法错误。添加任何代码需要去那里,它应该工作。

if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_LEFT:
        lead_x_change = - 10
    if event.key == pygame.K_RIGHT:
        lead_x_change = 10
    if event.type == pygame.KEYUP:
        #  There is nothing here
    if event.key == pygame.K_LEFT or event.key == event.K_RIGHT:
        lead_x_change = 0

答案 1 :(得分:0)

确保您获得了lead_x,lead_y

的值
lead_x = 300
lead_y = 300

lead_x_change = 0
lead_y_change = 0

你需要if elif或它不会完成选择

    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            lead_x_change = -10
            lead_y_change = 0
        elif event.key == pygame.K_RIGHT:
            lead_x_change = 10
            lead_y_change = 0

确保绘制,渲染和更新屏幕

   gameDisplay.fill(white)
    pygame.draw.rect(gameDisplay, black, [lead_x,lead_y,10,10])
    pygame.display.update()

看起来应该是这样的

lead_x = 300
lead_y = 300

lead_x_change = 0
lead_y_change = 0

clock = pygame.time.Clock()


while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                lead_x_change = -10
                lead_y_change = 0
            elif event.key == pygame.K_RIGHT:
                lead_x_change = 10
                lead_y_change = 0
            elif event.key == pygame.K_UP:
                lead_y_change = -10
                lead_x_change = 0
            elif event.key == pygame.K_DOWN:
                lead_y_change = 10
                lead_x_change = 0

    if lead_x >= 800 or lead_x < 0 or lead_y >= 600 or lead_y < 0:
        gameExit = True



    lead_x += lead_x_change
    lead_y += lead_y_change
    gameDisplay.fill(white)
    pygame.draw.rect(gameDisplay, black, [lead_x,lead_y,10,10])
    pygame.display.update()

答案 2 :(得分:0)

你写的是event.K_RIGHT,应该是pygame.K_RIGHT