编写一个游戏,开始时屏幕中央有一个火箭,而玩家可使用四个方向键上下左右移动火箭。请务必确保火箭不会移到屏幕外面。
主程序:game
import pygame
from settings import Settings
from rocket import Rocket
import functions as f
def run_game():
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode(
(ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_caption("Exercise-rocket")
rocket = Rocket(ai_settings, screen)
while True:
f.check_events(rocket)
rocket.update()
f.update_screen(ai_settings, screen, rocket)
run_game()
设置类:Settings
import pygame
class Settings():
"""存储火箭所有设置的类"""
def __init__(self):
self.screen_width = 1200
self.screen_height = 600
self.bg_color = (230, 230, 230)
self.rocket_speed_factor = 2
火箭类:Rocket
import pygame
class Rocket():
def __init__(self, ai_settings, screen):
self.screen = screen
self.ai_settings = ai_settings
#读取图片
self.image = pygame.image.load('ship.bmp')
self.image_rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
#确定火箭初始位置
self.image_rect.centerx = self.screen_rect.centerx
self.image_rect.centery = self.screen_rect.centery
#移动标志
self.moving_left = False
self.moving_right = False
self.moving_up = False
self.moving_down = False
def update(self):
if self.moving_left and self.image_rect.left > 0:
self.image_rect.centerx -= 1
if self.moving_right and self.image_rect.right < self.screen_rect.right:
self.image_rect.centerx += 1
if self.moving_up and self.image_rect.top > 0:
self.image_rect.centery -= 1
if self.moving_down and self.image_rect.bottom < self.screen_rect.bottom:
self.image_rect.centery += 1
def blitme(self):
self.screen.blit(self.image, self.image_rect)
函数:functions
import sys
import pygame
def check_events(rocket):
"""响应键盘和鼠标事件"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
check_keydown_events(event, rocket)
elif event.type == pygame.KEYUP:
check_keyup_events(event, rocket)
def check_keydown_events(event, rocket):
if event.key == pygame.K_RIGHT:
rocket.moving_right = True
elif event.key == pygame.K_LEFT:
rocket.moving_left = True
elif event.key == pygame.K_UP:
rocket.moving_up = True
elif event.key == pygame.K_DOWN:
rocket.moving_down = True
def check_keyup_events(event, rocket):
if event.key == pygame.K_RIGHT:
rocket.moving_right = False
elif event.key == pygame.K_LEFT:
rocket.moving_left = False
elif event.key == pygame.K_UP:
rocket.moving_up = False
elif event.key == pygame.K_DOWN:
rocket.moving_down = False
def update_screen(ai_settings, screen, rocket):
#填充屏幕
screen.fill(ai_settings.bg_color)
rocket.blitme()
pygame.display.flip()
实际效果:
小结:这个程序其实是模仿书上的程序写的。但编写的过程中遇到许多小问题:
1.对于获取的矩形范围的上部是top而不是up
2.向下移动的时候是小于号,一直没注意找了好久才发现
3.在编写Rocket类时,在编写键盘判断过程中忘记写self,从而出现NameError
4.在check_events()函数中,对编写if语句块内容时忘记附上对象rocket.而导致出错