基於Pygame中Pygame模塊的大戰外星人實戰
一,引言
開發環境:Pycharm
操作系統:Windows 10
Pyhon版本:3.9.9
需要自行安裝Pygame 3(必須)和Python(必須)。
由於多次引用背景參數,建議不要更改文中的背景參數。本文中的圖片用的是相對引用的方式,如果和我圖片位置放置不同的話需要設置絕對引用。
二,主要內容
主要代碼片段:
import sys import pygame # 調用pygame from settings import Settings # 背景和一些必要值 from ship import Ship # 飛船個人設置 import game_function as gf # 移動和發射 # 把整個給gf 並不是按照調用類的方式用的 from pygame.sprite import Group from game_stats import GameStats from Button import Button from Scoreboard import Scoreboard def run_game(): pygame.init() ai_settings = Settings() pygame.display.set_caption('飛機大戰1') stats = GameStats(ai_settings) screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height)) play_button = Button(ai_settings, screen, 'game') sb = Scoreboard(ai_settings, screen, stats) ship = Ship(ai_settings, screen) bullets_left = Group() bullets_down = Group() bullets_right = Group() bullets = Group() aliens = Group() gf.create_fleet(ai_settings, screen ,ship,aliens) while True: gf.check_events(ai_settings, stats, play_button,screen,ship, aliens,bullets,bullets_left,bullets_right, bullets_down) if stats.game_active: ship.update() # 這句很重要必須要調用ship裡的判斷 gf.update_bullets(sb,screen,stats, ship ,ai_settings,aliens, bullets,bullets_left,bullets_right,bullets_down) ##### gf.update_aliens(ai_settings, aliens ,stats, screen, ship ,bullets,bullets_down,bullets_left,bullets_right) gf.update_screen(ai_settings, screen, stats,ship,aliens, bullets,bullets_left,bullets_right,bullets_down,play_button ,sb) run_game()
關於外星飛船的一些調用:
import pygame import sys from pygame.sprite import Sprite class Alien(Sprite): def __init__(self,ai_settings, screen): super(Alien, self).__init__() self.screen = screen self.ai_settings = ai_settings self.image = pygame.image.load('外星飛船.png') self.rect = self.image.get_rect() self.rect.x = self.rect.width self.rect.y = self.rect.height self.x = float(self.rect.x) # 外星人所在位置 def check_edges(self): # 檢測飛船是否碰到墻壁 screen_rect = self.screen.get_rect() if self.rect.right >= screen_rect.right: return True elif self.rect.left <= 0: return True def update(self): self.x += (self.ai_settings.alien_speed_factor*self.ai_settings.fleet_direction) self.rect.x = self.x def blitme(self): self.screen.blit(self.image, self.rect)
關於子彈的一些配置(這裡隻是向前方向的子彈) 其餘各個方向的子彈也是基於這個略改:
import pygame from pygame.sprite import Sprite class Bullet(Sprite): def __init__(self, ai_settings, screen, ship): super(Bullet, self).__init__() # pygame2.7需要這麼寫 self.screen = screen self.rect = pygame.Rect(0,0,ai_settings.bullet_width, ai_settings.bullet_height) self.rect.centerx = ship.rect.centerx self.rect.top = ship.rect.top # 子彈的初始位置 self.y = float(self.rect.y) # 記錄子彈輸出的位置 self.color = ai_settings.bullet_color self.speed_factor = ai_settings.bullet_speed_factor def update(self): self.y -= self.speed_factor # 讓子彈持續往上飛 self.rect.y = self.y def draw_bullet(self): pygame.draw.rect(self.screen, self.color, self.rect)
關於可操控飛船的一些設置(如果要改變背景的長寬比,需要改變飛船的重置位置):
import pygame class Ship(): def __init__(self, ai_settings, screen): self.screen = screen self.ai_settings = ai_settings self.image = pygame.image.load('小飛機.png') self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() self.rect.bottom = self.screen_rect.bottom self.rect.centerx = self.screen_rect.centerx # x # self.rect.centery = self.screen_rect.centery # y self.centerx = float(self.rect.centerx) self.centery = float(self.rect.centery) # 記錄飛機中心點 self.moving_right = False self.moving_left = False self.moving_up = False self.moving_down = False def update(self): if self.moving_right and self.rect.right < self.screen_rect.right: #小於屏幕右側 self.centerx += self.ai_settings.ship_speed_factor if self.moving_left and self.rect.left > 0: # 大於屏幕左側0 self.centerx -= self.ai_settings.ship_speed_factor if self.moving_up and self.rect.top > self.screen_rect.top: # 大於屏幕頂部0 self.centery -= self.ai_settings.ship_speed_factor if self.moving_down and self.rect.bottom < self.screen_rect.bottom: #小於屏幕底部 self.centery += self.ai_settings.ship_speed_factor self.rect.centerx = self.centerx self.rect.centery = self.centery def center_ship(self): # 讓飛船居中 self.centery = self.screen_rect.bottom-70 self.centerx = self.screen_rect.centerx def blitme(self): self.screen.blit(self.image, self.rect)
關於一些基本的文件設置和背景設置:
import pygame import sys class Settings(): def __init__(self): self.screen_width = 1200 self.screen_height = 800 self.bg_color = (230, 230, 230) # 飛船的速度: self.ship_limit = 3 # 子彈設置 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = (60, 60, 60) self.bullets_allowed = 3 # 限制子彈的數量 self.fleet_drop_speed = 8 self.score_scale = 2 self.speedup_scale = 1.1 self.initialize_dynamic_settings() def initialize_dynamic_settings(self): self.ship_speed_factor = 1.5 self.bullet_speed_factor = 1 # 子彈的速度 self.alien_speed_factor = 1 # 飛船速度 self.fleet_direction = 1 # 方向參數 self.alien_points = 50 def increase_speed(self): self.ship_speed_factor *= self.speedup_scale self.bullet_speed_factor *= self.speedup_scale self.alien_speed_factor *= self.speedup_scale self.alien_points = int(self.alien_points * self.score_scale) print(self.alien_points)
關於按鍵的一些設置(這部分我將子彈向下向左向右發射的按鍵也加入進去,如不需要請自行刪減):
import sys import pygame from time import sleep # 時間?休眠? from bullet import Bullet from bulletRIGHT import BulletRight from bulletDOWN import BulletDown from bulletLEFT import BulletLeft from alien import Alien def check_keydown_events(event,ai_settings, screen,ship, bullets,bullets_left,bullets_right,bullets_down): if event.key == pygame.K_d: ship.moving_right = True elif event.key == pygame.K_a: ship.moving_left = True elif event.key == pygame.K_w: ship.moving_up = True elif event.key == pygame.K_q: # p鍵退出 sys.exit() elif event.key == pygame.K_s: ship.moving_down = True elif event.key == pygame.K_UP: fire_bullet(ai_settings, screen, ship, bullets) elif event.key == pygame.K_DOWN: fire_bullet_down(ai_settings, screen, ship,bullets_down) elif event.key == pygame.K_LEFT: fire_bullet_left(ai_settings, screen, ship,bullets_left) elif event.key == pygame.K_RIGHT: fire_bullet_right(ai_settings, screen, ship,bullets_right) def check_keyup_events(event, ship): if event.key == pygame.K_d: ship.moving_right = False elif event.key == pygame.K_a: ship.moving_left = False elif event.key == pygame.K_w: ship.moving_up = False elif event.key == pygame.K_s: ship.moving_down = False def check_events(ai_settings, stats, play_button,screen,ship, aliens,bullets,bullets_left,bullets_right,bullets_down): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: # 註意這個位置是type並不是key check_keydown_events(event,ai_settings, screen,ship, bullets,bullets_left,bullets_right,bullets_down) elif event.type == pygame.KEYUP: check_keyup_events(event, ship) elif event.type == pygame.MOUSEBUTTONDOWN: mouse_x, mouse_y = pygame.mouse.get_pos() check_play_button(ai_settings, screen, stats, ship, aliens, bullets, bullets_left, bullets_right, bullets_down, play_button, mouse_x, mouse_y) def check_play_button(ai_settings,screen,stats,ship,aliens, bullets,bullets_left,bullets_right,bullets_down, play_button, mouse_x,mouse_y): # if play_button.rect.collidepoint(mouse_x, mouse_y): button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y) if button_clicked and not stats.game_active: ai_settings.initialize_dynamic_settings() # 重置速度 pygame.mouse.set_visible(False) # 隱藏光標 stats.reset_stats() stats.game_active = True aliens.empty() bullets.empty() bullets_down.empty() bullets_left.empty() bullets_right.empty() create_fleet(ai_settings,screen,ship,aliens) ship.center_ship() def update_bullets(sb,screen,stats, ship ,ai_settings,aliens, bullets,bullets_left,bullets_right,bullets_down): bullets.update() for bullet in bullets.copy(): if bullet.rect.bottom <= 0: bullets.remove(bullet) check_bullets_alien_collisions(sb,screen,stats, ship ,ai_settings,aliens, bullets,bullets_left,bullets_right,bullets_down) def check_bullets_alien_collisions(sb,screen,stats, ship ,ai_settings,aliens, bullets,bullets_left,bullets_right,bullets_down): # print(len(bullets)) # 此句顯示未刪除的子彈數量以確保前幾句正確刪除子彈 collections = pygame.sprite.groupcollide(bullets, aliens,True,True ) # 子彈與外星飛船同歸於盡 if collections: stats.score += ai_settings.alien_points sb.prep_score() sb.prep_level() if len(aliens) == 0: # 如果外星人被打光重置外星人 bullets.empty() ai_settings.increase_speed() stats.level += 1 sb.prep_level() create_fleet(ai_settings, screen, ship ,aliens) bullets_down.update() for bullet_down in bullets_down.copy(): if bullet_down.rect.top >= ai_settings.screen_height: bullets_down.remove(bullet_down) print(len(bullets_down)) # 此句顯示未刪除的子彈數量以確保前幾句正確刪除子彈 collections = pygame.sprite.groupcollide(bullets_down, aliens, True, True) if collections: stats.score += ai_settings.alien_points sb.prep_score() bullets_left.update() for bullet_left in bullets_left.copy(): if bullet_left.rect.right <= 0: bullets_left.remove(bullet_left) # print(len(bullets_left)) # 此句顯示未刪除的子彈數量以確保前幾句正確刪除子彈 collections = pygame.sprite.groupcollide(bullets_left, aliens, True, True) if collections: stats.score += ai_settings.alien_points sb.prep_score() bullets_right.update() for bullet_right in bullets_right.copy(): if bullet_right.rect.left >= ai_settings.screen_width: bullets_right.remove(bullet_right) # print(len(bullets_right)) # 此句顯示未刪除的子彈數量以確保前幾句正確刪除子彈 collections = pygame.sprite.groupcollide(bullets_right, aliens, True, True) if collections: stats.score += ai_settings.alien_points sb.prep_score() def update_screen(ai_settings, screen, stats,ship,aliens, bullets,bullets_left,bullets_right,bullets_down,play_button ,sb): # 顯示 screen.fill(ai_settings.bg_color) for bullet in bullets.sprites(): bullet.draw_bullet() for bullet in bullets_right.sprites(): bullet.draw_bullet() for bullet in bullets_left.sprites(): bullet.draw_bullet() for bullet in bullets_down.sprites(): bullet.draw_bullet() ship.blitme() aliens.draw(screen) sb.show_score() if not stats.game_active: play_button.draw_button() pygame.display.flip() def create_fleet(ai_settings, screen ,ship,aliens): alien = Alien(ai_settings, screen) number_aliens_x = get_number_aliens_x(ai_settings, alien.rect.width) number_rows = get_number_rows(ai_settings, ship.rect.height, alien.rect.height) for row_number in range(number_rows): for alien_number in range(number_aliens_x): create_alien(ai_settings, screen, aliens , alien_number, row_number) def get_number_aliens_x(ai_settings, alien_width): # 外星飛船數量 available_space_x = ai_settings.screen_width - 1* alien_width number_alien_x = int(available_space_x / (2 * alien_width)) return number_alien_x def create_alien(ai_settings, screen, aliens, alien_number, row_number): alien = Alien(ai_settings, screen) alien_width = alien.rect.width alien.x = alien_width + 2*alien_width * alien_number alien.rect.x = alien.x alien.rect.y = alien.rect.height + 2*alien.rect.height*row_number aliens.add(alien) def get_number_rows(ai_settings, ship_height, alien_height): # 計算可容納多少外星人 available_space_y = (ai_settings.screen_height - (3*alien_height) - ship_height ) number_rows = int(available_space_y/(2*alien_height)) return number_rows def check_fleet_edges(ai_settings, aliens): for alien in aliens.sprites(): if alien.check_edges(): change_fleet_direction(ai_settings, aliens) break def change_fleet_direction(ai_settings, aliens): for alien in aliens.sprites(): alien.rect.y += ai_settings.fleet_drop_speed ai_settings.fleet_direction *= -1 # 將移動距離變為負 def ship_hit(ai_settings, stats, screen, ship , aliens , bullets,bullets_down,bullets_left,bullets_right): # 響應外星人撞擊飛船 if stats.ships_left > 0: stats.ships_left -= 1 # 將ship_left減1 # 清空外星人列表和子彈列表 aliens.empty() bullets.empty() bullets_down.empty() bullets_left.empty() bullets_right.empty() create_fleet(ai_settings, screen , ship , aliens) # 重置飛船和外星人 ship.center_ship() sleep(0.5) # 暫停 else: stats.game_active = False pygame.mouse.set_visible(True) def check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets): screen_rect = screen.get_rect() for alien in aliens.sprites(): if alien.rect.bottom >= screen_rect.bottom: ship_hit(ai_settings, stats,screen, ship, aliens,bullets) break def update_aliens(ai_settings, aliens ,stats, screen, ship ,bullets,bullets_down,bullets_left,bullets_right): # 更新外星飛船的位置 check_fleet_edges(ai_settings, aliens) aliens.update() if pygame.sprite.spritecollideany(ship, aliens): print('GG') ship_hit(ai_settings, stats, screen, ship , aliens , bullets,bullets_down,bullets_left,bullets_right) def fire_bullet(ai_settings, screen, ship, bullets): # 前方子彈 if len(bullets) < ai_settings.bullets_allowed: # 已經產生的子彈少於設置的數時發射才有效果 new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet) # def fire_bullet_down(ai_settings, screen, ship,bullets_down): # 後方子彈 if len(bullets_down) < ai_settings.bullets_allowed: # 已經產生的子彈少於設置的數時發射才有效果 new_bullet_down = BulletDown(ai_settings, screen, ship) bullets_down.add(new_bullet_down) # def fire_bullet_left(ai_settings, screen, ship,bullets_left): # 左方子彈 if len(bullets_left) < ai_settings.bullets_allowed: # 已經產生的子彈少於設置的數時發射才有效果 new_bullet_left = BulletLeft(ai_settings, screen, ship) bullets_left.add(new_bullet_left) # def fire_bullet_right(ai_settings, screen, ship,bullets_right): # 右方子彈 if len(bullets_right) < ai_settings.bullets_allowed: # 已經產生的子彈少於設置的數時發射才有效果 new_bullet_right = BulletRight(ai_settings, screen, ship) bullets_right.add(new_bullet_right) #
關於字體和開始按鍵的一些設置:
import pygame.font class Button(): def __init__(self, ai_settings, screen ,msg): self.screen = screen self.screen_rect = screen.get_rect() self.width, self.height = 200,50 self.button_color = (28, 136 ,121) self.text_color = (255, 255, 255) self.font = pygame.font.SysFont(None, 48) self.rect = pygame.Rect(0,0, self.width,self.height) self.rect.center = self.screen_rect.center self.prep_msg(msg) def prep_msg(self,msg): self.msg_image = self.font.render(msg,True,self.text_color,self.button_color) self.msg_image_rect = self.msg_image.get_rect() # 關於字的一些設置 self.msg_image_rect.center = self.rect.center def draw_button(self): self.screen.fill(self.button_color,self.rect) self.screen.blit(self.msg_image, self.msg_image_rect)
一些分數顯示和等級顯示代碼:
from settings import Settings from ship import Ship class GameStats(): def __init__(self, ai_settings): self.ai_settings = ai_settings self.reset_stats() self.game_active = False def reset_stats(self): self.ships_left = self.ai_settings.ship_limit self.score = 0 self.level = 1
關於等級難度提升的一些設置:
import pygame.font # 字體 from pygame.sprite import Group from ship import Ship class Scoreboard(): def __init__(self,ai_settings, screen, stats): self.screen = screen self.screen_rect = screen.get_rect() self.ai_settings = ai_settings self.stats = stats self.text_color = (30, 30, 30) self.font = pygame.font.SysFont(None, 48) self.prep_score() self.prep_level() # 等級 def prep_level(self): level_str = str(self.stats.level) self.level_image = self.font.render(level_str, True, self.text_color,self.ai_settings.bg_color) self.level_rect = self.level_image.get_rect() self.level_rect.right = self.score_rect.right self.level_rect.top = self.score_rect.bottom + 10 def prep_score(self): rounded_score = int(round(self.stats.score, -1)) score_str = "{:,}".format(rounded_score) self.score_image = self.font.render(score_str, True, self.text_color,self.ai_settings.bg_color) self.score_rect = self.score_image.get_rect() self.score_rect.right = self.screen_rect.right - 20 self.score_rect.top = 20 def show_score(self): self.screen.blit(self.score_image, self.score_rect) self.screen.blit(self.level_image, self.level_rect)
效果展示:
開始狀態:
點擊Game進行開始(開始後鼠標自動消失)
點擊上下左右鍵發射子彈(設置屏幕同一方向隻能存在三顆)
消滅飛船後難度提升 (死亡三次後從新開始成績清空)
遊戲介紹:
按game進行遊戲,遊戲開始後鼠標自動消失,用WSED來控制飛船飛行方向,用上下左右箭頭來控制子彈設計方向。外星人會以S型的飛行方式向玩傢飛來,當外星人碰到玩傢玩傢就會損失一條命,玩傢飛船共三條命,外星人碰到玩傢後玩傢位置和外星人位置就會重置,分數不會重置,當外星人沖過玩傢到達下方玩傢也會被判定丟失一條命然後位置重置。每消滅一個外星人右上角就會進行積分,當把框中的外星人全部消滅,外星人重新刷新。外星人速度和能力會以兩倍的實力增長,玩傢受到的分數獎勵也會增加,當玩傢三條命都丟失時遊戲結束。
到此這篇關於基於Pygame中Pygame模塊的大戰外星人實戰的文章就介紹到這瞭,更多相關Pygame 大戰外星人內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- Pygame實戰之實現經典外星人遊戲
- python pygame 憤怒的小鳥遊戲示例代碼
- Pygame遊戲開發之太空射擊實戰子彈與碰撞處理篇
- Python+Pygame實戰之實現小蜜蜂歷險記遊戲
- Pygame Rect區域位置的使用(圖文)