python[外星人入侵] 项目

这个项目主要是根据《python编程从入门到实践》这本书上的内容学这来的。
在这个项目中,随着游戏一步一步的深化,对于类的不断创建以及对于模块不断的重构,虽然这个步骤可能在你开始创建觉得麻烦一些,但是在以后的维护过程中却能省很大的力气。
这里主要是运用了pygame第三方库来实现的
主要是通过这篇文章来记录一下自己的第一个项目(书上有很清楚的解释)
新增了飞船上下移动操作

main.py

通过这个窗口来进行程序的执行与其他类的调用

import sys
import pygame
import functions
from pygame.sprite import Group
from sets import Sets
from ship import Ship
from game_stats import GameStats
from button import Button
from scoreboard import Scoreboard
def run_game():
    pygame.init()
    setting=Sets()
    screen=pygame.display.set_mode((setting.screen_width,setting.screen_height))
    #标题
    pygame.display.set_caption("first game")

    #储存游戏统计
    stats=GameStats(setting)
    #初始化飞船
    ship=Ship(setting,screen)
    #储存子弹
    bullets=Group()
    #创建一群外星人
    aliens=Group()
    play_button=Button(setting,screen,"Play")
    sb=Scoreboard(setting,screen,stats)

    functions.creat_fleet(setting,screen,ship,aliens)
    while True:
        functions.check_event(setting,screen,stats,sb,play_button,ship,aliens,bullets)
        if stats.game_active:
            ship.update()
            functions.update_bullets(setting,screen,stats,sb,ship,aliens,bullets)
            functions.update_aliens(setting,screen,stats,sb,ship,aliens,bullets)
        functions.update_screen(setting,screen,stats,sb,ship,aliens,bullets,play_button)
# 主函数为以下部分
run_game()

functions.py

简化代码结构,储存了大量的操作函数,简化main.py

import sys
import pygame
from time import sleep
from bullet import Bullet
from alien import Alien

def check_keydown(event,setting,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(setting,screen,ship,bullets)
    elif event.key==pygame.K_UP:
        ship.moving_up=True
    elif event.key==pygame.K_DOWN:
        ship.moving_down=True
    elif event.key==pygame.K_q:
        sys.exit()



def check_keyup(event,ship):
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False
    elif event.key==pygame.K_UP:
        ship.moving_up=False
    elif event.key==pygame.K_DOWN:
        ship.moving_down=False

def check_event(setting,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(event,setting,screen,ship,bullets)
        elif event.type==pygame.KEYUP:
            check_keyup(event,ship)
        elif event.type==pygame.MOUSEBUTTONDOWN:
            mouse_x,mouse_y=pygame.mouse.get_pos()
            check_play_button(setting,screen,stats,sb,play_button,ship,aliens,bullets,mouse_x,mouse_y)

def check_play_button(setting,screen,stats,sb,play_button,ship,aliens,bullets,mouse_x,mouse_y):
    button_checked = play_button.rect.collidepoint(mouse_x,mouse_y)
    if button_checked and not stats.game_active:
        setting.initialize_dynamic_settings()
        pygame.mouse.set_visible(False)
        #重置游戏统计信息
        stats.reset_stats()
        stats.game_active=True
        #重置计分牌
        sb.prep_high_score()
        sb.prep_level()
        sb.prep_score()
        sb.prep_ships()
        #清空列表
        aliens.empty()
        bullets.empty()
        #创建一群外星人
        creat_fleet(setting,screen,ship,aliens)
        ship.center_ship()

def update_screen(setting,screen,stats,sb,ship,alien,bullets,play_button):
    screen.fill(setting.color)
    sb.show_score()
    for bullet in bullets.sprites():
        bullet.draw_bullet()
    ship.blitme()
    alien.draw(screen)
    if not stats.game_active:
        play_button.draw_button()

    pygame.display.flip()

def update_bullets(setting,screen,stats,sb,ship,aliens,bullets):
    bullets.update()
    for bullet in bullets.copy():
        if bullet.rect.bottom<=0:
            bullets.remove(bullet)
    check_bullet_alien_conllisions(setting,screen,stats,sb,ship,aliens,bullets)
#子弹是否碰撞
def check_bullet_alien_conllisions(setting,screen,stats,sb,ship,aliens,bullets):
    collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
    if collisions:
        for aliens in collisions.values():
            stats.score+=setting.alien_points*len(aliens)
            sb.prep_score()
        check_high_score(stats,sb)

    if len(aliens) == 0:
        # bullets.empty()
        setting.increase_speed()
        #提高等级
        stats.level+=1
        sb.prep_level()

        creat_fleet(setting, screen, ship, aliens)


def fire_bullet(setting,screen,ship,bullets):
    if len(bullets) < setting.bullet_allowed:
        new_bullet = Bullet(setting, screen, ship)
        bullets.add(new_bullet)
#计算行容纳外星人
def get_number_aliens_x(setting,alien_width):
    available_space_x=setting.screen_width-5*alien_width
    number_aliens_x=int(available_space_x/(2*alien_width))
    return number_aliens_x
#计算列容纳外星人
def get_number_rows(setting,ship_height,alien_height):
    available_space_y=(setting.screen_height-(3*alien_height)-ship_height)
    number_rows=int(available_space_y/(2*alien_height))
    return number_rows
#生成一个外星人
def creat_alien(setting,screen,aliens,alien_number,row_num):
    alien = Alien(setting, 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_num
    aliens.add(alien)
#生成外星人群
def creat_fleet(setting,screen,ship,aliens):
    alien=Alien(setting,screen)
    number_aliens_x=get_number_aliens_x(setting,alien.rect.width)
    number_row=get_number_rows(setting,ship.rect.height,alien.rect.height)
    #创建一行外星人
    for row_number in range(number_row):
        for num in range(number_aliens_x):
            creat_alien(setting,screen,aliens,num,row_number)
#当外星人到达边缘
def check_fleet_edges(setting,aliens):
    for alien in aliens.sprites():
        if alien.check_edges():
            change_fleet_direction(setting,aliens)
            break

#将外星人向下移,并改变运动方向
def change_fleet_direction(setting,aliens):
    for alien in aliens.sprites():
        alien.rect.y+=setting.fleet_drop_speed
    setting.fleet_direction *=-1

#检查是否有外星人到达屏幕底端
def check_aliens_bottom(setting,screen,stats,sb,ship,aliens,bullets):
    screen_rect=screen.get_rect()
    for alien in aliens.sprites():
        if alien.rect.bottom>=screen_rect.bottom:
            ship_hit(setting,screen,stats,sb,ship,aliens,bullets)
            break


def update_aliens(setting,screen,stats,sb,ship,aliens,bullets):
    check_fleet_edges(setting,aliens)
    aliens.update()
    if pygame.sprite.spritecollideany(ship,aliens):
        ship_hit(setting,screen,stats,sb,ship,aliens,bullets)
    check_aliens_bottom(setting,screen,stats,sb,ship,aliens,bullets)
#检查飞船是否撞击
def ship_hit(setting,screen,stats,sb,ship,aliens,bullets):
    if stats.ships_left>0:
        stats.ships_left-=1
        sb.prep_ships()
        aliens.empty()
        bullets.empty()
        #创建新外星人,重置飞船
        creat_fleet(setting,screen,ship,aliens)
        ship.center_ship()

        #暂停
        sleep(2)
    else:
        stats.game_active=False
        pygame.mouse.set_visible(True)

def check_high_score(stats,sb):
    if stats.score>stats.high_score:
        stats.high_score=stats.score
        sb.prep_high_score()

sets.py

储存了大量的初始设置,如果更改属性,直接更改sets.py内容

import pygame
class Sets:
    def __init__(self):
        #初始屏幕大小设置
        self.screen_width=1400
        self.screen_height=700
        self.color=(255,255,255)
        #飞船速度设置
        self.ship_speed_factor=0.3
        self.ship_limit=3
        #子弹设置
        self.bullet_speed_factor=1
        self.bullet_width=3
        self.bullet_height=15
        self.bullet_color=0,0,0
        self.bullet_allowed=10

        #外星人设置
        self.alien_speed_factor=0.5
        self.fleet_drop_speed=10
        self.fleet_direction=1

        #按钮设置

        self.button_width=200
        self.button_height=50
        self.button_color=(72,61,139)
        self.button_text_color=(255,255,255)
        self.button_font=pygame.font.SysFont('arial',30)
        #以什么样的速度急速游戏节奏
        self.speedup_scale=1.2
        #外星人点数题高
        self.score_scale=1.5
        self.initialize_dynamic_settings()

        #显示得分的字体设置
        self.score_text_color=(30,30,30)
        self.score_font=pygame.font.SysFont('arial',30)

    def initialize_dynamic_settings(self):
        self.ship_speed_factor=0.7
        self.bullet_speed_factor=2
        self.alien_speed_factor=0.5
        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)



bullet.py

储存子弹的一些操作

import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
    def __init__(self,settings,screen,ship):
        super().__init__()
        self.screen=screen

        self.rect=pygame.Rect(0,0,settings.bullet_width,settings.bullet_height)
        self.rect.centerx=ship.rect.centerx
        self.rect.top=ship.rect.top

        #储存子弹位置
        self.y=float(self.rect.y)
        self.color=settings.bullet_color
        self.speed_factor=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)


ship.py

储存飞船的一系列内容

import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
    def __init__(self,setting,screen):
        #初始飞船位置
        super(Ship,self).__init__()
        self.screen=screen
        #飞船速度
        self.setting=setting

        self.image=pygame.image.load('image.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

        self.center=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.center+=self.setting.ship_speed_factor
        if self.moving_left and self.rect.left>0:
            self.center-=self.setting.ship_speed_factor
        if self.moving_up and self.rect.top>0:
            self.centery-=self.setting.ship_speed_factor
        if self.moving_down and self.rect.bottom<self.screen_rect.bottom:
            self.centery+=self.setting.ship_speed_factor

        self.rect.centerx=self.center
        self.rect.centery=self.centery
    #在指定位置绘制飞船
    def blitme(self):
        self.screen.blit(self.image,self.rect)

    def center_ship(self):
        self.center=self.screen_rect.centerx
        self.centery=self.screen_rect.bottom-30

alien.py

import pygame
from pygame.sprite import Sprite
class Alien(Sprite):
    def __init__(self,setting,screen):
        super().__init__()
        self.screen=screen
        self.setting=setting
        #加载外星人图像
        self.image=pygame.image.load('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):
        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.setting.alien_speed_factor*self.setting.fleet_direction
        self.rect.x=self.x

game_stats.py

跟踪游戏统计信息类

class GameStats():
    def __init__(self,setting):
        self.game_active=False
        self.setting=setting
        self.reset_stats()
        self.high_score=0

    def reset_stats(self):
        self.ships_left=self.setting.ship_limit
        self.score=0
        self.level=1

button.py

游戏按钮储存

import pygame.font
class Button():
    def __init__(self,setting,screen,msg):
        #初始化按钮
        self.screen=screen
        self.screen_rect=screen.get_rect()
        #设置按钮尺寸及其其他属性
        self.width=setting.button_width
        self.height=setting.button_height
        self.button_color=setting.button_color
        self.text_color=setting.button_text_color
        self.font=setting.button_font

        #创建按钮使其剧中
        self.rect=pygame.Rect(0,0,self.width,self.height)
        self.rect.center=self.screen_rect.center

        self.prep_msg(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)

scoreboard.py

游戏计分

import pygame.font
from pygame.sprite import Group
from ship import Ship
class Scoreboard():
    def __init__(self,setting,screen,stats):
        self.screen=screen
        self.screen_rect=screen.get_rect()
        self.setting=setting
        self.stats=stats

        self.text_color=setting.score_text_color
        self.font=setting.score_font

        self.prep_score()
        self.prep_high_score()
        self.prep_level()
        self.prep_ships()

    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)

    def prep_score(self):
        #score_str=str(self.stats.score)
        rounded_score=int(round(self.stats.score,-1))
        score_str="Current score: "+"{:,}".format(rounded_score)

        self.score_image=self.font.render(score_str,True,self.text_color,self.setting.color)

        #计分显示在右上角
        self.score_rect=self.score_image.get_rect()
        self.score_rect.right=self.screen_rect.right-20
        self.score_rect.top=20

    def prep_high_score(self):
        high_score=int(round(self.stats.high_score,-1))
        high_score_str="Highest score: "+"{:,}".format(high_score)
        self.high_score_image=self.font.render(high_score_str,True,self.text_color,self.setting.color)

        self.high_score_rect=self.high_score_image.get_rect()
        self.high_score_rect.centerx=self.screen_rect.centerx
        self.high_score_rect.top=self.score_rect.top
    def prep_level(self):
        self.level_image=self.font.render("Level: "+str(self.stats.level),True,self.text_color,self.setting.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_ships(self):
        self.ships= Group()
        for ship_num in range(self.stats.ships_left):
            ship=Ship(self.setting,self.screen)
            ship.rect.x=10+ship_num*ship.rect.width
            ship.rect.y=10
            self.ships.add(ship)
python学习记录 文章被收录于专栏

python一些学习记录

全部评论

相关推荐

美团 后端开发 总包n(15%是股票)
点赞 评论 收藏
分享
菜菜咪:1. 可以使用简历网站的模版,美观度会更好一点 2. 邮箱可以重新申请一个,或者用qq邮箱的别名,部分hr可能会不喜欢数字邮箱 3. 项目经历最好分点描述,类似的项目很多,可以参考一下别人怎么写的 4. 自我评价可加可不加,技术岗更看重技术。最后,加油,优秀士兵
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务