gpt4 book ai didi

Python 窗口打开和关闭

转载 作者:行者123 更新时间:2023-12-01 09:11:11 24 4
gpt4 key购买 nike

我一直在关注 here 的教程构建一个小型 python 游戏。这将是其背后的代码:

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>## </code to remove>一切正常。这段代码中是什么导致了这种情况的发生?

最佳答案

这是由 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()

关于Python 窗口打开和关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51639365/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com