day11-pygame应用/2018-07-30
2018-08-07 本文已影响0人
向前冲我在路上
一、pygame事件
1、窗口的建立
import pygame导出第三方pygame库的第一句代码。
a. 初始化python.init()
b. 设置窗口大小,且赋值一个变量。screen = python.display.set_mode((600,400))
c. 设置窗口标题
python.display.set_caption('窗口标题')
pygame.display.flip()
d. 在while True:中的代码
"""
QUIT:关闭按钮被点击事件
MOUSEBUTTONDOWN: 鼠标按下事件
MOUSEBUTTONUP: 鼠标按下弹起
MOUSEMOTION:鼠标移动
鼠标相关事件关心事件产生的位置
KEYDOWN: 键盘按下
KEYUP: 键盘弹起
"""
while True:
# 每次循环检测有没有事件发生
for event in pygame.event.get():
# 不同类型的事件对应的type值不一样
if event.type == pygame.QUIT:
exit()
# 鼠标相关事件
# pos属性,获取鼠标事件产生的位置
if event.type == pygame.MOUSEBUTTONDOWN:
print('鼠标按下', event.pos)
if event.type == pygame.MOUSEBUTTONUP:
print('鼠标弹起', event.pos)
if event.type == pygame.MOUSEMOTION:
print('鼠标移动', event.pos)
# 键盘相关事件
# key属性,被按的按键对应的值的编码
if event.type == pygame.KEYDOWN:
print('键盘按键被按下',chr(event.key))
if event.type == pygame.KEYUP:
print('键盘按钮弹起', chr(event.key))
鼠标的相关事件:
(1)鼠标按下事件
(2)鼠标弹起事件
(3)鼠标移动事件
用pos属性获取鼠标事件发生时坐标的位置
键盘的相关事件:
(1)键盘按键被按下事件
(2)键盘按钮弹起事件
用key属性,被按的按键对应的值的编码,再通过chr(编码)转换成字母就知道是那个键了。
二、鼠标事件的应用
- 判断一个指定的点是否在一个矩形范围中
写一个函数来实现判断功能,
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, bth_color, title_color):
# 画个按钮
"""矩形框"""
pygame.draw.rect(screen, bth_color, (100, 100, 100, 60))
"""文字"""
font = pygame.font.SysFont('Times', 30)
title = font.render('clicke', True, title_color)
screen.blit(title, (120, 120))
3.在指定坐标画一个圆
def rand_color():
"""
产生随机颜色的函数
"""
return randint(0, 255), randint(0, 255), randint(0, 255)
#画一个圆的函数,(画的对象,圆心坐标)
def draw_ball(screen, pos):
pygame.draw.circle(screen, rand_color(), pos, randint(10, 20))
# 只要屏幕上的内容有更新,都需要调用下面这两个方法中的一个
# pygame.display.flip()
pygame.display.update()
if __name__ == '__main__':
#初始化
pygame.init()
#窗口大小
screen = pygame.display.set_mode((600, 400))
#窗口背景色
screen.fill((255,255,255))
# 窗口标题
pygame.display.set_caption('鼠标事件')
# 画个按钮
draw_button(screen, (0, 255, 0), (255, 0, 0))
# """矩形框"""
# pygame.draw.rect(screen,(0, 255, 0),(100, 100, 100, 60))
# """文字"""
# font = pygame.font.SysFont('Times', 30)
# title = font.render('clicke',True,(255, 0, 0))
# screen.blit(title, (120, 120))
pygame.display.flip()
while True:
for event in pygame.event.get():
# 退出
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
# 在指定的坐标处画一个球
# draw_ball(screen, event.pos)
if is_in_rect(event.pos, (100, 100, 100, 60)):
draw_button(screen, (0, 100, 0), (100, 0, 0))
pygame.display.update()
if event.type == pygame.MOUSEBUTTONUP:
if is_in_rect(event.pos, (100, 100, 100, 60)):
draw_button(screen, (0, 255, 0),(255, 0, 0))
pygame.display.update()
if event.type == pygame.MOUSEMOTION:
screen.fill((255, 255, 255))
draw_button(screen, (0, 255, 0), (255, 0, 0))
draw_ball(screen, event.pos)