注:本题目为书籍 Python 编程 从入门到实践 练习题
1. 代码
1.1 设置部分:
import pygame
class RocketSettings:
def __init__(self):
self.dis_width = 1000
self.dis_height = 600
self.dis_color = (255, 255, 255)
self.moving_speed = 1.5
1.2 图片参数部分:
import pygame
class RocketImages:
def __init__(self, rocket_pos):
self.screen = rocket_pos.screen
self.settings = rocket_pos.settings
self.screen_rect = rocket_pos.screen.get_rect()
self.image = pygame.image.load("images/rocket.bmp")
self.rect = self.image.get_rect()
self.rect.midbottom = self.screen_rect.midbottom
self.moving_right = False
self.moving_left = False
self.moving_up = False
self.moving_down = False
self.x = float(self.rect.x)
self.y = float(self.rect.y)
def pos_update(self):
if self.moving_right and self.rect.right < self.screen_rect.right:
self.x += self.settings.moving_speed
if self.moving_left and self.rect.left > 0:
self.x -= self.settings.moving_speed
if self.moving_up and self.rect.top > 0:
self.y -= self.settings.moving_speed
if self.moving_down and self.rect.bottom < self.screen_rect.bottom:
self.y += self.settings.moving_speed
self.rect.x = self.x
self.rect.y = self.y
def blitrocket(self):
self.screen.blit(self.image, self.rect)
图片:
下载链接
参考图:
1.3 主程序部分:
import sys
import pygame
from Rocket_setting import RocketSettings
from Rocket_images import RocketImages
class RocketMain:
def __init__(self):
pygame.init()
self.settings = RocketSettings()
self.screen = pygame.display.set_mode((self.settings.dis_width, self.settings.dis_height))
pygame.display.set_caption("RocketGame")
self.rocket_image = RocketImages(self)
def rocket_run(self):
while True:
self._check_events()
self.rocket_image.pos_update()
self._update_screen()
def _check_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _update_screen(self):
self.screen.fill(self.settings.dis_color)
self.rocket_image.blitrocket()
pygame.display.flip()
def _check_keydown_events(self, event):
if event.key == pygame.K_RIGHT:
self.rocket_image.moving_right = True
elif event.key == pygame.K_LEFT:
self.rocket_image.moving_left = True
elif event.key == pygame.K_UP:
self.rocket_image.moving_up = True
elif event.key == pygame.K_DOWN:
self.rocket_image.moving_down = True
elif event.key == pygame.K_q:
sys.exit()
def _check_keyup_events(self, event):
if event.key == pygame.K_RIGHT:
self.rocket_image.moving_right = False
if event.key == pygame.K_LEFT:
self.rocket_image.moving_left = False
if event.key == pygame.K_UP:
self.rocket_image.moving_up = False
if event.key == pygame.K_DOWN:
self.rocket_image.moving_down = False
if __name__ == '__main__':
rocket = RocketMain()
rocket.rocket_run()
2. 实现效果
2.1 界面图片
### 2.1 演示效果