pygame的鼠标事件
两个实例:
import pygame
import random
# 随机颜色
def rand_color():
return (random.randint(0,255),
random.randint(0,255),
random.randint(0,255))
# 画圆
def draw_circle(screen,pos):
pygame.draw.circle(screen,
rand_color(),
event.pos,
random.randint(10, 40))
# 判断点击范围
def is_in_rect(point,rect):
x,y = point
rx,ry,rw,rh = rect
if (rx <= x <= rx+rw) and (ry <= y <= ry+rh):
return True
return False
# 画一个按钮
def draw_button(screen,b_color,t_color):
pygame.draw.rect(screen, b_color, (125, 125, 90, 40))
font = pygame.font.SysFont('Times', 30)
button = font.render('clicke', True, t_color)
screen.blit(button,(135,125))
return button
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode((500,500))
screen.fill((255,255,255))
# 设置窗口标题
pygame.display.set_caption('鼠标事件')
while True:
rect = (125, 125, 90, 40)
# draw_button(screen,(0,255,0),(255,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
# 判断鼠标点击的位置是否在框内,在画一个按钮
if event.type == pygame.MOUSEBUTTONDOWN:
# draw_circle(screen,event.pos)
if is_in_rect(event.pos,rect):
draw_button(screen, (255, 0, 0), (0, 255, 0))
pygame.display.flip()
# 鼠标弹起返回按钮原先的状态
if event.type == pygame.MOUSEBUTTONUP:
draw_button(screen, (0, 255, 0), (255, 0, 0))
pygame.display.flip()
# 鼠标移动带圆
if event.type == pygame.MOUSEMOTION:
screen.fill((255,255,255))
draw_button(screen, (0, 255, 0), (255, 0, 0))
draw_circle(screen,event.pos)
pygame.display.flip()
# 要求:先在屏幕上显示一张图片,当鼠标按下移动的时候,拽着图片跟着一起动。鼠标弹起就不动了
import pygame
# 判断点在某个范围内
def is_in_rect(point,rect):
x,y = point
rx,ry,rw,rh = rect
if (rx <= x <= rx+rw) and (ry <= y <= ry+rh):
return True
return False
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode((500,500))
screen.fill((255,255,255))
# 设置窗口标题
pygame.display.set_caption('鼠标事件2')
image = pygame.image.load('hero1.png')
screen.blit(image,(125,125))
iw,ih = image.get_size()
rect = (125, 125, iw, ih)
pygame.display.flip()
# 移动状态
flag = False
while True:
# draw_button(screen,(0,255,0),(255,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
# 按下可动
if event.type == pygame.MOUSEBUTTONDOWN:
if is_in_rect(event.pos,rect):
flag = True
# 弹起不可动
if event.type == pygame.MOUSEBUTTONUP:
flag = False
# 画图片
if event.type == pygame.MOUSEMOTION:
x,y = event.pos
if flag:
screen.fill((255,255,255))
screen.blit(image,(x-iw/2,y-ih/2))
rect = (x-iw/2,y-ih/2,iw,ih)
pygame.display.flip()