Pythone入门到实践-学习笔记-Day5

实战项目:大战外星人

pygame是跨平台Python模块,专为电子游戏设计,包含图像、声音,建立在SDL(Simple DirectMedia Layer)基础上

一、pygame各模块和功能

在某些平台下,有些功能可能没有,可用None测试

if pygame.cdrom is None:
  print "pygame.cdrom not available"
模块名 功能
pygame.cdrom 访问光驱
pygame.cursors 加载光标
pygame.display 访问显示设备
pygame.draw 绘制形状、线和点
pygame.event 管理事件
pygame.font 使用字体
pygame.image 加载和存储图片
pygame.joystick 使用游戏手柄或类似设置
pygame.key 读取键盘按键
pygame.mixer 声音
pygame.mouse 鼠标
pygame.movie 播放视频
pygame.music 播放音频
pygame.overlay 访问高级视频叠加
pygame.rect 管理矩形区域
pygame.sndarray 操作声音数据
pygame.sprite 操作移动图像
pygame.surface 管理图像和屏幕
pygame.surfarray 管理点阵图像数据
pygame.time 管理时间和帧信息
pygame.transform 绽放和移动图像

二、创建Pygame窗口

import sys
import pygame
def run_game():
  pygame.init()
  screen = pygame.display.set_mode((1200,800))
  pygame.display.set_caption("大战外星人")
  bg_color = (230,230,230)
  while True:
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        sys.exit()
  screen.fill(bg_color)
  pygame.display.flip()

run_game()

pygame.init():初始化游戏并创建一个屏幕对像
screen = pygame.display.set_mode((1200,800)):创建一个显示窗口,游戏的所有图形元素都奖在其中绘制,(1200,800)元组实参决定窗口的尺寸(宽1200高800)
pygame.display.set_caption("大战外星人"):设置窗口标题
pygame.event.get():接收用户输入事件(按键和移动鼠标)
screen.fill(bg_color):设置背景颜色
pygame.display.flip():命令Pygame让最近绘制的屏幕可见,不断刷新屏幕,以显示元素的位置,并在原来的位置隐藏元素,从而营造平滑移动的效果。

三、创建飞船

加载一幅图像,再使用Pygame方法blit()绘制

import pygame
class Ship():
  def __init__(self, screen):
    self.screen = screen
    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.screcn_rect.bottom

  def blitme(self):
    self.screen.blit(self.image, self.rect)

self.image = pygame.image.load() :加载飞船图片,并存储到self.image中
get_rect():获取图像的属性rect,python能够像处理矩形(rect对象)一样处理图像,处理rect对象时,可使用矩形四角(left,right,bottom,top)、坐标(x,y)和中心的x(centerx)和y(centery)坐标,来指矩形的位置。
self.screen.blit(self.image, self.rect):根据rect指定的位置将图像绘制到飞屏幕上。

四、驾驶飞船

def check_events(ship):
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      exit()
  elif event.type == pygame.KEYDOWN:
    if event.key == pygame.K_RIGHT:
      ship.rect.centerx += 1
    elif event.key == pygame.K_LEFT:
      ship.rect.centerx -= 1

pygame.KEYDOWN:按下;pygame.KEYUP:弹起
** pygame.K_RIGHT:向右键; pygame.K_LEFT**:向左键

扩展飞船功能:

1、允许不断移动
2、限制飞船的活动范围(不能超出屏幕)

五、飞船开炮

1、炮弹

class Bullet(Sprite):
  def __init__(self, ai_settings, screen, ship):
    super(Bullet,self).__init__()
    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):
    pygam.draw.rect(self.screen, self.color, self.rect)

super(Bullet,self).init():Python2.7语法,也适用Python3,但Python3可以简写为:super()._init_()
pygame.rect(0,0,ai_settings.bullet_width,ai_settings.bullet_height):创建矩形,第一个实参指定左上角x坐标,第二实参指定左上角y坐标,第三实参指定矩形的宽,第四实参指定矩形的高度
self.rect.centerx = ship.rect.centerx和self.rect.top = ship.rect.top:调整矩形的位置
def update(self):向上移动炮弹
pygam.draw.rect(self.screen, self.color, self.rect):使用self.color填充表示子弹的rect,并绘制到screen

2. 创建外星人

import pygame
from pygame.sprite import Sprite
class Alien(Sprite):
  def __init__(selft, ai_settings, screen):
    super().__init__()
    self.screen = screen
    self.ai_settings = ai_settings
    self.image = pygame.image.load('image/alien.bmp')

    self.rect = self.image.get_rect()
    self.rect.x = self.rect.width
    selft.rect.y = self.rect.height
    self.x = float(self.rect.x)

  def upate(self):
    self.x += (self.ai_settings.alien_speed_factor * self.ai_settings.fleet_direction)
    self.rect.x = self.x

  def check_edges(self):
    screen_rect = self.screen.get_rect()
    if self.rect.right >= screen.right:
      return True
    elif self.rect.left <= 0:
      return True      

  def blitme(self):
    self.screen.blit(self.image, self.rect)  

外星人默认在屏幕左上方位置,并向右边移动,除了位置不同外,大部分与Ship类相似
fleet_direction:控制外星人向左向右移动,如果到最右边,向下移动并向左边移动,如果到最左边,向下移动并向右边移动
check_edges:检查外星人是否到屏幕边缘

3.创建多行外星人

def create_fleet(ai_settings, screen, ship, aliens):
  alien = Alien(ai_settings,screen)
  alien_widht = alien.rect.widht
  availabe_width = screen.width -(2 * alien_width)
  number_alien_x = available_width /(2 * alien_widht)
  alien_height = alien.rect.height 
  availabled_height = aline.screen.height
 - (3 * alien_height) - ship.height
  number_alien_y = availabled_height / (2 *availabled_height )
  for m in range(number_alien_y):
    form n in range(number_alien_x):
      aline = Alien(ai_settings, screen)
      alien.x = aline_width +2 * alien_widht * n
      alien.y = aline_height + 2 * alien_height* m  
      alien.rect.x = alien.x
      alien.rect.y = alien.y
      aliens.add(alien)

4.射杀外星人

collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)

遍历组子弹组和外星人组,当有子弹和外星人的rect重叠时,groupcollid()在它返回的字典中添加一个键值对,两个实参True告诉python删除发碰撞的子弹和外星人

5. 结束游戏

创建游戏统计信息类:

class GameStats():
   def __init__(self, ai_settings):
    self.ai_setting = ai_settings
    self.game_active = True
    self.reset_stats()
  
  def reset_stats(self):
    self.ship_left = self.ai_settings.ship_limit

外星人撞到飞船或外得人到达屏幕底部时,需结束游戏
pygame.sprite.spritecollideany(ship,alines):检查外星人和飞船是否相撞,检查编组是否有成员开发业有灵发生碰撞,并在找到与精灵发生碰撞的成员后停止遍历,并返回找到的第一个发生碰撞的外星人,如果没有发生碰撞,返回None

def ship_hit(ai_settings, stats, screen, ship, aliens, bullets):
    
    aliens.empty()
    bullets.empty()

    create_fleet(ai_settings, screen, ship, aliens)
    ship.center_ship()

    if stats.ship_left > 0:
        stats.ship_left -= 1
        sleep(0.5)
    else:
        stats.game_active = False

def check_alien_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

第十四章 记分

添加Play按钮

import pygame.font

class Button():
    def __init__(self,ai_settings, screen, msg):
        self.screen = screen
        self.screct_rect = screen.get_rect()

        self.width, self.height = 200,50
        self.color = (0,250,0)
        self.text_color = (255,255,255)
        self.font = pygame.font.SysFont(None,48)

        self.rect = pygmae.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_img = self.font.render(msg, True, self.text_color,self.color)
    self.msg_image_rect = self.msg_img.get_rect()
    self.msg_image_rect.center = self.rect.center

  def draw_button(self):
    self.screen.fill(self.color,self.rect)
    self.screen.blit(self.msg_img,self.msg_image_rect)

pygame.font让pygame能够将文本渲染到屏幕上
**pygame.font.SysFont(None,48)
**:指定使用什么字体来渲染文本,实参None让python使用默认字体,48指定文本的字号
font.render():将存储在msg中的文本转换为图像,然后将图像存储中msg_img中,实参True指定开启反锯齿功能,剩下两个分别是文本颜色和背景色
self.screen.fill():表示按钮的矩形,再调用一次screen.blit(),并向它传递一幅图像与该图像的关联和rect对象

按钮点击事件

def check_play_button(ai_settings,screen, stats,ship,bullets,aliens, play_button,mouse_x,mouse_y):
    
    button_clicked = play_button.rect.collidepoint(mouse_x,mouse_y)
    if button_clicked and not stats.game_active:
        pygame.mouse.set_visible(False)
        stats.game_active = True
        stats.reset_stats()
        aliens.empty()
        bullets.empty()

        create_fleet(ai_settings, screen, ship, aliens)
        ship.center_ship()

**pygame.mouse.set_visible(False)
**:隐藏鼠标

记分

显示飞船数prep_ship(),当前得分prep_score(),当前等级prep_level()

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

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

    def prep_score(self):
        score_str = 'Scroe:' + str(self.stats.score)
        self.msg_img = self.font.render(score_str, True, self.text_color,self.ai_settings.bg_color)
        self.msg_image_rect = self.msg_img.get_rect()
        self.msg_image_rect.right = self.screen_rect.right - 20
        self.msg_image_rect.top = 20

    def prep_level(self):
        level_str = 'Level:'+str(self.stats.play_level)
        self.level_img = self.font.render(level_str,True, self.text_color,self.ai_settings.bg_color)
        self.level_img_rect = self.level_img.get_rect()
        self.level_img_rect.right = self.screen_rect.right - 20
        self.level_img_rect.top = 50

    def prep_ship(self):
        self.ships = Group()
        for num in range(self.stats.ship_left):
            ship = Ship(self.ai_settings, self.screen)
            ship.rect.x = 10 + num * ship.rect.width
            ship.rect.y = 10
            self.ships.add(ship)

附代码:

settings类

class Settings():
    """存储所有设置的类"""
    def __init__(self):
        """初始化游戏的设置"""
        #屏幕设置
        self.screen_width = 800
        self.screen_height = 600
        self.bg_color = (230,230,230)
        
        self.bullet_width = 3
        self.bullet_height = 15
        self.bullet_color = 60,60,60
        self.bullets_allowed = 100
        self.space_x = 1

        self.fleet_direction=1
        self.fleet_drop_speed=20

        self.speedup_scale =1.1
        self.ship_limit = 3
        self.init_dynamic_settings()        

    def init_dynamic_settings(self):
        self.bullet_speed_factor = 1
        self.alien_speed_factor = 1
        self.ship_speed_factor = 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

ship类

import pygame
from pygame.sprite import Sprite

class Ship(Sprite):

    def __init__(self,ai_settings,screen):
        super().__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

        # 移动标志
        self.moving_right = False
        self.moving_left = False
        # 一直开火
        self.keeping_fire = False

    def  update(self):
        """根据移动标志调整飞船的位置 """
        if self.moving_right and self.rect.right < self.screen_rect.right:
            self.rect.centerx += self.ai_settings.ship_speed_factor
        if self.moving_left and self.rect.left > 0:
            self.rect.centerx -= self.ai_settings.ship_speed_factor

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

    def center_ship(self):
        self.rect.centerx = self.screen_rect.centerx

Bullet类

import pygame

from pygame.sprite import Sprite

class Bullet(Sprite):
    """"一个对飞船发射子弹进行管理的类"""

    def __init__(self,ai_settings, screen, ship):
        """"在飞船所处的位置创建一个子弹对象"""
        super(Bullet, self).__init__()
        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
        #更新表示子弹的rect的位置
        self.rect.y = self.y       

    def draw_bullet(self):
        """在屏幕上绘制子弹"""
        pygame.draw.rect(self.screen, self.color, self.rect)

Alien类

import pygame

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('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 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)

    def check_edges(self):
        screen_rect = self.screen.get_rect()
        if self.rect.right >= screen_rect.right or self.rect.left <= screen_rect.left :
            return True
        else:
            return False

公共控制模块

import sys
import time

import pygame
from time import sleep

from bullet import Bullet
from alien import Alien

def check_events(ai_settings,stats, screen,ship,bullets,aliens,play_button):
    """响应按键和鼠标事件"""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            check_down_events(event, ai_settings, screen, ship, bullets)               
        elif event.type == pygame.KEYUP:
            check_up_events(event, ai_settings, screen, ship, bullets)
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x,mouse_y = pygame.mouse.get_pos()
            check_play_button(ai_settings,screen,stats,ship,bullets,aliens, play_button,mouse_x,mouse_y)


def check_down_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:
        ship.keeping_fire = True
        fire_bullet(ai_settings, screen, ship, bullets)
    
def check_up_events(event, ai_settings, screen, ship, bullets):
    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_SPACE:
        ship.keeping_fire = False

def update_screen(ai_settings, stats, screen, ship, aliens, bullets, play_button, sb):
    """更新屏幕上的图像,并切换到新屏幕"""
    # 重绘屏幕
    screen.fill(ai_settings.bg_color)    
        
    # 在飞船和外星人后面重绘所有子弹
    for bullet in bullets.sprites():
        bullet.draw_bullet()
    
    ship.blitme()
    aliens.draw(screen)
    sb.show_score_board()
    
    if not stats.game_active:
        play_button.draw_button()
     # 让最近绘制的屏幕可见
    pygame.display.flip()

def update_bullets(ai_settings,screen, ship, aliens, bullets,stats, sb):
    bullets.update()
    
    for bullet in bullets.copy():
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)
    collissions = pygame.sprite.groupcollide(bullets, aliens ,True, True)
    if collissions:
        stats.score += 1
        sb.prep_score()
    if len(aliens) == 0:
        stats.play_level += 1
        sb.prep_level()
        bullets.empty()
        
        ai_settings.increase_speed()
        create_fleet(ai_settings,screen,ship,aliens)
        

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 get_number_aliens_x(ai_settings, alien_width):
    available_space_x = ai_settings.screen_width - 2 * alien_width
    number_aliens_x = int(available_space_x / (2 * alien_width))
    return number_aliens_x

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 create_alien(ai_settings, screen, aliens, alien_number, row_number):
    alien = Alien(ai_settings, screen)
    alien.x = alien.rect.width + 2 * alien.rect.width * alien_number
    alien.rect.x = alien.x
    alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
    aliens.add(alien)

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 update_aliens(ai_settings,stats,screen,ship,aliens, bullets,sb):
    check_fleet_edges(ai_settings, aliens)
    aliens.update()
    if pygame.sprite.spritecollideany(ship, aliens):
        ship_hit(ai_settings, stats, screen, ship, aliens, bullets,sb)
    check_alien_bottom(ai_settings, stats, screen, ship, aliens, bullets,sb)

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,sb):    
    aliens.empty()
    bullets.empty()

    create_fleet(ai_settings, screen, ship, aliens)
    ship.center_ship()     

    if stats.ship_left > 0:
        stats.ship_left -= 1
        sb.prep_ship()
        sleep(0.5)
    else:        
        stats.game_active = False
        pygame.mouse.set_visible(True)

def check_alien_bottom(ai_settings, stats, screen, ship, aliens, bullets,sb):
    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,sb)
            break

def check_play_button(ai_settings,screen, stats,ship,bullets,aliens, play_button,mouse_x,mouse_y):
    
    button_clicked = play_button.rect.collidepoint(mouse_x,mouse_y)
    if button_clicked and not stats.game_active:
        pygame.mouse.set_visible(False)
        stats.game_active = True
        stats.reset_stats()
        aliens.empty()
        bullets.empty()

        create_fleet(ai_settings, screen, ship, aliens)
        ship.center_ship()

Button类

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.color = (0,250,0)
        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_img = self.font.render(msg, True, self.text_color,self.color)
        self.msg_image_rect = self.msg_img.get_rect()
        self.msg_image_rect.center = self.rect.center

    def draw_button(self):
        self.screen.fill(self.color,self.rect)
        self.screen.blit(self.msg_img,self.msg_image_rect)

记分类

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

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

    def prep_score(self):
        score_str = 'Scroe:' + str(self.stats.score)
        self.msg_img = self.font.render(score_str, True, self.text_color,self.ai_settings.bg_color)
        self.msg_image_rect = self.msg_img.get_rect()
        self.msg_image_rect.right = self.screen_rect.right - 20
        self.msg_image_rect.top = 20

    def prep_level(self):
        level_str = 'Level:'+str(self.stats.play_level)
        self.level_img = self.font.render(level_str,True, self.text_color,self.ai_settings.bg_color)
        self.level_img_rect = self.level_img.get_rect()
        self.level_img_rect.right = self.screen_rect.right - 20
        self.level_img_rect.top = 50

    def prep_ship(self):
        self.ships = Group()
        for num in range(self.stats.ship_left):
            ship = Ship(self.ai_settings, self.screen)
            ship.rect.x = 10 + num * ship.rect.width
            ship.rect.y = 10
            self.ships.add(ship)

    def show_score_board(self):
        #self.screen.fill(self.text_color,self.rect)
        self.screen.blit(self.msg_img,self.msg_image_rect)
        self.screen.blit(self.level_img,self.level_img_rect)
        self.ships.draw(self.screen)

游戏状态类

class GameStats():
    def __init__(self, ai_settings):
        self.ai_settings = ai_settings
        self.reset_stats()
        self.game_active = False
        self.play_level = 1
        self.reset_stats()
        
  
    def reset_stats(self):
        self.ship_left = self.ai_settings.ship_limit
        self.score = 0

主程序

import sys
import pygame
from pygame.sprite import Group
from settings import Settings
from ship import Ship
from gamestats import GameStats
from button import Button
from scoreboard import Scoreboard
import game_functions as gf

def run_game():
    # 初始化背景设置
    pygame.init()

    ai_settings=Settings()
    stats = GameStats(ai_settings) 
    
    # 创建显示窗口
    screen = pygame.display.set_mode(
        (ai_settings.screen_width,ai_settings.screen_height))
    # 设置窗口标题
    pygame.display.set_caption('Alien Invasion')
    sb = Scoreboard(ai_settings,screen,stats)    

    #创建一艘飞船
    ship = Ship(ai_settings, screen)
    play_button = Button(ai_settings, screen, 'Play')

    bullets = Group()
    aliens = Group()
    while True:
        # 处理事件
        gf.check_events(ai_settings,stats, screen,ship,bullets,aliens,play_button)

        if stats.game_active:
            ship.update()        
            gf.update_aliens(ai_settings, stats, screen,ship,aliens, bullets,sb)        
            gf.update_bullets(ai_settings,screen, ship, aliens,bullets,stats,sb)
            
        gf.update_screen(ai_settings,stats,screen,ship,aliens,bullets,play_button,sb)

run_game()

总结

1、屏幕创建

pygame.init()#初始化
screen = pygame.display.set_mode(width, height) #设置尺寸
screen_rect = screen.get_rect() #获取屏幕矩形位置
pygame.display.set_caption('xx') #设置标题
screen.fill(bg_color) #(230,230,230)
pygame.display.flip()# 让最近绘制的屏幕可见

2、响应事件(键盘鼠标)

#捕捉所有事件
for event in pygame.event.get():
  #按下
  if event.type == pygame.KEYDOWN:
    #按下什么键
    if event.key = pygame.K_RIGHT:
    elif event.key == pygame.K_LEFT:
 #弹起
  elif event.type == pygame.KEYUP:
#鼠标按下
  elif event.type == pygame.MOUSEDONW:    

3、读取图片并显示到屏幕

image = pygame.image.load('image_path') #从文件读取图片
img_rect = image.get_rect()
#定位
img_rect.centerx = screen_rect.cetnerx
img_rect.bottom = screen_rect.bottom
#获取长高度
img_width = img_rect.width
img_height = img_rect.height
#按指定位置显示到屏幕
screen.blit(image,img_rect)

4、显示按钮,并响应按下操作

#按钮背景
self.width,self.height = 200,50
self.bg_color = (0,250,0)
self.rect = pygame.Rect(0,0,self.width,self.height)
self.screen.fill(self.bg_color,self.rect)

#按钮字体字号
self.text_color = (255, 255, 255)
self.font = pygame.font.SysFont(None,48)
#将文本转换为图像
btn_img= self.font.render(str,True, self.text_color, self.bg_color )
btn_rect = btn_img.get_rect()
btn_rect .center = self.rect.center
self.screen.blit(btn_img,btn_rect )

#按下
#获取鼠标位置
mouse_x,mouse_y = pygame.mouse.get_pos()
#检查是否按在按钮上面
clicked = play_button.rect.collidepoint(mouse_x,mouse_y)

5、显示文字
self.font = pygame.font.SysFont(None,48)
text_img = self.font.render(text, True,self.text_color, self.bg_color)
text_rect = text_img.get_rect()
screen.blit(text_img,text_rect)

6、pygame方法

#检查精灵和精精灵编组是否相撞
pygame.sprite.spritecollideany(ship,aliens)
#删除相撞的物体,返回键值对
collisions = pygame.sprite.groupcollide(bullets,aliens,True,True)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,602评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,442评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,878评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,306评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,330评论 5 373
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,071评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,382评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,006评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,512评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,965评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,094评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,732评论 4 323
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,283评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,286评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,512评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,536评论 2 354
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,828评论 2 345

推荐阅读更多精彩内容