基于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)

效果展示:

开始状态:

基于Pygame中Pygame模块的大战外星人实战_第1张图片

点击Game进行开始(开始后鼠标自动消失)

基于Pygame中Pygame模块的大战外星人实战_第2张图片

点击上下左右键发射子弹(设置屏幕同一方向只能存在三颗)

基于Pygame中Pygame模块的大战外星人实战_第3张图片

消灭飞船后难度提升 (死亡三次后从新开始成绩清空)

 游戏介绍:

按game进行游戏,游戏开始后鼠标自动消失,用WSED来控制飞船飞行方向,用上下左右箭头来控制子弹设计方向。外星人会以S型的飞行方式向玩家飞来,当外星人碰到玩家玩家就会损失一条命,玩家飞船共三条命,外星人碰到玩家后玩家位置和外星人位置就会重置,分数不会重置,当外星人冲过玩家到达下方玩家也会被判定丢失一条命然后位置重置。每消灭一个外星人右上角就会进行积分,当把框中的外星人全部消灭,外星人重新刷新。外星人速度和能力会以两倍的实力增长,玩家受到的分数奖励也会增加,当玩家三条命都丢失时游戏结束。

到此这篇关于基于Pygame中Pygame模块的大战外星人实战的文章就介绍到这了,更多相关Pygame 大战外星人内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(基于Pygame中Pygame模块的大战外星人实战)