模仿学习小游戏外星人入侵-Python学习,体会“函数”编程
游戏类如下:
1 # !/usr/bin/python 2 # -*- coding:utf-8 -*- 3 """ 4 Author :ZFH 5 File :alien.py 6 Software :PyCharm 7 Datetime :2019-01-14 17:31 8 Version :v1.0 9 Funciton : 10 """ 11 import pygame 12 from pygame.sprite import Sprite 13 14 15 class Alien(Sprite): 16 """表示单个外星人的类""" 17 18 def __init__(self, ai_settings, screen): 19 """初始化外星人并设置其其实位置""" 20 21 super(Alien, self).__init__() 22 self.screen = screen 23 self.ai_settings = ai_settings 24 25 # 加载外星人图像,并设置其rect属性 26 self.image = pygame.image.load("images/alien.png") 27 self.rect = self.image.get_rect() 28 29 # 每个外星人最初都在屏幕左上角附近 30 self.rect.x = self.rect.width 31 self.rect.y = self.rect.height 32 33 # 存储外星人得准确位置 34 self.x = float(self.rect.x) 35 36 def blitme(self): 37 38 """在指定位置绘制外星人""" 39 self.screen.blit(self.image, self.rect) 40 41 def check_edges(self): 42 """如果外星人位于屏幕边缘,就返回True""" 43 screen_rect = self.screen.get_rect() 44 if self.rect.right >= screen_rect.right: 45 return True 46 elif self.rect.left <= 0: 47 return True 48 49 def update(self): 50 # """向右移动外星人""" 51 # self.x += self.ai_settings.alien_speed_factor 52 # self.rect.x = self.x 53 """向右或者向左移动外星人""" 54 self.x += (self.ai_settings.alien_speed_factor * self.ai_settings.fleet_direction) 55 self.rect.x = self.x
1 # !/usr/bin/python 2 # -*- coding:utf-8 -*- 3 """ 4 Author :ZFH 5 File :alien_invasion.py 6 Software :PyCharm 7 Datetime :2019-01-11 15:10 8 Version :v1.0 9 Funciton : 10 """ 11 12 import sys,pygame 13 from settings import Settings 14 from ship import Ship 15 import game_functions 16 from pygame.sprite import Group 17 from alien import Alien 18 from game_stats import GameStats 19 from button import Button 20 from scoreboard import ScoreBoard 21 22 def run_game(): 23 # 初始化游戏并创建一个屏幕对象 24 # 初始化pygame、设置屏幕对象 25 26 pygame.init() 27 28 ai_settings = Settings() 29 screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height)) 30 31 pygame.display.set_caption('zfh') 32 33 # 创建play按钮 34 play_button = Button(ai_settings, screen, "Play") 35 36 # 创建一个用于存储游戏统计信息的实例,并创建记分牌 37 stats = GameStats(ai_settings) 38 scoreboard = ScoreBoard(ai_settings, screen, stats) 39 40 # 创建一艘飞船 41 ship = Ship(ai_settings, screen) 42 43 # 设置背景颜色 44 # bg_color = (230, 230, 230) 45 46 # 创建一个用于存储子弹的编组 47 bullets = Group() 48 49 # 创建一个外星人 50 # alien = Alien(ai_settings, screen) 51 52 # 创建外星人群 53 aliens = Group() 54 game_functions.create_fleet(ai_settings, screen, ship, aliens) 55 56 # 开始游戏的主循环 57 58 while True: 59 # 监视键盘和鼠标事件 60 # for event in pygame.event.get(): 61 # if event.type == pygame.QUIT: 62 # sys.exit() 63 # check_functions.check_events() 64 # # 每次循环时都重绘制屏幕 65 # screen.fill(ai_settings.bg_color) 66 # ship.blitme() 67 # 68 # # 让最近绘画的屏幕可见 69 # pygame.display.flip() 70 71 game_functions.check_events(ai_settings, screen, stats, scoreboard, play_button, ship, aliens, bullets) 72 73 74 if stats.game_active: 75 76 ship.update() 77 78 ## 更新子弹的位置 79 # bullets.update() 80 # 81 # # 删除已消失的子弹 82 # for bullet in bullets.copy(): 83 # if bullet.rect.bottom <= 0: 84 # bullets.remove(bullet) 85 game_functions.update_bullets(ai_settings, screen, stats, scoreboard, ship, aliens, bullets) 86 87 game_functions.update_aliens(ai_settings, stats, screen, scoreboard, ship, aliens, bullets) 88 89 game_functions.update_screen(ai_settings, screen, stats,scoreboard, ship, aliens, bullets, play_button) 90 91 # game_functions.update_bullets(bullets) 92 93 run_game()
1 # !/usr/bin/python 2 # -*- coding:utf-8 -*- 3 """ 4 Author :ZFH 5 File :bullet.py 6 Software :PyCharm 7 Datetime :2019-01-14 15:35 8 Version :v1.0 9 Funciton : 10 """ 11 import pygame 12 from pygame.sprite import Sprite 13 14 class Bullet(Sprite): 15 """一个对飞船发射子弹进行管理的类""" 16 17 def __init__(self,ai_settings, screen, ship, *args, **kwargs): 18 """在飞船所处位置创建一个子弹对象""" 19 super(Bullet, self).__init__() 20 self.screen = screen 21 22 #在(0,0)处创建一个表示子弹的矩形,再设置正确的位置 23 self.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_height) 24 self.rect.centerx = ship.rect.centerx 25 self.rect.top = ship.rect.top 26 27 #存储用小数表示的子弹位置 28 self.y = float(self.rect.y) 29 30 self.color = ai_settings.bullet_color 31 self.speed_factor = ai_settings.bullet_speed_factor 32 33 def update(self): 34 """向上移动子弹""" 35 # 更新表示子弹位置的小数值 36 self.y -= self.speed_factor 37 # 更新表示子弹的rect的位置 38 self.rect.y = self.y 39 40 def draw_bullet(self): 41 """在平面上绘制子弹""" 42 pygame.draw.rect(self.screen, self.color, self.rect)
1 # !/usr/bin/python 2 # -*- coding:utf-8 -*- 3 """ 4 Author :ZFH 5 File :button.py 6 Software :PyCharm 7 Datetime :2019-01-24 10:24 8 Version :v1.0 9 Funciton : 10 """ 11 import pygame.font 12 13 class Button(): 14 def __init__(self, ai_settings, screen, msg): 15 """初始化按钮的属性""" 16 self.screen = screen 17 self.screen_rect = screen.get_rect() 18 19 # 设置按钮的尺寸和其他属性 20 self.width, self.height = 200, 50 21 self.button_color = (0, 255, 0) 22 self.text_color = (255, 255, 255) 23 self.font = pygame.font.SysFont(None, 48) 24 25 # 创建按钮的rect对象,并使其居中 26 self.rect = pygame.Rect(0, 0, self.width, self.height) 27 self.rect.center = self.screen_rect.center 28 29 # 按钮的标签只需创建一次 30 self.prep_msg(msg) 31 32 def prep_msg(self, msg): 33 """将msg渲染为图像,并使其在按钮上居中""" 34 self.msg_image = self.font.render(msg, True, self.text_color, self.button_color) 35 self.msg_image_rect = self.msg_image.get_rect() 36 self.msg_image_rect.center = self.rect.center 37 38 def draw_button(self): 39 # 绘制一个用颜色填充的按钮,在绘制文本 40 self.screen.fill(self.button_color, self.rect) 41 self.screen.blit(self.msg_image, self.msg_image_rect)
1 # !/usr/bin/python 2 # -*- coding:utf-8 -*- 3 """ 4 Author :ZFH 5 File :game_functions.py 6 Software :PyCharm 7 Datetime :2019-01-11 16:46 8 Version :v1.0 9 Funciton : 10 """ 11 import sys,pygame 12 from bullet import Bullet 13 from alien import Alien 14 from time import sleep 15 16 def check_events(ai_settings, screen, stats, scoreboard, paly_button, ship, aliens, bullets, *args, **kwargs): 17 18 """ 19 响应按键和鼠标事件 20 """ 21 for event in pygame.event.get(): 22 if event.type == pygame.QUIT: 23 sys.exit() 24 elif event.type == pygame.KEYDOWN: 25 # if event.key == pygame.K_RIGHT: 26 # # # 向右移动飞船 27 # # ship.rect.centerx += 1 28 # ship.moving_right = True 29 # elif event.key == pygame.K_LEFT: 30 # # 向左移动飞船 31 # ship.moving_left = True 32 check_keydown_events(event, ai_settings, screen, ship, bullets) 33 34 elif event.type == pygame.KEYUP: 35 # if event.key == pygame.K_RIGHT: 36 # ship.moving_right = False 37 # elif event.key == pygame.K_LEFT: 38 # ship.moving_left = False 39 check_keyup_events(event, ship) 40 # 鼠标点击play按钮事件 41 elif event.type == pygame.MOUSEBUTTONDOWN: 42 mouse_x, mouse_y = pygame.mouse.get_pos() 43 check_play_button(ai_settings, screen, stats, scoreboard, paly_button, ship, aliens, bullets, mouse_x, mouse_y) 44 45 46 47 def check_keydown_events(event, ai_settings, screen, ship, bullets, *args, **kwargs): 48 49 """响应按键""" 50 if event.key == pygame.K_RIGHT: 51 ship.moving_right = True 52 elif event.key == pygame.K_LEFT: 53 ship.moving_left = True 54 elif event.key == pygame.K_UP: 55 ship.moving_up = True 56 elif event.key == pygame.K_DOWN: 57 ship.moving_down = True 58 elif event.key == pygame.K_SPACE: 59 fire_bullet(ai_settings, screen, ship, bullets) 60 elif event.key == pygame.K_q: 61 sys.exit() 62 63 64 def fire_bullet(ai_settings, screen, ship, bullets, *args, **kwargs): 65 """如果没有达到限制,就发射一颗子弹""" 66 # 创建一颗子弹,并将其加入到编组bullets中 67 if len(bullets) < ai_settings.bullets_allowed: 68 new_bullet = Bullet(ai_settings, screen, ship) 69 bullets.add(new_bullet) 70 71 72 def check_keyup_events(event, ship, *args, **kwargs): 73 """响应松开""" 74 if event.key == pygame.K_RIGHT: 75 ship.moving_right = False 76 elif event.key == pygame.K_LEFT: 77 ship.moving_left = False 78 elif event.key == pygame.K_UP: 79 ship.moving_up = False 80 elif event.key == pygame.K_DOWN: 81 ship.moving_down = False 82 83 84 def update_screen(ai_settings, screen, stats, scoreboard, ship, aliens, bullets, play_button, *args, **kwargs): 85 """更新屏幕上的图像,并切换到新屏幕""" 86 # 每次循环时都重绘屏幕 87 screen.fill(ai_settings.bg_color) 88 for bullet in bullets.sprites(): 89 bullet.draw_bullet() 90 ship.blitme() 91 92 # 让外星人出现在屏幕上 93 # alien.blitme() 94 95 #绘制外星人编组 96 aliens.draw(screen) 97 98 # 显示得分 99 scoreboard.show_score() 100 101 # 如果游戏处于非活动状态,就绘制Play按钮 102 if not stats.game_active: 103 play_button.draw_button() 104 105 # 让最近绘制的屏幕可见 106 pygame.display.flip() 107 108 109 def update_bullets(ai_settings, screen, stats, scoreboard, ship, aliens, bullets): 110 """更新子弹的位置,并删除已消失的子弹""" 111 # 更新子弹的位置 112 bullets.update() 113 114 # 删除已消失的子弹 115 for bullet in bullets.copy(): 116 if bullet.rect.bottom <= 0 : 117 bullets.remove(bullet) 118 119 check_bullet_alien_collisions(ai_settings, screen, stats, scoreboard, ship, aliens, bullets) 120 121 122 def check_bullet_alien_collisions(ai_settings, screen, stats, scoreboard, ship, aliens, bullets): 123 """响应子弹和外星人的碰撞""" 124 # 删除发生碰撞的子弹和外星人 125 # 检查是否有子弹击中了外星人 126 # 如果是这样,就删除相应的子弹和外星人 127 collisions = pygame.sprite.groupcollide(bullets, aliens, True, True) 128 129 if collisions: 130 for aliens in collisions.values(): 131 stats.score += ai_settings.alien_points * len(aliens) 132 scoreboard.prep_score() 133 check_high_score(stats, scoreboard) 134 135 if len(aliens) == 0: 136 # 删除现有的子弹,"加快游戏节奏",并新建一群外星人,游戏就提高一个等级 137 bullets.empty() 138 ai_settings.increase_speed() 139 140 # 提高等级 141 stats.level += 1 142 scoreboard.prep_level() 143 144 create_fleet(ai_settings, screen, ship, aliens) 145 146 147 def check_high_score(stats, scorebord): 148 """检查是否诞生了新的最高得分""" 149 if stats.score > stats.high_score: 150 stats.high_score = stats.score 151 scorebord.prep_high_score() 152 153 def get_number_aliens_x(ai_settings, alien_width): 154 """计算每行可容纳多少个外星人""" 155 available_space_x = ai_settings.screen_width - 2 * alien_width 156 number_aliens_x = int(available_space_x / (2 * alien_width)) 157 return number_aliens_x 158 159 def create_alien(ai_settings, screen, aliens, alien_number, row_number): 160 """创建一个外星人并将其放在当前行""" 161 alien = Alien(ai_settings, screen) 162 alien_width = alien.rect.width 163 alien.x = alien_width + 2 * alien_width * alien_number 164 alien.rect.x = alien.x 165 alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number 166 aliens.add(alien) 167 168 def get_number_rows(ai_settings, ship_height, alien_height): 169 """计算屏幕可容纳多少行外星人""" 170 available_space_y = (ai_settings.screen_height - (3 * alien_height) - ship_height) 171 number_rows = int(available_space_y / (2 * alien_height)) 172 return number_rows 173 174 def create_fleet(ai_settings, screen, ship, aliens): 175 """创建外星人群""" 176 # 创建一个外行人,并计算一行可容纳多少各外星人 177 # 外星人间距为外星人宽度 178 alien = Alien(ai_settings, screen) 179 # alien_width = alien.rect.width 180 # available_space_x = ai_settings.screen_width - 2 * alien_width 181 # number_aliens_x = int(available_space_x / (2 * alien_width)) 182 number_aliens_x = get_number_aliens_x(ai_settings, alien.rect.width) 183 number_rows = get_number_rows(ai_settings, ship.rect.height, alien.rect.height) 184 185 # 创建外星人群 186 for row_number in range(number_rows): 187 # 创建第一行外星人 188 for alien_number in range(number_aliens_x): 189 # # 创建一个外星人并将其加入当前行 190 # alien = Alien(ai_settings, screen) 191 # alien.x = alien_width + 2 * alien_width * alien_number 192 # alien.rect.x = alien.x 193 # aliens.add(alien) 194 create_alien(ai_settings, screen, aliens, alien_number, row_number) 195 196 def check_fleet_edges(ai_settings, aliens): 197 """有外星人到达边缘时采取相应得措施""" 198 for alien in aliens.sprites(): 199 if alien.check_edges(): 200 change_fleet_direction(ai_settings, aliens) 201 break 202 203 def change_fleet_direction(ai_settings, aliens): 204 """将整群外星人下移,并改变他们的方向""" 205 for alien in aliens.sprites(): 206 alien.rect.y += ai_settings.fleet_drop_speed 207 208 ai_settings.fleet_direction *= -1 209 210 211 def ship_hit(ai_settings, stats, screen, scoreboard, ship, aliens, bullets): 212 """响应外星人撞到飞船""" 213 if stats.ships_left > 0: 214 # 将ships_left减1 215 stats.ships_left -= 1 216 217 # 更新记分牌 218 scoreboard.prep_ships() 219 220 # 清空外星人到列表和子弹列表 221 aliens.empty() 222 bullets.empty() 223 224 # 创建一群新的外星人,并将飞船放到屏幕低端中央 225 create_fleet(ai_settings, screen, ship, aliens) 226 227 ship.center_ship() 228 229 # 暂停 230 sleep(0.5) 231 else: 232 stats.game_active = False 233 print("Game Over !!!") 234 pygame.mouse.set_visible(True) 235 236 def check_aliens_bottom(ai_setting, stats, screen, scoreboard, ship, aliens, bullets): 237 """检查是否有外星人到达了屏幕底端""" 238 screen_rect = screen.get_rect() 239 for alien in aliens.sprites(): 240 if alien.rect.bottom >= screen_rect.bottom: 241 # 像飞船被撞到一样处理 242 ship_hit(ai_setting, stats, screen, scoreboard, ship, aliens, bullets) 243 break 244 245 246 def update_aliens(ai_settings, stats, screen, scoreboard, ship, aliens, bullets): 247 """更新外星人群中所有外星人得位置""" 248 """ 249 检查是否有外星人位于屏幕边缘,并更新整群外星人的位置 250 """ 251 check_fleet_edges(ai_settings, aliens) 252 253 aliens.update() 254 255 # 检测外星人和飞船之间的碰撞 256 if pygame.sprite.spritecollideany(ship, aliens): 257 ship_hit(ai_settings, stats, screen, scoreboard, ship, aliens, bullets) 258 print("Ship hit !!!") 259 260 # 检查是否有外星人到达屏幕低端 261 check_aliens_bottom(ai_settings, stats, screen, scoreboard, ship, aliens, bullets) 262 263 def check_play_button(ai_settings, screen, stats, scoreboard, paly_button, ship, aliens, bullets, mouse_x, mouse_y): 264 """在玩家点击play按钮时开始新游戏""" 265 button_clicked = paly_button.rect.collidepoint(mouse_x, mouse_y) 266 267 # if paly_button.rect.collidepoint(mouse_x, mouse_y): 268 if button_clicked and not stats.game_active: 269 270 #重置游戏设置 271 ai_settings.initialize_dynamic_settings() 272 273 # 隐藏光标 274 pygame.mouse.set_visible(False) 275 # 重置游戏统计信息 276 stats.reset_stats() 277 stats.game_active = True 278 279 # 重置记分牌图像 280 scoreboard.prep_score() 281 scoreboard.prep_high_score() 282 scoreboard.prep_level() 283 scoreboard.prep_ships() 284 285 # 清空外星人到列表和子弹列表 286 aliens.empty() 287 bullets.empty() 288 289 # 创建一群新的外星人,并将飞船放到屏幕低端中央 290 create_fleet(ai_settings, screen, ship, aliens) 291 292 ship.center_ship()
1 # !/usr/bin/python 2 # -*- coding:utf-8 -*- 3 """ 4 Author :ZFH 5 File :game_stats.py 6 Software :PyCharm 7 Datetime :2019-01-24 9:29 8 Version :v1.0 9 Funciton : 10 """ 11 12 class GameStats(): 13 """跟踪游戏的统计信息""" 14 15 def __init__(self, ai_settings): 16 """初始化统计信息""" 17 self.ai_settings = ai_settings 18 self.reset_stats() 19 # 游戏杠启动时处于活动状态 20 self.game_active = False 21 # 在任何情况下都不重置最高得分 22 self.high_score = 0 23 24 def reset_stats(self): 25 """初始化在游戏运行期间可能变化的统计信息""" 26 self.ships_left = self.ai_settings.ship_limit 27 self.score = 0 28 self.level = 1
1 # !/usr/bin/python 2 # -*- coding:utf-8 -*- 3 """ 4 Author :ZFH 5 File :scoreboard.py 6 Software :PyCharm 7 Datetime :2019-01-24 11:24 8 Version :v1.0 9 Funciton : 10 """ 11 import pygame.font 12 from pygame.sprite import Group 13 from ship import Ship 14 15 class ScoreBoard(): 16 """显示得分信息的类""" 17 18 def __init__(self,ai_settings, screen, stats): 19 """初始化显示得分涉及的属性""" 20 21 self.screen = screen 22 self.screen_rect = screen.get_rect() 23 self.ai_settings = ai_settings 24 self.stats = stats 25 26 # 显示得分信息时使用的字体设置 27 self.text_color = (30, 30, 30) 28 self.font = pygame.font.SysFont(None, 48) 29 30 # 准备初始化得分图像,准备最高得分 的图像 31 self.prep_score() 32 self.prep_high_score() 33 34 # 显示游戏等级 35 self.prep_level() 36 37 # 显示飞船的数量 38 self.prep_ships() 39 40 def prep_ships(self): 41 """显示还剩余多少艘飞船""" 42 self.ships = Group() 43 for ship_number in range(self.stats.ships_left): 44 ship = Ship(self.ai_settings, self.screen) 45 ship.rect.x = 10 + ship_number * ship.rect.width 46 ship.rect.y = 10 47 self.ships.add_internal(ship) 48 49 def prep_level(self): 50 """将游戏等级转换为一副渲染的图像""" 51 self.level_image = self.font.render(str(self.stats.level), True, self.text_color, self.ai_settings.bg_color) 52 53 # 将等级放在得分下方 54 self.level_rect = self.level_image.get_rect() 55 self.level_rect.right = self.score_rect.right 56 self.level_rect.top = self.score_rect.bottom + 10 57 58 def prep_score(self): 59 """将得分转换为一副渲染的图像""" 60 rounded_score = int(round(self.stats.score, -1)) 61 # score_str = str(self.stats.score) 62 score_str = "{:,}".format(rounded_score) 63 self.score_image = self.font.render(score_str, True,self.text_color, self.ai_settings.bg_color) 64 65 # 将得分放在屏幕右上角 66 self.score_rect = self.score_image.get_rect() 67 self.score_rect.right = self.screen_rect.right - 20 68 self.score_rect.top = 20 69 70 def prep_high_score(self): 71 """将最高得分转换为渲染图像""" 72 high_score = int(round(self.stats.high_score, -1)) 73 high_score_str = "{:,}".format(high_score) 74 self.prep_high_image = self.font.render(high_score_str, True, self.text_color, self.ai_settings.bg_color) 75 76 # 将最高得分放在屏幕顶部中央 77 self.high_score_rect = self.prep_high_image.get_rect() 78 self.high_score_rect.centerx = self.screen_rect.centerx 79 self.high_score_rect.top = self.score_rect.top 80 81 def show_score(self): 82 """在屏幕上显示得分""" 83 self.screen.blit(self.score_image, self.score_rect) 84 # 在屏幕上显示最高得分 85 self.screen.blit(self.prep_high_image, self.high_score_rect) 86 # 在屏幕上方显示游戏等级 87 self.screen.blit(self.level_image, self.level_rect) 88 89 # 绘制飞船 90 self.ships.draw(self.screen)
1 # !/usr/bin/python 2 # -*- coding:utf-8 -*- 3 """ 4 Author :ZFH 5 File :settings.py 6 Software :PyCharm 7 Datetime :2019-01-11 15:23 8 Version :v1.0 9 Funciton : 10 """ 11 class Settings(): 12 """ 13 存储《外星人入侵》的所有设置的类 14 """ 15 def __init__(self): 16 """初始化游戏静态设置""" 17 """ 18 初始化游戏设置 19 """ 20 # 屏幕设置 21 self.screen_width = 1200 22 self.screen_height = 800 23 self.bg_color = (255, 255, 255) 24 25 # 设置飞机的速度 26 self.ship_speed_factor = 3 27 self.ship_limit = 3 28 29 # 子弹射击 30 self.bullet_speed_factor = 1 31 self.bullet_width = 5 32 self.bullet_height = 5 33 self.bullet_color = (236, 28, 36) 34 self.bullets_allowed = 10 35 36 # 外星人设置 37 self.alien_speed_factor = 1 38 self.fleet_drop_speed = 2 39 # fleet_direction为 1 表示向右移动,为 -1 表示向左移动 40 self.fleet_direction = -1 41 42 # 以什么样的速度加快游戏节凑 43 self.speedup_scale =1.1 44 45 # 外星人点数的提高速度 46 self.score_scale = 1.5 47 48 self.initialize_dynamic_settings() 49 50 def initialize_dynamic_settings(self): 51 """初始化随游戏进行而设置变化的设置""" 52 self.ship_speed_factor = 1.5 53 self.bullet_speed_factor = 3 54 self.alien_speed_factor = 1 55 56 # fleet_direction为1表示享有;为-1表示向左 57 self.fleet_direction = 1 58 59 # 记分 60 self.alien_points = 50 61 62 def increase_speed(self): 63 """提高速度设置""" 64 self.ship_speed_factor *= self.speedup_scale 65 self.bullet_speed_factor *= self.speedup_scale 66 self.alien_speed_factor *= self.speedup_scale 67 68 self.alien_points = int(self.alien_points * self.score_scale) 69 print(self.alien_points)
1 # !/usr/bin/python 2 # -*- coding:utf-8 -*- 3 """ 4 Author :ZFH 5 File :ship.py 6 Software :PyCharm 7 Datetime :2019-01-11 15:42 8 Version :v1.0 9 Funciton : 10 """ 11 import pygame 12 13 class Ship(): 14 15 def __init__(self,ai_settings, screen, *args, **kwargs): 16 """初始化飞船并设置其初始位置""" 17 super(Ship, self).__init__() 18 19 self.screen = screen 20 self.ai_settings = ai_settings 21 # 加载飞船图像并获取其外接矩形 22 self.image = pygame.image.load('images/ship1.png') 23 self.rect = self.image.get_rect() 24 self.screen_rect = screen.get_rect() 25 26 # 将每艘飞船放在屏幕底部中央 27 self.rect.centerx = self.screen_rect.centerx #将飞船中心的x坐标设置为表示屏幕的矩形的属性centerx 28 self.rect.bottom = self.screen_rect.bottom #注意屏幕边缘的表示:top,bottom,left,right 29 #将每艘飞船放置在屏幕底端中央位置,在pygame中,原点(0,0)位于屏幕左上角 30 31 # 在飞船的属性centerx中存储小数值 32 self.center = float(self.rect.centerx) 33 self.bottom = float(self.rect.bottom) 34 35 # 移动标志 36 self.moving_right = False 37 self.moving_left = False 38 self.moving_up = False 39 self.moving_down = False 40 41 def blitme(self): 42 """在指定位置绘制飞船""" 43 self.screen.blit(self.image, self.rect) 44 45 def update(self): 46 """ 47 根据移动标志调整飞船位置 48 """ 49 # 更新飞船的center值,而不是rect,self.rect.right < self.screen_rect.right限制飞船的右侧位置。 50 if self.moving_right and self.rect.right < self.screen_rect.right: 51 # self.rect.centerx += 1 52 self.center += self.ai_settings.ship_speed_factor 53 # self.rect.left > 0 限制飞船右侧得位置 54 if self.moving_left and self.rect.left >= 0: 55 # self.rect.centerx -= 1 56 self.center -= self.ai_settings.ship_speed_factor 57 58 if self.moving_up and self.rect.top >= 0 : 59 self.bottom -= self.ai_settings.ship_speed_factor 60 61 if self.moving_down and self.rect.bottom < self.screen_rect.bottom: 62 self.bottom += self.ai_settings.ship_speed_factor 63 64 self.rect.centerx = self.center 65 self.rect.bottom = self.bottom 66 67 def center_ship(self): 68 """让飞船在屏幕上居中""" 69 self.center = self.screen_rect.centerx
效果如下,飞船太难看了.......