python项目练手(一)------飞船大战游戏

python学习有一段时间了,想开发一些有意思的项目,就从《python 编程 从入门到实战》上找了这个项目练手,下面时我当时遇到的一些问题以及记录吧。
模块安装
开发python游戏,主要是pygame模块,我用的是pip安装,此处不做过多的介绍。
pygame窗口创建
alien_invasion.py

import sys
import pygame
from settings import Settings
def run_game():
    #初始化游戏,并建立一个屏幕对象
    pygame.init()#初始化背景设置
    ai_settings=Settings()
    screen=pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height))#创建显示窗口,(1200,800)指定了游戏窗口的尺寸
    pygame.display.set_caption('Alien innvasion')#显示标题

    #游戏主循环
    while True:
        for event in pygame.event.get():  #监听鼠标和键盘的事件
            if  event.type == pygame.QUIT:

                sys.exit()
        screen.fill(ai_settings.bg_color)#用背景色填充屏幕
        pygame.display.flip()#不断更新屏幕,让最新绘制的屏幕可见,以显示元素的新位置
run_game() #初始化游戏,并开始主循环

此处的settings模块代码:
settings.py

class Settings():
    """存储要设置的类"""
    def __init__(self):
        self.screen_width = 800
        self.screen_height = 600
        self.bg_color = (210,210,210)

代码的理解参考注释,其实python可以说是一门傻瓜式语言,不难懂,要记住的就是pygame的一些常用方法。

  • pygame的方法:
    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 就是我们在学的这个东西了……
    pygame.rect 管理矩形区域
    pygame.sndarray 操作声音数据
    pygame.sprite 操作移动图像
    pygame.surface 管理图像和屏幕
    pygame.surfarray 管理点阵图像数据
    pygame.time 管理时间和帧信息
    pygame.transform 缩放和移动图像
    添加飞船图像
    图片素材链接http://pixabay.com/,格式.bmp较好
    1 创建一个ship模块,管理飞船的行为
    ship.py
import pygame

class Ship():
    def __init__(self,screen):
        self.screen=screen
        self.image=pygame.image.load('images/feichuan.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#将飞船放置在屏幕底部中央

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

然后对alien_invasion.py添加如下代码

ship = Ship(screen)#创建飞船
....
ship.blitem()

运行结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42069523/article/details/81435468