目录一、课程内容二、学习目标三、知识点1.pygame.mouse.get_pos()2.pygame.Rect3.pygame.Surface.get_rect()四、难点五、延伸1.mouse模块2.Rect类
mouse模块用于获取或设置“鼠标”相关信息。
get_pos()函数用于获取鼠标光标在游戏窗口中的位置,返回值为光标水平方向坐标和垂直方向坐标组成的元组。
可以通过在游戏窗口上打印返回值信息来验证函数的功能,代码如下:
ximport pygamefrom pygame.locals import *from sys import exitpygame.init()screen = pygame.display.set_mode((400, 200))font = pygame.font.SysFont(None, 30)BLACK = (0, 0, 0)WHITE = (255, 255, 255)while True: for event in pygame.event.get(): if event.type == QUIT: exit() pos = pygame.mouse.get_pos() img = font.render(str(pos), True, WHITE) screen.fill(BLACK) screen.blit(img, (10, 10)) pygame.display.update()在窗口中移动鼠标,左上角的位置信息也跟着改变。效果如图:

Rect类的对象用于存储和操作矩形区域。
创建对象
xxxxxxxxxxRect(left, top, width, height) left、top用于设置矩形左上角的坐标;width、height用于设置矩形的宽度和高度
访问属性
Rect对象有一些用于获取或设置矩形位置的属性,例如:
xxxxxxxxxximport pygamerect = pygame.Rect(100, 200, 300, 400)print(rect.topleft)print(rect.size)print(rect.center)print(rect.centerx)输出为:
xxxxxxxxxx(100, 200)(300, 400)(250, 400)250调用方法
Rect对象还有一些用于操作矩形或进行矩形间关系检测的方法,例如:
xxxxxxxxxximport pygamerect1 = pygame.Rect(100, 200, 300, 400)rect2 = pygame.Rect(300, 300, 200, 200)print(rect1.contains(rect2))rect2 = rect2.move(-150, 0)print(rect1.contains(rect2))输出为:
xxxxxxxxxx01第一次使用contains方法检测rect1是否包含rect2时,结果为0;使用move方法移动过rect2的位置后再次执行检测,结果为1。
使用draw模块的rect函数将两个矩形绘制到窗口上,效果更加明显。
Suface类的对象用于表示具有固定分辨率的任何图像,比如游戏窗口、图片等。
get_rect()函数用于获取Surface对象对应的矩形区域,其中top、left参数初始值始终为0。例如:
xxxxxxxxxximport pygamepath = 'resources/images/'wanzai = pygame.image.load(path + 'wanzai.png')rect = wanzai.get_rect()print(rect)输出为:
xxxxxxxxxx<rect(0, 0, 95, 135)>传递Rect对象作为blit方法的"位置"参数进行绘制时,默认使用其topleft属性。
“面向对象”思想的理解和应用。
“面向过程”的实现方式重在分析完成一个任务的过程或步骤,而“面向对象”需要找出与需求相关的对象,进而分析对象具备的静态特征和动态行为。
pygame.mouse.set_pos():设置鼠标光标的位置
pygame.mouse.get_rel():获取鼠标自上次调用该函数后的偏移量
pygame.mouse.set_visible():设置鼠标光标的可见性,参数值为False则隐藏光标
pygame.Rect.inflate(x, y):增大或减小矩形的尺寸,但矩形中心点保持不变。
pygame.Rect.collidepoint(x, y):测试参数指定的“点”是否在矩形内
pygame.Rect.colliderect(Rect):测试两个矩形是否重叠
想要了解更多信息,可以参考Pygame官方文档:https://www.pygame.org/docs/ref/rect.html