我一直在遵循here的教程来构建一个小型python游戏。 这就是其背后的代码:
RUN apt-get update && apt-get install --no-install-recommends -y \
wget \
nano \
git \
unzip \
iputils-ping \
gnupg \
supervisor \
cron
COPY .docker/scripts/init-services.sh /usr/bin/init-services
RUN chmod +x /usr/bin/init-services
CMD ["/usr/bin/init-services"]
当我尝试运行它时,窗口打开并立即关闭。但是,如果我删除两个import pygame
pygame.init()
display_width = 1280
display_height = 720
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Racing Game")
clock = pygame.time.Clock()
black = (0,0,0)
white = (255,255,255)
carImg = pygame.image.load("racecar.png")
def car(x,y):
gameDisplay.blit(carImg, (x,y))
x = display_width * 0.45
y = display_height * 0.8
x_change = 0
car_speed = 0
crashed = True
while crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = False
## <code to remove>
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
if event.type = pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
## </code to remove>
print(event)
x += x_change
gameDisplay.fill((255,255,255))
car(x,y)
pygame.display.update()
clock.tick(60)
pygame.display.quit()
pygame.quit()
quit()
和## <code to remove>
之间的代码,一切正常。这段代码是由什么引起的?
答案 0 :(得分:1)
这是由if event.type = pygame.KEYUP:
处的语法错误引起的。打开文件将使其立即关闭,但是在解释器(IDLE)中运行该文件将向您显示该错误。只需将其更改为if event.type == pygame.KEYUP:
,一切正常。
更新:
文件中运行的代码而不是解释器(IDLE)不会总是打开。最好在IDLE中运行它。
代码:
import pygame
pygame.init()
display_width = 1280
display_height = 720
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Racing Game")
clock = pygame.time.Clock()
black = (0,0,0)
white = (255,255,255)
carImg = pygame.image.load("racecar.png")
def car(x,y):
gameDisplay.blit(carImg, (x,y))
x = display_width * 0.45
y = display_height * 0.8
x_change = 0
car_speed = 0
crashed = True
while crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = False
#############################
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
#############################
print(event)
x += x_change
gameDisplay.fill((255,255,255))
car(x,y)
pygame.display.update()
clock.tick(60)
pygame.display.quit()
pygame.quit()
quit()