前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >16 Python 基础: 重点知识点--Pygame的基础知识梳理

16 Python 基础: 重点知识点--Pygame的基础知识梳理

原创
作者头像
野原测试开发
修改2019-07-24 17:22:20
3K0
修改2019-07-24 17:22:20
举报
文章被收录于专栏:技术探究技术探究

本文首发于腾讯云+社区,也可关注微信公众号【离不开的网】支持一下,就差你的关注支持了。


Pygame--初识pygame

pygame的安装: pip install pygame

image.png
image.png

这是 jupyter notebook 下代码:

代码语言:txt
复制
%%writefile PygameHello.py
#要使用必先导入
import pygame
#导入pygame中的所有常量·
from pygame.locals import *
#需要导入sys模块,系统模块
import sys


#rgb===>(0-255,0-255,0-255)
white = (255,255,255)
blue = (0,0,255)

#初始化PyGame
pygame.init()
#创建1个窗口,设置窗口分辨率的大小
screen = pygame.display.set_mode((600,500))
#设置标题
pygame.display.set_caption('哈哈')

#图标就是一张图片,先载入图片,在设置图标
icon = pygame.image.load('./haimian.jpeg')
pygame.display.set_icon(icon)



#创建1个文字对象,None(如果有中文,一定要设置一种字体,不然出现的是框框,因为用None默认字体没有中文)是设置系统默认字体,60是字体的大小
#myfont = pygame.font.Font(None,30)
# 传入艺术字体文件路径
myfont = pygame.font.Font('./meng.ttf',60)

#设置系统自带的字体对象
# myfont= pygame.font.SysFont('microsoftyaheimicrosoftyaheiui',60)


#参数1是文字对象显示的文字内容,参数2设置为True,参数3,设置字体的颜色
textImage = myfont.render('Hello PyGame',True,white)

while True:
    for event in pygame.event.get():
        if event.type in (QUIT,KEYDOWN):
            sys.exit()
    #设置窗口的背景颜色
    screen.fill(blue)

    #将字体对象绑定到窗口上,并且设置文字显示的位置
    screen.blit(textImage, (100, 100))
    #pygame将内容更新出来
    pygame.display.update()

---------------------------------------------------------------
!python PygameHello.py      #运行python文件

这是pycharm下代码:

代码语言:txt
复制
#使用前导入pygame模块
import pygame
#导入pygame中所有的常量
from pygame.locals import *
#导入系统模块,sys模块
import sys

#初始化pygame
pygame.init()

#颜色变量要在这里定义初始化,在pygame里颜色都是以rgb设置的
#rgb===>(0-255,0-255,0-255)
white=(255,255,255)
black=(0,0,0)

#设置标题
pygame.display.set_caption('changetitle')
#修改标题旁的图标
#图标就是一张图片,先载入图片,在设置图标
#icon=pygame.image.load('./图片完整名,如123.jpg')
#pygame.display.set_icon(icon)

#创建一个窗口,设置窗口分辨率大小
screen=pygame.display.set_mode((800,600))

#初始化或创建一个文字对象,None是不进行配置,默认系统字体,50为字体大小
myfont=pygame.font.Font(None,50)
#传入艺术字体文件路径
#myfont=pygame.font.Font('./艺术字等自己下载的字体文件,如abc.ttf',60)
#SysFont设置系统自带的字体对象
#可通过pygame.font.get_fonts()查看具体字体名,如microsoftyaheimicrosoftyaheiui
#myfont=pygame.font.SysFont('microsoftyaheimicrosoftyaheiui',60)

#用render进行渲染字体的配置,参数1是文字对象显示的文字内容,参数2设置为True,参数3,设置字体的颜色
textImage=myfont.render('hellogpp',True,white)

#如果不定义一个循环,则会一闪而过,因为pygame是一帧一帧运行的,运行完就没有了
while True:
#事件处理的其中一种模式,实现退出机制
for event in pygame.event.get():#循环看是否有退出或按下这些事件,有则退出
if event.type in (QUIT,KEYDOWN):#当有按键按下去和点关闭
#event.type和QUIT,KEYDOWN都是代表一个数字,这里表示这个数字在这个元组的范围里
sys.exit()#这个进程,系统就会退出
#设置窗口背景颜色
screen.fill(black)
#将文字对象绑定到窗口上,用blit进行文字窗口绑定,(要绑定的文字对象,设置文字显示的位置)
screen.blit(textImage,(200,200))
#将内容进行更新
pygame.display.update()

Pygame--圆形与移动矩形绘制

代码语言:txt
复制
    aaline(...)
        aaline(Surface, color, startpos, endpos, blend=1) -> Rect
        draw fine antialiased lines
    
    aalines(...)
        aalines(Surface, color, closed, pointlist, blend=1) -> Rect
        draw a connected sequence of antialiased lines
    
    arc(...)
        arc(Surface, color, Rect, start_angle, stop_angle, width=1) -> Rect
        draw a partial section of an ellipse
    
    circle(...)
        circle(Surface, color, pos, radius, width=0) -> Rect
        draw a circle around a point
    
    ellipse(...)
        ellipse(Surface, color, Rect, width=0) -> Rect
        draw a round shape inside a rectangle
    
    line(...)
        line(Surface, color, start_pos, end_pos, width=1) -> Rect
        draw a straight line segment
    
    lines(...)
        lines(Surface, color, closed, pointlist, width=1) -> Rect
        draw multiple contiguous line segments
    
    polygon(...)
        polygon(Surface, color, pointlist, width=0) -> Rect
        draw a shape with any number of sides
    
    rect(...)
        rect(Surface, color, Rect, width=0) -> Rect
        draw a rectangle shape
代码语言:txt
复制
#要使用必先导入
importpygame
#导入pygame中的所有常量
frompygame.localsimport*
importsys

#初始化PyGame
pygame.init()

#创建一个600*500的窗口

screen=pygame.display.set_mode((800,500))

#设置颜色、位置、圆的半径、宽度
white=(255,255,255)
position=(400,250)
radius=100
width=0

blue=(0,0,255)

whileTrue:
foreventinpygame.event.get():
ifevent.typein(QUIT,KEYDOWN):
sys.exit()
#设置窗口的颜色
screen.fill((0,0,0))

#绘制圆,对应上面定义的值
pygame.draw.circle(screen,white,position,radius,width)
#绘制矩形,(200,150,50)设置颜色,[10,10,150,50]设置开始位置,和宽高
pygame.draw.rect(screen,(200,150,50),[10,10,150,50])

#其他绘制也同理

pygame.display.update()

图形移动

代码语言:txt
复制
#要使用必先导入
import pygame
#导入pygame中的所有常量
from pygame.locals import *
import sys


#初始化PyGame
pygame.init()

#创建一个600*500的窗口
screen = pygame.display.set_mode((800,500))
x = 400
y = 250
xv = 4  #帧率变化速度
yv = 3

#设置定义一下帧率
clock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type in (QUIT,KEYDOWN):
            sys.exit()
    #设置窗口的颜色
    
    #设置绘制图像的帧率,一秒30帧率相当于30像素
    clock.tick(30)
    
    screen.fill((0,0,0))
    x = x + xv
    y = y + yv
    #设置来回运动,碰到边缘就反方向
    if x > 700 or x < 100:
        xv = -xv
        
    if y > 400 or y < 100:
        yv = -yv
        
    #之所以会动,是因为每一帧绘制的位置不一样.
    pygame.draw.circle(screen,(123,245,199),(x,y),100)
    pygame.display.update()
代码语言:txt
复制
# Import a library of functions called 'pygame'
import pygame
from math import pi
 
# Initialize the game engine
pygame.init()
 
# Define the colors we will use in RGB format
#黑色
BLACK = (  0,   0,   0)
#白色
WHITE = (255, 255, 255)
#蓝色
BLUE =  (  0,   0, 255)
#绿色
GREEN = (  0, 255,   0)
#红色
RED =   (255,   0,   0)
 
# 设置800*600分辨率的窗口
size = [800, 600]
screen = pygame.display.set_mode(size)

#设置窗口标题
pygame.display.set_caption("Example code for the draw module")
 
#Loop until the user clicks the close button.
done = False
clock = pygame.time.Clock()
 
while not done:
 
    # This limits the while loop to a max of 10 times per second.
    # Leave this out and we will use all CPU we can.
    clock.tick(10)#当前绘制频率是1秒10帧
     
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done=True # Flag that we are done so we exit this loop
 
    # All drawing code happens after the for loop and but
    # inside the main while done==False loop.
     
    # Clear the screen and set the screen background
    screen.fill(WHITE)
 
    # 绘制1条线段,宽度5像素,参数1绘制到窗口,参数2设置线段的颜色,参数3设置线段的起始位置,参数4是设置终点位置,参数5设置线段宽度
#     pygame.draw.line(screen, GREEN, [50, 50], [500,400], 5)
 
#     # 通过设置多个点绘制线段,参数1绘制到窗口,参数2设置线段的颜色,参数3设置线段是否是闭合线段,参数4设置多个点的列表,参数5设置线段宽度
#     pygame.draw.lines(screen, BLACK, False, [[0, 80], [50, 90], [200, 400], [600, 330]], 5)
    
# #     # Draw on the screen a GREEN line from (0,0) to (50.75) 
# #     # 5 pixels wide.
#     pygame.draw.aaline(screen, GREEN, [0, 50],[50, 80], True)

# #     # Draw a rectangle outline
#     pygame.draw.rect(screen, BLACK, [75, 10, 50, 20], 2)
     
# #     # Draw a solid rectangle
#     pygame.draw.rect(screen, BLACK, [150, 10, 50, 20])
     
# #   绘制椭圆,参数1绘制到什么位置,参数2绘制的颜色,参数3绘制的位置和大小以列表或者元组的形式传入,参数4设置相对应的宽度
#     pygame.draw.ellipse(screen, RED, [225, 10, 50, 20],2) 

# #     # Draw an solid ellipse, using a rectangle as the outside boundaries
# #     pygame.draw.ellipse(screen, RED, [300, 10, 50, 20]) 
 
# #     绘制多边形,参数1绘制到什么位置,参数2绘制的颜色,多边形顶点列表,多边形宽度
#     pygame.draw.polygon(screen, BLACK, [[300,200], [500, 400], [700,450]],5)
  
#     # Draw an arc as part of an ellipse. 
#     # Use radians to determine what angle to draw.

    pygame.draw.rect(screen,(223,156,70),[100,100,400,400],1)
    
    #绘制圆弧,,参数1绘制到什么位置,参数2绘制的颜色,圆弧原本椭圆的大小[位置,宽高],圆弧角度的起始角度,圆弧终点角度(弧度制)
    pygame.draw.arc(screen, BLACK, [100,100,400, 400], 0, pi*3/4, 2)
#     pygame.draw.arc(screen, GREEN,[210, 75, 150, 125], pi/2, pi, 2)
#     pygame.draw.arc(screen, BLUE, [210, 75, 150, 125], pi,3*pi/2, 2)
#     pygame.draw.arc(screen, RED,  [210, 75, 150, 125], 3*pi/2, 2*pi, 2)
    
#     # Draw a circle
#     pygame.draw.circle(screen, BLUE, [60, 250], 40)
    
#     # Go ahead and update the screen with what we've drawn.
#     # This MUST happen after all the other drawing commands.
#重新绘制所有图像
#     pygame.display.flip()
#更新更改的图像
    pygame.display.update()
 
# Be IDLE friendly
pygame.quit()

Pygame--PyGame事件

image.png
image.png
image.png
image.png

常见事件类型

  • QUIT none
  • KEYDOWN unicode, key, mod
  • KEYUP key, mod
  • MOUSEMOTION pos, rel, buttons
  • MOUSEBUTTONUP pos, button
  • MOUSEBUTTONDOWN pos, button

所有的事件都放置到内置队列列表里,取出的方式是先进先出

获取所有的事件

pygame.event.get()

获取特定的事件类型

pygame.event.get(type) 注意:每一次获取单独的事件类型之后,要记得取出其他的事件,免得队列里面有太多的事件堆叠起来。

获取特定按键

keys = pygame.key.pressed() 获取所有的按键,里面有true和false来设置是否按下这个按键 keys按键的常量 根据索引获取到的true还是false来得知是否按下了没有

image.png
image.png
image.png
image.png
代码语言:txt
复制
#QUIT,KEYDOWN,KEYUP,MOUSEBUTTONDOWN,MOUSEBUTTONUP

#实时事件循环
# for event in pygame.event.get(): #循环从pygame事件模块里获取的所有的事件
#     if event.type in (QUIT, KEYDOWN):#每一个事件都会有type属性
#         sys.exit()
image.png
image.png

keys按键的常量,可查按键常量,也有些日常的如K_你所按下的键的名称(K_a比如这样就是a键)

Pygame--打字测速游戏

打字测速游戏

  • 随机出字母A-Z
  • 需要用户快速按下按键,去销毁字母
  • 销毁字母后,又能立即随机出字母A-Z
  • 10秒钟之后计算最终每分钟打印的分数
  • random随机模块
    • 随机65-90的整数来映射--》A-Z的单词(因为ASCII码中对应65是A,90是Z)

ASCII参考 http://tool.oschina.net/commons?type=4

  • pygame.time,
    • 能获取得到程序运行的时间,pygame.time.get_ticks()
    • 设置帧率,clock = pygame.time.Clock(),clock.ticks(30) #设置为每秒帧数为30
  • 显示文字
  • 处理按键事件
  • chr(num)传入十进制的整数---》0-256的ascii的字符
image.png
image.png
image.png
image.png
  • pygame.time.Clock 我们主要用它的tick()来更新时钟,来设置帧率

打字测速游戏代码实现如下:

代码语言:txt
复制
import sys,random,time,pygame   #导入需要用到的模块
from pygame.locals import *

#主程序
pygame.init()

screen = pygame.display.set_mode((800,600))
pygame.display.set_caption('打字测速游戏')      #设置标题

#font1里面设置当前要打的单词是什么?
font1 = pygame.font.Font('./meng.ttf',60)
#font2当前打字的速度
font2 = pygame.font.Font('./meng.ttf',30)

white = (255,255,255)
num = random.randint(65,90)   #随机出65-90的整数
correctNum = 0
time = 0
endScore = None
while True:
    eventList = pygame.event.get()
    for event in eventList:      #循环所有的事件
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            print(eventList)
            print('num:',num)
            print(time)
            if  event.key ==  num+32:     #这里+32是a与A的判断,a97,A65在ASCII码表
                print('按键正确')
                                     #按下正确之后,correctNum加一,还要再重新随机出一个新的数
                correctNum = correctNum + 1    
                num = random.randint(65,90)     
            pass
        elif event.type == KEYUP:
            pass
    
    
    #随机出65-90的整数
    s1 =  chr(num)
        
    #运行的总时间
    time = pygame.time.get_ticks()
    
    
    
    
    if time<10000:
        fontText = font1.render('请快速打出--> %s <--字母'%s1,True,(0,0,0))
        fontV = font2.render('当前的打字速度是{}字/分钟'.format(correctNum*60000/time),True,(0,0,0))


    #     keys = pygame.key.get_pressed()
        screen.fill(white)
        screen.blit(fontText,(100,200))
        screen.blit(fontV,(10,10))
        pygame.display.update() 
    
    else:
        if not endScore: 
            endScore = correctNum 
        fontText = font1.render('游戏结束',True,(0,0,0))
        fontV = font2.render('当前的打字速度是{}字/分钟'.format(endScore*6),True,(0,0,0))
        
        screen.fill(white)
        screen.blit(fontText,(100,200))
        screen.blit(fontV,(130,300))
        pygame.display.update() 

Pygame--位图

图形

  • pygame.image.load — 在磁盘里加载文件图片

| 扩展: |

| ------------------------------------------------------------ |

| 在这里值得注意的是,图片加载这些有一个IO的操作,我们都知道磁盘的读取速度跟内存的读取速度是没有办法比的,一个天一个地的区别,所以像这个磁盘加载的东西你最好一次性的将图片加载进来,不要每一次(比如说,再循环的过程中,就是在每一帧渲染的时候加载图片,尽量不要),而是在循环的外面也就是在初始化的过程中你就要将图片加载进来,不要再循环里面加载,因为这样你就会降低你的帧的渲染的速度,如果图片很多你想想光是等待的时间,你还要渲染内容,所以这是一个值得注意的问题。 |

  • pygame.image.save — 将图片保存到磁盘
image.png
image.png

pygame.image.save(fontImage,'./fontImage.png')

把fontImage文字对象以图片格式(.jpg .png 等等)保存在当前文件夹

转换

调用转换函数,返回1个新的图像对象,之前的图像对象不改变。

  • pygame.transform.flip - 垂直和水平翻转
  • pygame.transform.scale - 调整大小到新的分辨率
  • pygame.transform.rotate - 旋转图像
  • pygame.transform.rotozoom - 过滤的比例和旋转
  • pygame.transform.scale2x - 专业图像倍增器,这个直接放大两倍的,不用设置任何东西
  • pygame.transform.smoothscale - 将表面平滑地缩放到任意大小
  • subsurface - 子图
image.png
image.png
image.png
image.png
代码语言:txt
复制
screen = pygame.display.set_mode()
space = pygame.image.load("图片地址").convert_alpha() #convert_alpha可支持透明 convert不支持
                                                                                                                       #适合JPG/PNG/GIF/BMP/PCX/TIF
screen.blit(space,(0,0))

Pygame--surface对象

surface对象方法

  • pygame.Surface.blit - 将一个图像绘制到另一个
  • pygame.Surface.blits - 将许多图像绘制到另一个
  • pygame.Surface.copy - 创建Surface的新副本
  • pygame.Surface.fill - 用纯色填充Surface
  • pygame.Surface.subsurface - 创建一个引用其父级的新表面
  • pygame.Surface.get_parent - 找到地下的父母
  • pygame.Surface.get_offset - 在父母中找到子地下的位置
  • pygame.Surface.get_size - 获取Surface的尺寸
  • pygame.Surface.get_width - 获取Surface的宽度
  • pygame.Surface.get_height - 获得Surface的高度
  • pygame.Surface.get_rect - 得到Surface的矩形区域
  • pygame.Surface.get_bitsize - 获取Surface像素格式的位深度

surface对象(surface表面的意思)以层的形式渲染内容,我们几乎见到的都是surface对象(不管是文字还是图像等)。一层盖一层的形式,如果两个有重叠部分,则上面会覆盖下面的。

Pygame--精灵

精灵

  • 要定义精灵类,就需要继承pygame.sprite.Sprite
  • 不要忘了写pygame.sprite.Sprite.__init__(self)
  • 精灵对象,必须要有2个属性,image属性(用来显示什么图像)和rect属性(用来决定精灵大小和位置)
  • 之所以精灵会有动画,是根据不断调用update方法,来更改image图像和rect位置。

Pygame--精灵与精灵组

精灵常用的属性

  • pygame.sprite.Sprite.update - 控制精灵行为的方法
  • pygame.sprite.Sprite.add - 将精灵添加到组
  • pygame.sprite.Sprite.remove - 从组中删除精灵
  • pygame.sprite.Sprite.kill - 从所有组中删除Sprite
  • pygame.sprite.Sprite.alive - 精灵属于任何组
  • pygame.sprite.Sprite.groups - 包含此Sprite的组列表

精灵组常用的属性

  • pygame.sprite.Group.sprites - 此组包含的精灵列表
  • pygame.sprite.Group.copy - 复制本集团
  • pygame.sprite.Group.add - 将Sprite添加到此组
  • pygame.sprite.Group.remove - 从集团中删除Sprite
  • pygame.sprite.Group.has - 测试一个组是否包含精灵
  • pygame.sprite.Group.update - 在包含的Sprite上调用update方法
  • pygame.sprite.Group.draw - blit Sprite图片
  • pygame.sprite.Group.clear - 在Sprite上画一个背景
  • pygame.sprite.Group.empty - 删除所有精灵

精灵碰撞相关属性

  • pygame.sprite.spritecollide - 在与另一个精灵相交的组中查找精灵。
  • pygame.sprite.collide_rect - 两个精灵之间的碰撞检测,使用rects。
  • pygame.sprite.collide_rect_ratio - 两个精灵之间的碰撞检测,使用缩放比例的rects。
  • pygame.sprite.collide_circle - 两个精灵之间的碰撞检测,使用圆圈。
  • pygame.sprite.collide_circle_ratio - 两个精灵之间的碰撞检测,使用按比例缩放的圆圈。
  • pygame.sprite.groupcollide - 找到在两组之间发生碰撞的所有精灵。

Pygame--音频混响

  • pygame.mixer.init - 初始化混音器模块
  • pygame.mixer.pre_init - 预设混音器初始化参数
  • pygame.mixer.quit - 未初始化混音器
  • pygame.mixer.get_init - 测试混音器是否初始化
  • pygame.mixer.stop - 停止播放所有声道
  • pygame.mixer.pause - 暂时停止播放所有声道
  • pygame.mixer.unpause - 恢复暂停播放声道
  • pygame.mixer.fadeout - 停止前淡出所有声音的音量
  • pygame.mixer.set_num_channels - 设置播放频道的总数
  • pygame.mixer.get_num_channels - 获取播放频道的总数
  • pygame.mixer.set_reserved - 预留频道自动使用
  • pygame.mixer.find_channel - 找到一个未使用的频道
  • pygame.mixer.get_busy - 测试是否混合了任何声音
  • pygame.mixer.Sound - 从文件或缓冲区对象创建新的Sound对象
  • pygame.mixer.Channel - 创建一个Channel对象来控制播放
image.png
image.png

声音对象

  • pygame.mixer.Sound.play - 开始播放声音
  • pygame.mixer.Sound.stop - 停止声音播放
  • pygame.mixer.Sound.fadeout - 淡出后停止声音播放
  • pygame.mixer.Sound.set_volume - 设置此声音的播放音量
  • pygame.mixer.Sound.get_volume - 获取播放音量
  • pygame.mixer.Sound.get_num_channels - 计算此声音播放的次数
  • pygame.mixer.Sound.get_length - 得到声音的长度
  • pygame.mixer.Sound.get_raw - 返回Sound样本的bytestring副本。

Pygame--游戏音乐

游戏音乐

  • pygame.mixer.music.load - 加载音乐文件以进行播放
  • pygame.mixer.music.play - 开始播放音乐流
  • pygame.mixer.music.rewind - 重启音乐
  • pygame.mixer.music.stop - 停止音乐播放
  • pygame.mixer.music.pause - 暂时停止播放音乐
  • pygame.mixer.music.unpause - 恢复暂停的音乐
  • pygame.mixer.music.fadeout - 淡出后停止播放音乐
  • pygame.mixer.music.set_volume - 设置音乐音量
  • pygame.mixer.music.get_volume - 得到音乐音量
  • pygame.mixer.music.get_busy - 检查音乐流是否正在播放
  • pygame.mixer.music.set_pos - 设定位置来玩
  • pygame.mixer.music.get_pos - 得到音乐播放时间
  • pygame.mixer.music.queue - 排队音乐文件以跟随当前
  • pygame.mixer.music.set_endevent - 播放停止时让音乐发送事件
  • pygame.mixer.music.get_endevent - 获取播放停止时频道发送的事件
image.png
image.png

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Pygame--初识pygame
  • Pygame--圆形与移动矩形绘制
  • Pygame--PyGame事件
  • Pygame--打字测速游戏
  • Pygame--位图
  • Pygame--surface对象
  • Pygame--精灵
  • Pygame--精灵与精灵组
  • Pygame--游戏音乐
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档