为了保证文章的原创性,我决定用自己理解的语言开始后面的学习笔记。
1.4.3 左右移动
之前我们添加了飞船向右移动功能,同时对持续移动做了更新和改进。下面我们该添加向左移动飞船的功能了。需要修改ship类和函数check_events()。
先来修改ship类:
import pygame
class Ship():
def __init__(self,screen):
#初始化飞船并设置其初始位置
self.screen = screen
# 加载飞船图像并获取其外接矩形
self.image = pygame.image.load('images/ship.png')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
# 将每艘新飞船放在屏幕底部中央
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = self.screen_rect.bottom
#移动标志
self.moving_right = False
self.moving_left = False
def update(self):
#根据移动标志调整飞船的位置
if self.moving_right:
self.rect.centerx += 1
if self.moving_left:
self.rect.centerx -= 1
def blitme(self):
# 在指定位置绘制飞船
self.screen.blit(self.image, self.rect)
这里首先要在init函数中增加向左移动飞船的标志,同时初始化为False。然后修改update函数,当标志为left时,飞船的位置向左移动1。接下来仿照向右移动的功能,我们要修改game_function中的check_events()。
import sys
import pygame
def check_events(ship):
#响应案件和鼠标事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
#判断持续移动
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
#向右移动飞船
ship.moving_right = True
elif event.key == pygame.K_LEFT:
#向左移动飞船
ship.moving_left = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
ship.moving_right = False
elif event.key == pygame.K_LEFT:
ship.moving_left = False
def update_screen(ai_settings,screen,ship):
#每次循环时都重绘屏幕
screen.fill(ai_settings.bg_color)
# 屏幕上绘制飞船#
ship.blitme()
#让最近绘制的屏幕可见#
pygame.display.flip()
下节预告:优化移动功能