用pygame实现左右移动,可是无法上下移动,不知道哪里有问题
import pygameimport sys
class Rocket:
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((1300,600))
self.bg_color = (230,230,230)
pygame.display.set_caption('rocket')
self.image = pygame.image.load('E:\python_work\pratice\image\ship.bmp')
self.image_rect = self.image.get_rect()
self.screen_rect = self.screen.get_rect()
self.image_rect.midbottom = self.screen_rect.midbottom
# self.image_rect.centerx = self.screen_rect.centerx
# self.image_rect.centery = self.screen_rect.centery
self.moving_right = False
self.moving_left = False
self.moving_up = False
self.moving_down = False
self.speed = 1.5
def _blit_image(self):
self.screen.blit(self.image,self.image_rect)
def _check_event(self):
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
self.moving_right = True
elif event.key == pygame.K_LEFT:
self.moving_left = True
elif event.key == pygame.K_UP:
self.moving_up == True
elif event.key == pygame.K_DOWN:
self.moving_down == True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
self.moving_right = False
elif event.key == pygame.K_LEFT:
self.moving_left = False
elif event.key == pygame.K_UP:
self.moving_up == False
elif event.key == pygame.K_DOWN:
self.moving_down == False
elif event.type == pygame.QUIT:
sys.exit()
def _moving(self):
self.x = float(self.image_rect.x)
self.y = float(self.image_rect.y)
if self.moving_down and self.image_rect.bottom < self.screen_rect.bottom:
self.y += self.speed
if self.moving_up and self.image_rect.top > 0:
self.y -= self.speed
if self.moving_right and self.image_rect.right < self.screen_rect.right:
self.x += self.speed
if self.moving_left and self.image_rect.left > 0:
self.x -= self.speed
self.image_rect.x = self.x
self.image_rect.y = self.y
# print("left= %d,right= %d" % (self.image_rect.left,self.image_rect.right))
# print("top= %d,bottom= %d" % (self.image_rect.top,self.image_rect.bottom))
def _update_screen(self):
self.screen.fill(self.bg_color)
self._blit_image()
pygame.display.flip()
def run_game(self):
print("left= %d,right= %d" % (self.image_rect.left,self.image_rect.right))
print("top= %d,bottom= %d" % (self.image_rect.top,self.image_rect.bottom))
self._check_event()
self._moving()
print("left= %d,right= %d" % (self.image_rect.left,self.image_rect.right))
print("top= %d,bottom= %d" % (self.image_rect.top,self.image_rect.bottom))
self._blit_image()
self._update_screen()
while True:
self._check_event()
self._moving()
self._blit_image()
self._update_screen()
if __name__ == '__main__':
rocket = Rocket()
rocket.run_game()
_check_event()函数中 self.moving_up == False多打了一个“=”
页:
[1]