PyGame 游戏在幕后工作,但图像不会移动
Posted
技术标签:
【中文标题】PyGame 游戏在幕后工作,但图像不会移动【英文标题】:Behind the scenes PyGame game works but image won't move 【发布时间】:2020-05-21 20:47:33 【问题描述】:我正在尝试制作自己的游戏。之前,汽车图像会很好地移动,但随后将我的循环置于“def”事物中,以便在汽车撞墙和获胜时重新开始游戏。现在,一切正常,只是游戏似乎没有更新到屏幕上,因为汽车不会移动。游戏似乎仍然在屏幕后面运行,因为当我在没有看到它移动的情况下发生车祸时,它会播放碰撞片段。 PyGame 没有说 day 是错误的。这对我来说有点新鲜,我真的不明白是什么问题。 这是我的代码的一部分:
#Setting and variables
display_width = 1570
display_height = 450
car_width = 98
car_height = 66
clock = pygame.time.Clock()
wn = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('My own game')
finish_line = pygame.image.load('myOwnFinishreal.png')
carImg = pygame.image.load('myOwnRGame.png')
carY = 192
carX = 10
Xchange = 0
Ychange = 0
Xfin = 1480
Yfin = 0
carY = 192
carX = 10
#racecar
def car(x,y):
wn.blit(carImg, (carX, carY))
#finish line
def finish():
wn.blit(finish_line, (Xfin, Yfin))
#Crashing
def textObjects(text, font):
textSurface = font.render(text, True, red)
return textSurface, textSurface.get_rect()
def displayMessage(text):
textFont1 = pygame.font.Font('freesansbold.ttf', 32)
textSurf, textRect = textObjects(text, textFont1)
textRect.center = ((display_width/2),(display_height/2))
while True:
wn.blit(textSurf, textRect)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
pygame.quit()
if event.key == pygame.K_SPACE:
gameLoop()
pygame.display.update()
def crash():
displayMessage('You crashed!Press X to quit, _SPACE_ to restart!')
def win():
displayMessage('Bravo! You are the best car runner! Press X to quit _SPACE_ to restart.')
#Game loop
def gameLoop():
carY = 192
carX = 10
Xchange = 0
Ychange = 0
alive = True
losing = True
while alive and losing:
carX += Xchange
carY += Ychange
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
pygame.quit()
if event.key == pygame.K_UP:
Xchange = 0
Ychange = 0
Xchange = 2.5
elif event.key == pygame.K_LEFT:
Xchange = 0
Ychange = 0
time.sleep(0.85)
Ychange = -3
elif event.key == pygame.K_RIGHT:
Xchange = 0
Ychange = 0
time.sleep(0.85)
Ychange = 3
elif event.key == pygame.K_DOWN:
Xchange = 0
Ychange = 0
time.sleep(0.85)
Xchange = -3
if carY <= -15 or carY >= display_height - 15:
Xchange = 0
Ychange = 0
crash()
if carX >= display_width:
Xchange = 0
Ychange = 0
win()
if carX <= 0:
carX = 10
#350 250 120 30
wn.fill(grey)
finish()
carX += Xchange
carY += Ychange
car(carX, carY)
pygame.display.update()
clock.tick(60)
pygame.quit()
gameLoop()
期待您的帮助并出价感谢!
【问题讨论】:
“def”的东西被称为函数。你的方法根本行不通,因为主应用程序循环是递归调用的。 【参考方案1】:您必须在函数car
中使用参数x
和y
而不是carX
和carY
:
def car(x,y):
wn.blit(carImg, (x, y))
【讨论】:
以上是关于PyGame 游戏在幕后工作,但图像不会移动的主要内容,如果未能解决你的问题,请参考以下文章