您好,登錄后才能下訂單哦!
這篇文章主要介紹“如何使用Pygame模塊實(shí)現(xiàn)大戰(zhàn)外星人游戲”,在日常操作中,相信很多人在如何使用Pygame模塊實(shí)現(xiàn)大戰(zhàn)外星人游戲問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”如何使用Pygame模塊實(shí)現(xiàn)大戰(zhàn)外星人游戲”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!
開發(fā)環(huán)境:Pycharm
操作系統(tǒng):Windows 10
Pyhon版本:3.9.9
需要自行安裝Pygame 3(必須)和Python(必須)。
由于多次引用背景參數(shù),建議不要更改文中的背景參數(shù)。本文中的圖片用的是相對引用的方式,如果和我圖片位置放置不同的話需要設(shè)置絕對引用。
主要代碼片段:
import sys import pygame # 調(diào)用pygame from settings import Settings # 背景和一些必要值 from ship import Ship # 飛船個(gè)人設(shè)置 import game_function as gf # 移動和發(fā)射 # 把整個(gè)給gf 并不是按照調(diào)用類的方式用的 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('飛機(jī)大戰(zhàn)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() # 這句很重要必須要調(diào)用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()
關(guān)于外星飛船的一些調(diào)用:
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)
關(guān)于子彈的一些配置(這里只是向前方向的子彈) 其余各個(gè)方向的子彈也是基于這個(gè)略改:
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 # 讓子彈持續(xù)往上飛 self.rect.y = self.y def draw_bullet(self): pygame.draw.rect(self.screen, self.color, self.rect)
關(guān)于可操控飛船的一些設(shè)置(如果要改變背景的長寬比,需要改變飛船的重置位置):
import pygame class Ship(): def __init__(self, ai_settings, screen): self.screen = screen self.ai_settings = ai_settings self.image = pygame.image.load('小飛機(jī).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) # 記錄飛機(jī)中心點(diǎn) 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: #小于屏幕右側(cè) self.centerx += self.ai_settings.ship_speed_factor if self.moving_left and self.rect.left > 0: # 大于屏幕左側(cè)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)
關(guān)于一些基本的文件設(shè)置和背景設(shè)置:
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 # 子彈設(shè)置 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = (60, 60, 60) self.bullets_allowed = 3 # 限制子彈的數(shù)量 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 # 方向參數(shù) 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)
關(guān)于按鍵的一些設(shè)置(這部分我將子彈向下向左向右發(fā)射的按鍵也加入進(jìn)去,如不需要請自行刪減):
import sys import pygame from time import sleep # 時(shí)間?休眠? 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: # 注意這個(gè)位置是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) # 隱藏光標(biāo) 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)) # 此句顯示未刪除的子彈數(shù)量以確保前幾句正確刪除子彈 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)) # 此句顯示未刪除的子彈數(shù)量以確保前幾句正確刪除子彈 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)) # 此句顯示未刪除的子彈數(shù)量以確保前幾句正確刪除子彈 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)) # 此句顯示未刪除的子彈數(shù)量以確保前幾句正確刪除子彈 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): # 外星飛船數(shù)量 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): # 計(jì)算可容納多少外星人 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 # 將移動距離變?yōu)樨?fù) def ship_hit(ai_settings, stats, screen, ship , aliens , bullets,bullets_down,bullets_left,bullets_right): # 響應(yīng)外星人撞擊飛船 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: # 已經(jīng)產(chǎn)生的子彈少于設(shè)置的數(shù)時(shí)發(fā)射才有效果 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: # 已經(jīng)產(chǎn)生的子彈少于設(shè)置的數(shù)時(shí)發(fā)射才有效果 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: # 已經(jīng)產(chǎn)生的子彈少于設(shè)置的數(shù)時(shí)發(fā)射才有效果 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: # 已經(jīng)產(chǎn)生的子彈少于設(shè)置的數(shù)時(shí)發(fā)射才有效果 new_bullet_right = BulletRight(ai_settings, screen, ship) bullets_right.add(new_bullet_right) #
關(guān)于字體和開始按鍵的一些設(shè)置:
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() # 關(guān)于字的一些設(shè)置 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)
一些分?jǐn)?shù)顯示和等級顯示代碼:
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
關(guān)于等級難度提升的一些設(shè)置:
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)
開始狀態(tài):
點(diǎn)擊Game進(jìn)行開始(開始后鼠標(biāo)自動消失)
點(diǎn)擊上下左右鍵發(fā)射子彈(設(shè)置屏幕同一方向只能存在三顆)
消滅飛船后難度提升 (死亡三次后從新開始成績清空)
按game進(jìn)行游戲,游戲開始后鼠標(biāo)自動消失,用WSED來控制飛船飛行方向,用上下左右箭頭來控制子彈設(shè)計(jì)方向。外星人會以S型的飛行方式向玩家飛來,當(dāng)外星人碰到玩家玩家就會損失一條命,玩家飛船共三條命,外星人碰到玩家后玩家位置和外星人位置就會重置,分?jǐn)?shù)不會重置,當(dāng)外星人沖過玩家到達(dá)下方玩家也會被判定丟失一條命然后位置重置。每消滅一個(gè)外星人右上角就會進(jìn)行積分,當(dāng)把框中的外星人全部消滅,外星人重新刷新。外星人速度和能力會以兩倍的實(shí)力增長,玩家受到的分?jǐn)?shù)獎勵也會增加,當(dāng)玩家三條命都丟失時(shí)游戲結(jié)束。
到此,關(guān)于“如何使用Pygame模塊實(shí)現(xiàn)大戰(zhàn)外星人游戲”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。