系列文章目录
第一章:武装飞船
06:让飞船移动
目录
系列文章目录
第一章:武装飞船
06:让飞船移动
一、驾驶飞船
二、让飞船移动
1.代码及注释(笔记)
A:修改文件:game_functions.py
B:修改文件:alien_invasion.py
C:修改文件:ship.py
2.运行效果
A.按下右箭头键后向右移动,再按下左箭头键时停止
B.按下左箭头键后向右移动,再按下右箭头键时停止
一、驾驶飞船
下面来让玩家能够左右移动飞船。我们将编写代码,在用户按左或右箭头键时做出响应。我们将首先专注于向右移动,再使用同样的原理来控制向左移动。通过这样做,你将学会如何控制屏幕图像的移动。
二、让飞船移动
1.代码及注释(笔记)
(笔记在代码的注释中!!!)
A:修改文件:game_functions.py
#渗透小红帽python的学习之路#外星人入侵小游戏#game_functions.py#存储让游戏运行的函数import sysimport pygamedef check_events(ship): # 在玩家按右箭头时需要将飞船向右移动,# 所以给函数加上了形参shipfor event in pygame.event.get(): # 监听键盘和鼠标事件if event.type == pygame.QUIT:sys.exit()#修改alien_invasion.py,使其导入game_functions#并将事件循环替换为对函数check_events()的调用elif event.type == pygame.KEYDOWN:if event.key == pygame.K_RIGHT:#移动飞船ship.moving_right = True#玩家按下右箭头键时标志设为trueelif event.key == pygame.K_LEFT:ship.moving_left = True# 玩家按下左箭头键时标志设为trueelif event.type == pygame.KEYUP:if event.key == pygame.K_RIGHT:ship.moving_right = False# 玩家松开右箭头键时标志设为falseelif event.key == pygame.K_LEFT:ship.moving_left = False# 玩家松开左箭头键时标志设为falsedef update_screen(ai_settings,screen,ship):# 将更新屏幕的代码移到此处screen.fill(ai_settings.bg_color) # 每次循环都会重绘屏幕ship.blitme() # 每次循环时重新绘制飞船pygame.display.flip() # 让最近绘制的屏幕可见# 然后修改alien_invasion.py
B:修改文件:alien_invasion.py
#渗透小红帽python的学习之路#外星人入侵小游戏#game_functions.py#存储让游戏运行的函数import sysimport pygamedef check_events(ship): # 在玩家按右箭头时需要将飞船向右移动,# 所以给函数加上了形参shipfor event in pygame.event.get(): # 监听键盘和鼠标事件if event.type == pygame.QUIT:sys.exit()#修改alien_invasion.py,使其导入game_functions#并将事件循环替换为对函数check_events()的调用elif event.type == pygame.KEYDOWN:if event.key == pygame.K_RIGHT:#移动飞船ship.moving_right = True#玩家按下右箭头键时标志设为trueelif event.key == pygame.K_LEFT:ship.moving_left = True# 玩家按下左箭头键时标志设为trueelif event.type == pygame.KEYUP:if event.key == pygame.K_RIGHT:ship.moving_right = False# 玩家松开右箭头键时标志设为falseelif event.key == pygame.K_LEFT:ship.moving_left = False# 玩家松开左箭头键时标志设为falsedef update_screen(ai_settings,screen,ship):# 将更新屏幕的代码移到此处screen.fill(ai_settings.bg_color) # 每次循环都会重绘屏幕ship.blitme() # 每次循环时重新绘制飞船pygame.display.flip() # 让最近绘制的屏幕可见# 然后修改alien_invasion.py
C:修改文件:ship.py
#渗透小红帽python的学习之路#外星人入侵小游戏#ship.py#管理飞船行为的类import pygameclass Ship():def __init__(self,screen):#参数screen用来指定将飞船绘制到什么地方self.screen = screen#加载飞船图片并获取其外接矩形self.image = pygame.image.load('F:/PythonProject/pythongame/images/ship.bmp')#复制图片路径后需要将斜杠改为反斜杠self.rect = self.image.get_rect()self.screen_rect = screen.get_rect()#将每艘新飞船放在屏幕中间self.rect.centerx = self.screen_rect.centerxself.rect.bottom = self.screen_rect.bottom# 移动标志,玩家按下右箭头键时,将标志设为true,松开时重新设置为falseself.moving_right = Falseself.moving_left = False# 方法update()检查标志状态,标志为true时调整飞船位置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)
2.运行效果
A.按下右箭头键后向右移动,再按下左箭头键时停止
B.按下左箭头键后向左移动,再按下右箭头键时停止
有什么不懂的地方在评论区留言哦!希望我的文章能对你有所帮助,如果喜欢我的文章,请点赞收藏并关注!你的认可是对我创作最大的鼓励!