本文首发于腾讯云+社区,也可关注微信公众号【离不开的网】支持一下,就差你的关注支持了。
pygame的安装: pip install pygame
这是 jupyter notebook 下代码:
%%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下代码:
#使用前导入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()
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
#要使用必先导入
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()
图形移动
#要使用必先导入
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()
# 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.event.get()
获取特定的事件类型
pygame.event.get(type) 注意:每一次获取单独的事件类型之后,要记得取出其他的事件,免得队列里面有太多的事件堆叠起来。
获取特定按键
keys = pygame.key.pressed() 获取所有的按键,里面有true和false来设置是否按下这个按键 keys按键的常量 根据索引获取到的true还是false来得知是否按下了没有
#QUIT,KEYDOWN,KEYUP,MOUSEBUTTONDOWN,MOUSEBUTTONUP
#实时事件循环
# for event in pygame.event.get(): #循环从pygame事件模块里获取的所有的事件
# if event.type in (QUIT, KEYDOWN):#每一个事件都会有type属性
# sys.exit()
keys按键的常量,可查按键常量,也有些日常的如K_你所按下的键的名称(K_a比如这样就是a键)
打字测速游戏
打字测速游戏代码实现如下:
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()
图形
| 扩展: |
| ------------------------------------------------------------ |
| 在这里值得注意的是,图片加载这些有一个IO的操作,我们都知道磁盘的读取速度跟内存的读取速度是没有办法比的,一个天一个地的区别,所以像这个磁盘加载的东西你最好一次性的将图片加载进来,不要每一次(比如说,再循环的过程中,就是在每一帧渲染的时候加载图片,尽量不要),而是在循环的外面也就是在初始化的过程中你就要将图片加载进来,不要再循环里面加载,因为这样你就会降低你的帧的渲染的速度,如果图片很多你想想光是等待的时间,你还要渲染内容,所以这是一个值得注意的问题。 |
pygame.image.save(fontImage,'./fontImage.png')
把fontImage文字对象以图片格式(.jpg .png 等等)保存在当前文件夹
转换
调用转换函数,返回1个新的图像对象,之前的图像对象不改变。
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))
surface对象方法
surface对象(surface表面的意思)以层的形式渲染内容,我们几乎见到的都是surface对象(不管是文字还是图像等)。一层盖一层的形式,如果两个有重叠部分,则上面会覆盖下面的。
精灵
pygame.sprite.Sprite
pygame.sprite.Sprite.__init__(self)
精灵常用的属性
精灵组常用的属性
精灵碰撞相关属性
Pygame--音频混响
声音对象
游戏音乐
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有