✕
游戏鼠标的操作大多我们关注的是移动,点击等,pygame有两种(我晓得的)获取鼠标位置,点击。
获取鼠标移动方法1:
事件获取鼠标位置,键按下,弹起,
# 鼠标位置event.type == pygame.MOUSEMOTION# 鼠标按下
event.type == pygame.MOUSEBUTTONDOWN
# 鼠标弹起
event.type == pygame.MOUSEBUTTONUP
捕获的事件中,
鼠标位置是:
if event.type == pygame.MOUSEMOTION:
# print("移动")
# print(event.pos) # 查看移动的坐标
鼠标按下是:
左 = 1 滑轮 =2 右键=3
if event.button == 1:
print("鼠标左键按下")
elif event.button == 3:
print("鼠标右键按起")
鼠标抬起是:
左 = 1 滑轮 =2 右键=3
if event.button == 1:
print("鼠标左键抬起")
elif event.button == 3:
print("鼠标右键抬起")
晓得这之后我们就可以做一个跟随鼠标移动的球体了,并且利用鼠标左右键来控制球的大小。
上篇我们提到过,事件获取不能连续获取点击状态所以不能连续获取按下的情况!但是能捕捉到弹起的操作!
测试代码:按下左右键球体体积增大,松开减少!
import pygame
W = 600
H = 500
def main():
# 初始化pygame模块
pygame.init()
# 设置窗口大小
screen = pygame.display.set_mode((W,H))
# 设置窗口标题
pygame.display.set_caption('窗口标题')
# 球的初始位置
ball_x, ball_y = 0, 0
# 球的初始大小
q = 30
while True:
# 重绘屏幕
screen.fill((0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit(0)
elif event.type == pygame.MOUSEMOTION:
# print("移动")
# print(event.pos) # 查看移动的坐标
ball_x, ball_y = event.pos
elif event.type == pygame.MOUSEBUTTONDOWN:
# print(event)
if event.button == 1:
print("鼠标左键按下")
q += 10
elif event.button == 3:
print("鼠标右键按起")
q += 20
elif event.type == pygame.MOUSEBUTTONUP:
# print(event)
if event.button == 1:
print("鼠标左键抬起")
q -= 10
elif event.button == 3:
print("鼠标右键抬起")
q -= 20
pygame.draw.circle(screen, (255, 0, 0), [ball_x, ball_y], q)
# 刷新显示
pygame.display.update()
if __name__ == '__main__':
main()
获取鼠标移动方法2:
利用pygame.mouse 模块来获取鼠标的操作。
我们记几个常用的:
鼠标是否在窗口内:
pygame.mouse.get_focused()
鼠标光标的位置:
ball_x, ball_y = pygame.mouse.get_pos()
鼠标按键:
mouse = pygame.mouse.get_pressed()
返回值是一个元祖,类似(0,0,0)
如果左键按下则返回(1,0,0),
滚轮按下返回(0,1,0),
右键按下返回(0,0,1),
如果鼠标没有松开则一直返回,
返回的频率根据我们界面的刷新频率相同,
1秒返回很多很多次。。。
# 检测程序界面是否获得鼠标焦点
if pygame.mouse.get_focused():
# 获取光标位置,2个值
ball_x, ball_y = pygame.mouse.get_pos()
# 鼠标点击一次会被捕捉多次,可以通过刷新频率变更
clock.tick(30)
# 获取光标的按键情况 3个值,左 滚轮 右
mouse = pygame.mouse.get_pressed()
if mouse[0] == 1:
print("左键点击次数")
elif mouse[2] == 1:
print("左键点击次数")
鼠标按下后球体大小改变完整代码:
注意:球体太小会报错, 所以设置个最小值。
import pygame
W = 600
H = 500
def main():
# 初始化pygame模块
pygame.init()
# 设置窗口大小
screen = pygame.display.set_mode((W,H))
# 设置窗口标题
pygame.display.set_caption('窗口标题')
# 球的大小
q = 30
clock = pygame.time.Clock()
while True:
# 重绘屏幕
screen.fill((0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit(0)
# 检测程序界面是否获得鼠标焦点
if pygame.mouse.get_focused():
# 获取光标位置,2个值
ball_x, ball_y = pygame.mouse.get_pos()
# 鼠标点击一次会被捕捉多次,可以通过刷新频率变更
clock.tick(30)
# 获取光标的按键情况 3个值,左 滚轮 右
mouse = pygame.mouse.get_pressed()
if mouse[0] == 1:
q += 1
print("点击次数")
elif mouse[2] == 1:
q -= 1
# 避免太小太大
if q < 20:
q = 20
if q > 100:
q = 20
# 画个球
pygame.draw.circle(screen, (255, 0, 0),[ball_x,ball_y],q)
# 刷新显示
pygame.display.update()
if __name__ == '__main__':
main()