天天看點

python代碼學習之——外星人入侵

``# python代碼學習之——外星人入侵

自學 圖靈的《python程式設計從入門到實踐》——實踐練習記錄

遊戲介紹

該遊戲屬于簡單的2D遊戲,玩家控制一艘最初出現在螢幕底部中央的飛船(向左或向右),與此同時控制空格鍵來射擊天空中出現的一群外星人,它們會持續左右和向下移動,玩家的任務是射殺這些外星人。當螢幕中的外星人全都消失後會出現一群速度更快的外星人群,隻要外星人撞到飛船或者抵達螢幕底部,就會損失一個飛船,直至飛船用完,遊戲結束。

遊戲設計

  1. 對象:包含飛船、外星人群、子彈、分數系統;
  2. 飛船:初始及變動位置,個數,
  3. 外星人:初始及變動位置,個數(一行有多少,幾行)、移動速度(水準和垂直)
  4. 子彈:初始及變動位置,移動速度
  5. 記分:涉及飛船與外星人或底部螢幕(飛船失去一台)、外星人和子彈的碰撞(相應的外星人和飛船消失,加分),等級增加即已消滅一群外星人,此時飛船、外星人、子彈移動速度、分數由倍數增加。

主要運用pygame包繪制螢幕相關顯示,主程式alien_invasion.py應為簡潔調用方法的集合,打包裡的參數設定是最後一次調試用的參數(這個涉及面很小,僅供學習)

exe檔案 demo

https://pan.baidu.com/s/12xu91WiI_Q3B6beRBSzNEA 提取碼:j50z

我隻生成執行檔案是以用的是 -F ,

(env35) D:\workspace\python\AlienInvasion>   pyinstaller -F alien_invasion.py alien.py bullet.py button.py  game_functions.py game_stats.p
y scoreboard.py  settings.py ship.py -i D:\workspace\python\AlienInvasion\images\alien.ico -w
           

images 需要拷貝和exe同級目錄下 !!! 子彈和按鈕兩個檔案裡pygame.font.SysFont(‘arial’, 48) ‘arial’(自選) 不要填None 因為可能會出現界面沒法看;emmm 還有就是圖示要ico 格式,差不多這樣 沒啥特别注意的地方 pyinstaller 大點的工程得高階打包參考spec 配置打包方式

spec詳細

目錄

python代碼學習之——外星人入侵

注:high_score.txt 檔案初始可無,若無最高分預設0

連結與圖檔

連結: link.

圖檔:

python代碼學習之——外星人入侵

代碼展示

按照目錄順序粘貼

alien.py

// 
import pygame
from pygame.sprite import Sprite


class Alien(Sprite):
    """表示單個外星人的類"""

    def __init__(self, ai_settings, screen):
        """初始化外星人并設定其起始位置"""
        super(Alien, self).__init__()
        self.ai_settings = ai_settings
        self.screen = screen

        # 加載外星人圖像,并設定其rect屬性
        self.image = pygame.image.load('images/alien.bmp')
        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 blitme(self):
        """在指定位置繪制外星人"""
        self.screen.blit(self.image, self.rect)

    def check_edges(self):
        """如果外星人在螢幕邊緣,就傳回true"""
        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

           

alien_invasion.py

// import pygame
from pygame.sprite import Sprite


class Alien(Sprite):
    """表示單個外星人的類"""

    def __init__(self, ai_settings, screen):
        """初始化外星人并設定其起始位置"""
        super(Alien, self).__init__()
        self.ai_settings = ai_settings
        self.screen = screen

        # 加載外星人圖像,并設定其rect屬性
        self.image = pygame.image.load('images/alien.bmp')
        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 blitme(self):
        """在指定位置繪制外星人"""
        self.screen.blit(self.image, self.rect)

    def check_edges(self):
        """如果外星人在螢幕邊緣,就傳回true"""
        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

           

bullet.py

//
import pygame
from pygame.sprite import Sprite


class Bullet(Sprite):
    """一個對飛船發射的子彈進行管理的類"""
    def __init__(self, ai_settings, screen, ship):
        super(Bullet, self).__init__()
        self.screen = screen

        # 在(0,0)處建立一個表示子彈的矩形,再設定正确的位置
        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)
        
           

game_functions.py

//
import sys
from time import sleep
import pygame
from AlienInvasion.bullet import Bullet
from AlienInvasion.alien import Alien


def check_keydown_events(event, ai_settings, screen, ship, bullets):
    """響應按下"""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    elif event.key == pygame.K_SPACE:
        fire_bullet(ai_settings, screen, ship, bullets)
    elif event.key == pygame.K_q:
        sys.exit()


def fire_bullet(ai_settings, screen, ship, bullets):
    """如果還沒有達到限制,就發射一顆子彈"""
    # 建立一顆新子彈,并将其加入到編組bullets中
    if len(bullets) < ai_settings.bullets_allowed:
        new_bullet = Bullet(ai_settings, screen, ship)
        bullets.add(new_bullet)


def check_keyup_events(event, ship):
    """響應松開"""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    if event.key == pygame.K_LEFT:
        ship.moving_left = False


def check_events(ai_settings, screen, stats, sb, play_button, ship, aliens,
                 bullets):
    """響應鍵盤和滑鼠事件"""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event, ai_settings, screen, ship, bullets)
        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, sb, play_button,
                              ship, aliens, bullets, mouse_x, mouse_y)


def check_play_button(ai_settings, screen, stats, sb, play_button, ship,
                      aliens, bullets, mouse_x, mouse_y):
    button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)
    """在玩家點選Play後開始新遊戲"""
    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

        # 重置記分牌圖像
        sb.perp_score()
        sb.perp_high_score()
        sb.perp_level()
        sb.perp_ships()

        # 清空外星人清單和子彈清單
        aliens.empty()
        bullets.empty()

        # 建立一群外星人,并将飛船放置螢幕底部中央
        create_fleet(ai_settings, screen, ship, aliens)
        ship.center_ship()


def update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                  play_button):
    """更新螢幕上的圖像,并切換到新螢幕"""
    # 每次循環都重繪螢幕
    screen.fill(ai_settings.bg_color)
    ship.blitme()
    aliens.draw(screen)

    # 在飛船和外星人後面重繪所有子彈
    for bullet in bullets:
        bullet.draw_bullet()

    # 顯示得分
    sb.show_score()

    # 如果遊戲處于非活動狀态,就繪制Play按鈕
    if not stats.game_active:
        play_button.draw_button()

    # 讓最近繪制的螢幕可見
    pygame.display.flip()


def update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets):
    """更新子彈位置并删除已消失子彈"""
    # 更新子彈位置
    bullets.update()

    # 删除已消失的子彈
    for bullet in bullets.copy():
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)
    print(len(bullets))
    check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship,
                                  aliens, bullets)


def check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship,
                                  aliens, bullets):
    """響應子彈和外星人的碰撞"""
    # 删除相應的子彈和外星人
    collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)

    if collisions:
        for aliens in collisions.values():
            stats.score += ai_settings.alien_points
            sb.perp_score()
        check_high_score(stats, sb)

    if len(aliens) == 0:
        # 删除現有子彈,加快遊戲節奏,并建立一群新的外星人
        bullets.empty()
        ai_settings.increase_speed()
        create_fleet(ai_settings, screen, ship, aliens)

        # 提高等級
        stats.level += 1
        sb.perp_level()


def get_number_alien_x(ai_settings, alien_width):
    """計算每行可容納多少個外星人"""
    # 外星人間距為外星人寬度
    available_space_x = ai_settings.screen_width - (2 * alien_width)
    number_alien_x = int(available_space_x / (2 * alien_width))
    return number_alien_x


def get_number_rows(ai_settings, ship_height, alien_height):
    """計算螢幕可容納多少行外星人"""
    available_space_y = (ai_settings.screen_height
                         - ship_height - (3 * alien_height))
    number_rows = int(available_space_y / (2 * alien_height))
    return number_rows


def create_alien(ai_settings, screen, aliens, alien_number, number_rows):
    """建立一個外星人并将其放在第一行"""
    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 = (1 + 2 * number_rows) * alien.rect.height
    aliens.add(alien)


def create_fleet(ai_settings, screen, ship, aliens):
    """建立外星人群"""
    # 建立一個外星人 并計算一行可容納多少個外星人
    alien = Alien(ai_settings, screen)
    number_alien_x = get_number_alien_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_alien_x):
            create_alien(ai_settings, screen, aliens, alien_number,
                         row_number)


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, screen, stats, sb, ship, aliens, bullets):
    """響應被外星人撞到的飛船"""
    if stats.ships_left > 0:
        # 将減ship_left 減1
        stats.ships_left -= 1

        # 更新記分牌
        sb.perp_ships()

        # 清空外星人清單和子彈清單
        aliens.empty()
        bullets.empty()

        # 建立一群外星人,并将飛船放置螢幕底部中央
        create_fleet(ai_settings, screen, ship, aliens)
        ship.center_ship()
    else:
        stats.game_active = False
        pygame.mouse.set_visible(True)

    # 暫停
    sleep(0.5)


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, screen, stats, sb, ship, aliens, bullets)


def update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets):
    """檢查是否有外星人位于螢幕邊緣,并更新所有外星人的位置"""
    check_fleet_edges(ai_settings, aliens)
    aliens.update()

    # 檢測外星人和飛船之間的碰撞
    if pygame.sprite.spritecollideany(ship, aliens):
        ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets)

    # 檢測是否有外星人到達螢幕底端
    check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets)


def check_high_score(stats, sb):
    """見檢查是否産生了新的最高得分"""
    if stats.score > stats.high_score:
        stats.high_score = stats.score
        # 存儲最高分在txt檔案
        with open(stats.ai_settings.filename, 'w') as f:
            f.write(str(stats.high_score))
        sb.perp_high_score()
        
           

game_stats.py

//
class GameStats():
    """跟蹤遊戲的統計資訊"""

    def __init__(self, ai_settings):
        """初始化統計資訊"""
        self.ai_settings = ai_settings
        self.reset_stats()
        # 設定遊戲剛啟動時處于非活動狀态
        self.game_active = False
        # 在任何情況下都不應重置最高得分
        try:
            with open(self.ai_settings.filename) as f:
                self.high_score = int(f.read())
        except FileNotFoundError:
            self.high_score = 0

    def reset_stats(self):
        """初始化在遊戲運作期間可能變化的統計資訊"""
        self.ships_left = self.ai_settings.ship_limit
        self.score = 0
        self.level = 1

           

scoreboard.py

//
import pygame.font
from pygame.sprite import Group
from AlienInvasion.ship import Ship


class ScoreBoard():
    """顯示得分資訊的類"""

    def __init__(self, ai_settings, screen, stats):
        """初始化得分涉及的屬性"""
        self.ai_settings = ai_settings
        self.screen = screen
        self.screen_rect = screen.get_rect()
        self.stats = stats

        # 顯示得分資訊時使用的字型屬性
        self.text_color = (255, 255, 255)
        self.font = pygame.font.SysFont(None, 32)

        # 準備包含最高得分和目前得分圖像
        self.perp_score()
        self.perp_high_score()
        self.perp_level()
        self.perp_ships()

    def perp_ships(self):
        """顯示還餘下多少飛船"""
        self.ships = Group()
        for ship_number in range(self.stats.ships_left):
            ship = Ship(self.ai_settings, self.screen)

            ship.rect.x = self.ai_settings.screen_width - ship.rect.width
            ship.rect.y = self.ai_settings.screen_height - ship.rect.height - (
                    ship_number * ship.rect.height)
            self.ships.add(ship)

    def perp_level(self):
        """将等級轉換為渲染的圖像"""
        str_level = "Level: " + str(self.stats.level)
        self.level_image = self.font.render(str_level, True, self.text_color,
                                            self.ai_settings.bg_color)

        # 将得分放在螢幕左上角, 距邊緣間隔20
        self.level_rect = self.level_image.get_rect()
        self.level_rect.left = self.screen_rect.left + 20
        self.level_rect.top = 20

    def perp_score(self):
        """将得分轉換成一幅被渲染的圖像"""
        rounded_score = int(round(self.stats.score, -1))
        score_str = "Score: " + "{:,}".format(rounded_score)
        self.score_image = self.font.render(score_str, True, self.text_color,
                                            self.ai_settings.bg_color)

        # 将得分放在螢幕右上角, 距邊緣間隔20
        self.score_rect = self.score_image.get_rect()
        self.score_rect.right = self.screen_rect.right - 20
        self.score_rect.top = 20

    def perp_high_score(self):
        """将得分轉換成一幅被渲染的圖像"""
        rounded_high_score = int(round(self.stats.high_score, -1))
        high_score_str = "Top: " + "{:,}".format(rounded_high_score)
        self.high_score_image = self.font.render(high_score_str, True,
                                                 self.text_color,
                                                 self.ai_settings.bg_color)

        # 将得分放在螢幕右上角, 距邊緣間隔20
        self.high_score_rect = self.high_score_image.get_rect()
        self.high_score_rect.centerx = self.screen_rect.centerx
        self.high_score_rect.top = 20

    def show_score(self):
        """顯示得分"""
        self.screen.blit(self.score_image, self.score_rect)
        self.screen.blit(self.high_score_image, self.high_score_rect)
        self.screen.blit(self.level_image, self.level_rect)
        self.ships.draw(self.screen)

           

settings.py

//
class Settings():
    """存儲《外星人入侵》的所有設定的類"""

    def __init__(self):
        """初始化遊戲的靜态設定"""
        # 螢幕設定
        self.screen_width = 1000
        self.screen_height = 600
        self.bg_color = (0, 0, 0)

        # 飛船的設定
        self.ship_limit = 3

        # 子彈設定
        self.bullet_width = 5
        self.bullet_height = 15
        self.bullet_color = 200, 200, 200
        self.bullets_allowed = 20

        # 外星人設定
        self.fleet_drop_speed = 8

        # 以什麼樣的速度加快遊戲節奏
        self.speedup_scale = 1.1
        # 外星人點數提高的速度
        self.score_scale = 1.5

        # 記分
        self.alien_points = 50
        self.filename = 'high_score.txt'

        self.initialize_dynamic_settings()

    def initialize_dynamic_settings(self):
        """初始化由遊戲進行而改變的設定"""
        self.ship_speed_factor = 1.5
        self.bullet_speed_factor = 3
        self.alien_speed_factor = 1

        # fleet_direction為1表示向右移動 -1表示向左移動
        self.fleet_direction = 1

    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)

           

ship.py

//
import pygame
from pygame.sprite import Sprite


class Ship(Sprite):
    def __init__(self, ai_settings, screen):
        """初始化飛船并設定其初始位置"""
        super(Ship, self).__init__()
        self.screen = screen
        self.ai_settings = ai_settings

        # 加載飛船圖像并擷取其外接矩形
        self.image = pygame.image.load('images/ship.bmp')
        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

        # 在飛船的屬性center中存儲小數值
        self.center = float(self.rect.centerx)

        # 移動标志
        self.moving_right = False
        self.moving_left = False

    def update(self):
        """根據移動标志來調整飛船位置"""
        if self.moving_right and self.rect.right < self.screen_rect.right:
            self.center += self.ai_settings.ship_speed_factor
        if self.moving_left and self.rect.left > 0:
            self.center -= self.ai_settings.ship_speed_factor
        # 根據self.center更新rect對象
        self.rect.centerx = self.center

    def blitme(self):
        """在指定位置繪制飛船"""
        self.screen.blit(self.image, self.rect)

    def center_ship(self):
        """讓飛船在螢幕上居中"""
        self.center = self.screen_rect.centerx

           

附:

pygame使用及介紹