pygame功能错误错误

时间:2018-08-28 20:38:33

标签: python

我似乎看不出这段代码中的错误,游戏只是在启动后就退出了。如果有人可以阅读我的代码并回答我做错了什么,我将非常感激。我已经阅读了所有内容,无法弄清楚。我不知道为什么游戏启动后立即退出。 (这意味着我什至无法移动我的方块)。

import pygame
import time

pygame.init()

width = 800
height = 600
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)

gameDisplay = pygame.display.set_mode((width, height))
pygame.display.set_caption("First snake game.")

clock = pygame.time.Clock()

block_size = 1
FPS = 100





def gameloop():

    gameExit = False

    lead_x = width/2
    lead_y = height/2
    lead_x_change = 0
    lead_y_change = 0

    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_w:
                    lead_y_change = -block_size
                    lead_x_change = 0
                if event.key == pygame.K_s:
                    lead_y_change = block_size
                    lead_x_change = 0
                if event.key == pygame.K_d:
                    lead_x_change = block_size
                    lead_y_change = 0
                if event.key == pygame.K_a:
                    lead_x_change =  -block_size
                    lead_y_change = 0
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_a or event.key == pygame.K_d:
                    lead_x_change = 0
                if event.key == pygame.K_w or event.key == pygame.K_s:
                    lead_y_change = 0


        lead_x += lead_x_change
        lead_y += lead_y_change

        gameDisplay.fill(white)
        pygame.draw.rect(gameDisplay, black, [lead_x, lead_y, block_size, block_size])
        pygame.display.update()
        time.sleep(2)
        pygame.quit()
        quit()


    clock.tick(FPS)
gameloop()

`

1 个答案:

答案 0 :(得分:1)

不确定我是否正确理解代码,但是在gameloop()函数的末尾,您有pygame.quit()quit(),因此请注释掉并看看会发生什么。