|
发表于 2023-9-2 08:13:41
|
显示全部楼层
问题出在事件处理部分的代码上。在按下左右键时,虽然改变了变量 x_speed 的值,但是并没有更新 speed 变量的值。因此,图片的速度没有发生变化。
为了解决这个问题,需要在按下左右键时,更新 speed 变量的值。具体地,当按下右键时,将 x_speed 增加5;当按下左键时,将 x_speed 减少1。然后,将 speed 变量的值设置为 [x_speed, y_speed] 。
以下是修改后的代码:
- import sys
- import pygame
- import os
- from pygame.locals import *
- os.chdir("C:\\Users\\david\\Desktop")
- pygame.init()
- size = width, height = 600, 400
- bg = [255, 255, 255]
- x_speed = 2
- y_speed = 2
- speed = [x_speed, y_speed]
- fullscreen = False
- screen = pygame.display.set_mode(size)
- photo = pygame.image.load("uu.gif")
- position = photo.get_rect()
- while True:
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- sys.exit()
- if event.type == KEYDOWN:
- if event.key == K_RIGHT:
- x_speed += 5
- if event.key == K_LEFT:
- x_speed -= 1
- if event.key == K_h:
- print("hdjhj")
- fullscreen = not fullscreen
- if fullscreen:
- screen = pygame.display.set_mode(size, FULLSCREEN | HWSURFACE)
- else:
- pass
- speed = [x_speed, y_speed] # 更新速度
- position = position.move(speed)
- if position.left < 0 or position.right > width:
- photo = pygame.transform.flip(photo, True, False)
- speed[0] = -speed[0]
- if position.top < 0 or position.bottom > height:
- speed[1] = -speed[1]
- screen.fill(bg)
- screen.blit(photo, position)
- pygame.display.flip()
- pygame.time.delay(10)
复制代码
通过以上修改,当按下左右键时,图片的速度会发生相应的变化。 |
|