2025年4月12日 星期六 乙巳(蛇)年 正月十三 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

python3 pygame简单使用

时间:08-22来源:作者:点击数:29

安装

  • pip install pygame

1:导入pygame库,以及pygame中的所有常量

  • import pygame
  • from pygame.locals import *

2:初始化窗口

  • screen=pygame.display.set_mode((800,600))

实际上pygame.display.set_mode()这个函数会返回一个Surface对象,他是位图的一种。

3:加载和显示图标

  • #加载图标
  • icon=pygame.image.load("python_ico.jpg").convert_alpha()
  • #显示图标
  • pygame.display.set_icon(icon)

4:设置标题

  • pygame.display.set_caption("python_ico")

5:显示背景图片

  • #背景图片
  • background=pygame.image.load("python_ico.jpg").convert_alpha()
  • screen.blit(background,(0,0))
  • #更新显示屏幕
  • pygame.display.update()

pygame.image.load()函数用来加载位图,convert_alpha()方法会使用透明的方法绘制前景对象,因此在加载一个有alpha通道的素材时(比如PNG TGA),需要使用convert_alpha()方法,当然普通的图片也是可以使用这个方法的,用了也不会有什么副作用。

前面说过pygam.image.load()会返回一个surface对象,这个对象有一个blit方法,这个方法有两个参数,一个是加载完成的位图,第二个参数是绘制起始坐标。

完整代码

  • # -*- coding:utf-8 -*-
  • import pygame
  • from pygame.locals import *
  • def main():
  • pygame.mixer.init()
  • # 创建一个800x600的窗口
  • screen = pygame.display.set_mode((800, 600))
  • # 加载图标
  • icon = pygame.image.load("python_ico.jpg").convert_alpha()
  • # 显示图标
  • pygame.display.set_icon(icon)
  • # 设置标题
  • pygame.display.set_caption("python_ico")
  • # 背景图片
  • background = pygame.image.load("python_ico.jpg").convert_alpha()
  • while True:
  • for event in pygame.event.get():
  • if event.type == QUIT:
  • return
  • screen.blit(background, (0, 0))
  • # 更新显示屏幕
  • pygame.display.update()
  • if __name__ == '__main__':
  • main()
image.png

pygame加载音乐

1:导入pygame库,并且初始化声音播放模块

  • import pygame
  • pygame.mixer.init()

2:pygame提供了两个加载音乐文件的方法

pygame.mixer.Sound,主要加载ogg和wav音频文件。

pygame.mixer.music,主要加载mp3音频文件。

3:使用方法分别如下。

  • pygame.mixer.Sound
  • music=pygame.mixer.Sound("005.wav")
  • while True:
  • music.play()

pygame.mixer.Sound会返回一个Sound对象,该对象有stop,play等方法。

注意,这里的音频文件是采用流的方式打开,并不会一次性播放完毕,所以需要使用while循环。

  • # -*- conding:utf-8 -*-
  • import pygame
  • pygame.mixer.init()
  • music=pygame.mixer.Sound("006.wav")
  • while True:
  • music.play()
  • pygame.mixer.music
  • # -*- conding:utf-8 -*-
  • import pygame
  • pygame.mixer.init()
  • #加载音乐
  • pygame.mixer.music.load("006.mp3")
  • while True:
  • #检查音乐流播放,有返回True,没有返回False
  • #如果没有音乐流则选择播放
  • if pygame.mixer.music.get_busy()==False:
  • pygame.mixer.music.play()

此方法同Sound方法一样!都是以流的方式呈现,所以需要使用while循环!


pygame.Surface

上面我们说到pygame.image.load()返回的其实是一个surface对象,而pygame中专门有一个Surface类,并且这个类中还有许多的方法。

pygame.surface.blit — 画一个图像到另一个

pygame.surface.convert — 改变图片的像素格式

pygame.surface.convert_alpha — 改变图像的每个像素的像素格式包括阿尔法

pygame.surface.copy — 创建一个新的表面复制

pygame.surface.fill — 表面用纯色填充

pygame.surface.scroll — 在地方的表面形象转换

pygame.surface.set_colorkey — 设置透明色键

pygame.surface.get_colorkey — 获取当前透明色键

pygame.surface.set_alpha — 设置为全表面图像的alpha值

pygame.surface.get_alpha — 获取当前表面透明度值

pygame.surface.lock — 像素访问表面内存锁

pygame.surface.unlock — 从像素的访问解锁记忆

pygame.surface.mustlock — 测试如果表面需要锁定

pygame.surface.get_locked — 测试如果表面电流锁定

pygame.surface.get_locks — 获取表面的锁

pygame.surface.get_at — 在单个像素的颜色值的获得

pygame.surface.set_at — 设置为一个像素的颜色值

pygame.surface.get_at_mapped — 在一个单一的像素颜色值的映射

pygame.surface.get_palette — 得到一个8位的表面颜色索引调色板

pygame.surface.get_palette_at — 得到在调色板的颜色单一入口

pygame.surface.set_palette — 对于一个8位的表面设置的调色板

pygame.surface.set_palette_at — 设置在一个8位面单索引的颜色调色板

pygame.surface.map _ RGB — 将一个颜色映射的颜色值

pygame.surface.unmap_rgb — 将一个整数的颜色值映射成一个颜色

pygame.surface.set_clip — 设置当前剪辑区域的表面

pygame.surface.get_clip — 获取当前剪辑区域的表面

pygame.surface.subsurface — 创建一个新表,参考其母

pygame.surface.get_parent — 找到一个地下的父母

pygame.surface.get_abs_parent — 找到一个地下的顶级父

pygame.surface.get_offset — 发现在父母的孩子地下的位置

pygame.surface.get_abs_offset — 发现在其最高水平的孩子地下的绝对位置

pygame.surface.get_size — 得到表面的尺寸

pygame.surface.get_width — 得到表面的宽度

pygame.surface.get_height — 得到表面高度

pygame.surface.get_rect — 得到表面的矩形区域

pygame.surface.get_bitsize — 得到表面的像素格式的位深度

pygame.surface.get_bytesize — 习惯每面像素字节

pygame.surface.get_flags — 用于表面附加标志

pygame.surface.get_pitch — 得到每面行的字节数

pygame.surface.get_masks — 该掩码需要颜色和映射的整数之间的转换

pygame.surface.set_masks — 组需要一种颜色和一个映射的整数之间的转换的掩码

pygame.surface.get_shifts — 位的变化需要一种颜色和一个映射的整数之间的转换

pygame.surface.set_shifts — 设置位移所需颜色和映射的整数之间的转换

pygame.surface.get_losses — 有位用于颜色和映射的整数之间的转换

pygame.surface.get_bounding_rect — 找到最小的矩形包含数据

pygame.surface.get_view — 返回一个表面的像素缓存视图。

pygame.surface.get_buffer — 获取表面的像素缓冲区对象。

_pixels_address pygame。表面。 — 像素缓冲区地址

blit,convert,convert_alpah,这几个比较有印象吧!

这里我们着重介绍一下blit,fill。

我们在写一个简单的窗口程序。

创建一个600x400的窗口

  • screen=pygame.display.set_mode((600,400),0,32)

为窗口填充颜色

  • screen.fill(color=(255,255,0))
  • fill填充颜色必须使用RGB颜色序列例如(255,0,0)是红色,(255,255,0)是黄色等。

完整代码

  • # -*- conding:utf-8 -*-
  • import pygame
  • import sys
  • pygame.init()
  • screen=pygame.display.set_mode((600,400),0,32)
  • while True:
  • for event in pygame.event.get():
  • if event.type == pygame.QUIT:
  • sys.exit()
  • screen.fill(color=(255,255,0))
  • pygame.display.update()
image.png

这里着重讲一下  for event in pygame.event.get()

这是一个实施事件循环,该循环会创建当前等待处理的事件的一个列表,然后使用for循环来遍历里面的事件。这样,我们将会根据事件产生的顺序依次地进行不同的操作。常见的事件是按键按下,按键释放以及鼠标移动。通常需要最先处理QUIT事件(在用户关闭窗口的时候会产生该事件。)

如果不加这个事件循环的话,那么窗口程序运行会出现一点卡顿的现象


文字的使用

pygame提供了字体处理,但是对中文的支持貌似不是很好!

pygame对于字体的处理主要是pygame.font.Font()对象

对象中的方法如下

pygame.font.font.render— 在一个新的表面绘制文本

pygame.font.font.size —确定需要渲染文本的空间量

pygame.font.font.set_underline —如果文本呈现的下划线

pygame.font.font.get_underline —检查是否带下划线的文本将被呈现

pygame.font.font.set_bold —启用粗体文字假渲染

pygame.font.font.get_bold —检查文本呈现的是大胆

pygame.font.font.set_italic —使斜体假渲染

pygame.font.font.metrics —获取在过去的各个字符度量。

pygame.font.font.get_italic —如果支票将rendered italic文本

pygame.font.font.get_linesize —获得该字体的文本的行间距

pygame.font.font.get_height —得到的字体高度

pygame.font.font.get_ascent —获得字体的提升

pygame.font.font.get_descent —获得字体的血统

其中最常用的是pygame.font.font.render()方法。

这个方法一个接收三个参数,1:文本内容,2:(通常传入0或者1)3:颜色的RGB值

  • #创建字体对象
  • font=pygame.font.Font(None,56)
  • #文本与颜色
  • text=font.render("I love Python",1,(255,0,0))

上面代码我们实例化一个字体对象,(第一个参数是字体,第二个参数是字体大小)

然后就是绘制文本内容为”I lvoe Python”,并且设置字体的颜色为红色。

这个font也是一个surface对象!可以使用surface对象的方法。

例如可以使用Surface对象中个get_rect方法设置他的位置(center=(x,y)x,y是坐标值)

  • textpos = text.get_rect(center=(150,150))

完整代码

  • # -*- conding:utf-8 -*-
  • import pygame
  • import sys
  • pygame.init()
  • # 绘制窗口
  • screen = pygame.display.set_mode((600, 400), 0, 32)
  • # 绘制背景
  • background = pygame.Surface(screen.get_size())
  • # 填充颜色
  • background.fill(color=(255, 0, 0))
  • # 创建字体对象
  • font = pygame.font.Font(None, 56)
  • # 文本与颜色
  • text = font.render("I love Python", 1, (255, 255,255))
  • # 获取中心的坐标
  • center = (background.get_width() / 2, background.get_height() / 2)
  • # 获取设置后新的坐标区域
  • textpos = text.get_rect(center=center)
  • while True:
  • for event in pygame.event.get():
  • if event.type == pygame.QUIT:
  • sys.exit()
  • # 将字体填充到背景
  • background.blit(text, textpos)
  • # 将背景填充到窗口
  • screen.blit(background, (0, 0))
  • pygame.display.update()

效果图

image.png

最后要注意一下层级关系,先将文字填充到背景层上,然后再将背景填充到屏幕上。


pygame 坦克自动移动

让坦克自动跑起来

这里需要一个坦克的图。tanke.jpg

  • # -*- coding:utf-8 -*-
  • import pygame, sys
  • from pygame.locals import *
  • pygame.init()
  • FPS = 30
  • fpsClock = pygame.time.Clock()
  • DISPLAY_SURF = pygame.display.set_mode((400, 300), 0, 32)
  • pygame.display.set_caption("TankMoving")
  • WHITE = (255, 255, 255)
  • catImg = pygame.image.load("tanke.jpg")
  • catX = 10
  • catY = 10
  • direction = 'right'
  • while True:
  • DISPLAY_SURF.fill(WHITE)
  • if direction == "right":
  • catX += 5
  • if catX == 280:
  • direction = 'down'
  • elif direction == 'down':
  • catY += 5
  • if catY == 220:
  • direction = 'left'
  • elif direction == 'left':
  • catX -= 5
  • if catX == 10:
  • direction = 'up'
  • elif direction == 'up':
  • catY -= 5
  • if catY == 10:
  • direction = 'right'
  • DISPLAY_SURF.blit(catImg, (catX, catY))
  • for event in pygame.event.get():
  • if event.type == QUIT:
  • pygame.quit()
  • sys.exit()
  • pygame.display.update()
  • fpsClock.tick(FPS)

后来想了一想让它自动随机的跑,于是改了一下。

  • # -*- coding:utf-8 -*-
  • import pygame, sys, random
  • from pygame.locals import *
  • pygame.init()
  • FPS = 30
  • fpsClock = pygame.time.Clock()
  • DISPLAY_SURF = pygame.display.set_mode((400, 300), 0, 32)
  • pygame.display.set_caption("TankMoving")
  • WHITE = (255, 255, 255)
  • catImg = pygame.image.load("tanke.jpg")
  • '''
  • catX = 10
  • catY = 10
  • direction = 'right'
  • '''
  • catX = 200
  • catY = 140
  • while True:
  • DISPLAY_SURF.fill(WHITE)
  • temp = random.randrange(0, 4) # 0-3
  • if temp == 0:
  • catX += 10
  • if catX == 280:
  • catX -= 10
  • elif temp == 1:
  • catY += 10
  • if catY == 220:
  • catY -= 10
  • elif temp == 2:
  • catX -= 10
  • if catX == 10:
  • catX += 10
  • elif temp == 3:
  • catY -= 10
  • if catY == 10:
  • catY += 10
  • DISPLAY_SURF.blit(catImg, (catX, catY))
  • for event in pygame.event.get():
  • if event.type == QUIT:
  • pygame.quit()
  • sys.exit()
  • pygame.display.update()
  • fpsClock.tick(FPS)
jdfw.gif
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐