pygame学习点滴

pygame分为四块

引用/ 初始化/ 事件处理/ 窗口刷新

 普通版壁球游戏

 1 """
 2 引用部分
 3 """
 4 import pygame, sys
 5 
 6 
 7 """
 8 初始化部分
 9 """
10 pygame.init()   # 初始化
11 size = width, height = 600, 400  # 设置窗体大小
12 screen = pygame.display.set_mode(size)  # 调用窗体
13 pygame.display.set_caption("撞球")  # 设置窗体名称
14 speed = [1, 1]  # 设置移动速度
15 BGCOLOR = 23, 45, 23  # 利用RGB形式设置背景颜色
16 ball = pygame.image.load('2.png')  # 增加一个图片对象
17 ballrect = ball.get_rect()  # 为图像加一个外切矩形
18 fps = 60  # 设置刷新帧率
19 fclock = pygame.time.Clock()  # 设置clock对象
20 
21 
22 
23 while True:
24 
25     """
26     事件处理部分
27     """
28     for event in pygame.event.get():  # 所有外部输入设备的操作都在这里
29         if event.type == pygame.QUIT:
30             sys.exit()
31         elif event.type == pygame.KEYDOWN:
32             if event.key == pygame.K_LEFT:
33                 speed[0] = speed[0] if speed[0] == 0 else (abs(speed[0]) - 1) * int(speed[0] / abs(speed[0]))
34             elif event.key == pygame.K_RIGHT:
35                 speed[0] = speed[0] + 1 if speed[0] >= 0 else speed[0] - 1
36             if event.key == pygame.K_DOWN:
37                 speed[1] = speed[1] if speed[1] == 0 else (abs(speed[1]) - 1) * int(speed[1] / abs(speed[1]))
38             elif event.key == pygame.K_UP:
39                 speed[1] = speed[1] + 1 if speed[1] >= 0 else speed[1] - 1
40 
41     ballrect = ballrect.move(speed[0], speed[1])  # 设置外切矩形的运动速度
42     if ballrect.left < 0 or ballrect.right > width:  # 左右到边界
43         speed[0] = -speed[0]
44     if ballrect.top < 0 or ballrect.bottom > height:  # 上下到边界
45         speed[1] = -speed[1]
46 
47     """
48     窗口刷新部分
49     """
50     screen.fill(BGCOLOR)  # 为窗口填充背景色
51     screen.blit(ball, ballrect)  # 让球和外切矩形动起来
52     pygame.display.update()  # 刷新窗口
53     fclock.tick(fps)  # 设置刷行频率

发现问题:

如果把

32     ballrect = ballrect.move(speed[0], speed[1])  # 设置外切矩形的运动速度
33     if ballrect.left < 0 or ballrect.right > width:  # 左右到边界
34         speed[0] = -speed[0]
35     if ballrect.top < 0 or ballrect.bottom > height:  # 上下到边界
36         speed[1] = -speed[1]


这几行代码写到上面的for循环里面,整个游戏运行就会特别卡

屏幕需求设置

屏幕大小可改变pygame.RESIZABLE

扫描二维码关注公众号,回复: 4273951 查看本文章

游戏全屏pygame.FULLSCREEN

游戏无边框pygame.NOFRAME

pygame.display.set_mode((1440, 900), pygame.FULLSCREEN)


pygame.display.Info()

current_w

current_h

当前窗口的宽度,高度

更改标题栏内容和图标

pygame.display.set_caption("撞球")  # 设置标题信息
pygame.display.get_caption()  # 获得图标和标题信息
pygame.display.set_icon()  # 设置图标信息


窗口感知和刷新

pygame.display.get_active() #判断窗口是否被最小化
pygame.display.flip()  # 重新绘制所有窗口
pygame.display.update()  # 重新绘制变化的元素

窗口颜色:

Color类

rgba a表示透明度

.normalize 归一到0-1之间

图形绘制:

draw类

pygame.draw.rect(screen, color, rect, width=0)

猜你喜欢

转载自www.cnblogs.com/btxlc/p/10031384.html
今日推荐