美文网首页
day11 Pygame Ⅱ 事件处理2018-07-30

day11 Pygame Ⅱ 事件处理2018-07-30

作者: LPP27149 | 来源:发表于2018-07-30 21:54 被阅读0次

一、Pygame中的事件

鼠标事件和键盘事件

  监测鼠标、键盘事件

  • 鼠标事件
鼠标事件
pygame.QUIT 退出按钮被点击
pygame.MOUSEBUTTONDOWN 鼠标按下
pygame.MOUSEBUTTONDOWN 鼠标弹起
pygame.MOUSEMOTION 鼠标移动
  • 键盘事件
键盘事件
pygame.KEYUP 按键按下
pygame.KEYUP 按键弹起

# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name:     test
   Description :
   Author :       LPP
   date:          2018/7/30
-------------------------------------------------
   Change Activity:
                   2018/7/30:
-------------------------------------------------
"""
import pygame

if __name__ == '__main__':
    width = 600
    height = 400
    pygame.init()
    screen = pygame.display.set_mode((width, height))
    screen.fill((255, 255, 255))
    # 设置窗口标题
    pygame.display.set_caption('游戏事件')
    """
    QUIT: 关闭按钮被点击事件
    MOUSEBUTTONDOWN: 鼠标按下
    MOUSEBUTTONUP: 鼠标弹起
    MOUSEMOTION: 鼠标移动
    
    
    KEYDOWN: 键盘按下
    KEYUP: 键盘弹起
    """

    pygame.display.flip()
    while True:
        for event in pygame.event.get():
            # 不同事件对应不同的type值
            if event.type == pygame.QUIT:
                exit()

            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('键盘按键弹起', event.key)


二、鼠标事件的应用1

  事件的监测和处理

点击前 点击中
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name:     02-鼠标事件的应用
   Description :
   Author :       LPP
   date:          2018/7/30
-------------------------------------------------
   Change Activity:
                   2018/7/30:
-------------------------------------------------
"""
import pygame
from random import randint


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())
    pygame.display.flip()


def is_in_rect(point, rect):
    """
    判断指定的点是否在指定矩形范围内
    :param point: 指定的点
    :param rect: 指定的矩形范围
    :return: True / False
    """
    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, btn_color):
    """
    画一个按钮
    :param screen:
    :param btn_color:
    :param title_color:
    :return:
    """
    # # 画个按钮
    pygame.draw.rect(screen, btn_color, (166, 155, 268, 90))


def show_text(text, pos, title_color):
    font = pygame.font.Font('./aa.ttf', 30)
    title = font.render(text, True, title_color)
    screen.blit(title, pos)
    pygame.display.flip()


if __name__ == '__main__':
    width = 600
    height = 400
    pygame.init()
    screen = pygame.display.set_mode((width, height))
    screen.fill((255, 255, 255))
    pygame.display.set_caption('鼠标事件')

    # 画个按钮
    # pygame.draw.rect(screen, (0, 255, 0), (100, 100, 160, 90))
    # font = pygame.font.Font('./aa.ttf', 30)
    # title = font.render('屠龙宝刀,点击就送!!!', True, (255, 0, 0))
    screen.fill((255, 255, 255))
    draw_button(screen, (0, 255, 0))
    pygame.display.update()

    while True:
        show_text('屠龙宝刀,点击就送!!!', (166, 183), (0, 0, 0))
        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, (166, 155, 268, 90)):
                   draw_button(screen, (255, 0, 0))
                   show_text('屠龙宝刀,点击就送!!!', (166, 183), (0, 0, 0))
                   pygame.display.flip()

            if event.type == pygame.MOUSEBUTTONUP:
                if is_in_rect(event.pos, (100, 100, 160, 90)):
                    draw_button(screen, (0, 255, 0))
                    pygame.display.flip()

            if event.type == pygame.MOUSEMOTION:
                screen.fill((255, 255, 255))
                draw_button(screen, (0, 255, 0))
                draw_ball(screen, event.pos)

三、鼠标事件的应用2

  通过监测鼠标事件实现窗口内图片拖动

原始位置 拖动之后
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name:     03-鼠标事件应用2
   Description :
   Author :       LPP
   date:          2018/7/30
-------------------------------------------------
   Change Activity:
                   2018/7/30:
-------------------------------------------------
"""
import pygame


def is_in_rect(point, rect):
    """
    判断指定的点是否在指定矩形范围内
    :param point: 指定的点
    :param rect: 指定的矩形范围
    :return: True / False
    """
    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((640, 360))
    screen.fill((255, 255, 255))
    image = pygame.image.load(r'C:/Users/96240/Desktop/海绵宝宝.jpg')
    image_x = 0
    image_y = 0
    img_w, img_h = image.get_size()
    screen.blit(image, (image_x, image_y))

    is_removable = False

    pygame.display.flip()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()

            if event.type == pygame.MOUSEBUTTONUP:
                    is_removable = False

            if event.type == pygame.MOUSEBUTTONDOWN:
                if is_in_rect(event.pos, (image_x, image_y, img_w, img_h)):
                    is_removable = True

            if event.type == pygame.MOUSEMOTION:
                if is_removable:
                    screen.fill((255, 255, 255))
                    x, y = event.pos
                    image_x, image_y = (x - img_w/2, y - img_h/2)
                    screen.blit(image, (x - img_w/2, y - img_h/2))
                    pygame.display.flip()

四、动画效果

   通过持续绘制图形实现动画效果

pygame三角函数动画的截图
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name:     04-动画效果
   Description :
   Author :       LPP
   date:          2018/7/30
-------------------------------------------------
   Change Activity:
                   2018/7/30:
-------------------------------------------------
"""
import pygame
from random import randint
from math import sin, cos, pi


def static_page(screen, text,color, pos):
    font = pygame.font.SysFont('Times New Roman', 40)
    title = font.render(text, True, color)
    screen.blit(title, pos)


def animation_title(screen):
    font = pygame.font.SysFont('楷体', 40)
    title = font.render('Welcome', True, (randint(0, 255), randint(0, 255), randint(0, 255)))
    screen.blit(title, (200, 100))


if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((1600, 900))
    screen.fill((255, 255, 255))

    pygame.display.flip()
    x = 0
    y = 0
    while True:
        """程序执行到这个位置,暂停一段时间后在执行后面的代码(线程阻塞)
        单位: 毫秒(1000ms = 1s)"""
        pygame.time.delay(17)
        # 只有事件发生后才会执行
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()

        # 在下面写每一帧要显示的内容
        # 动画前要将原来的内容清空
        x += 1
        y = int(200*sin(0.01*pi*x))+400
        y2 = int(-200*sin(0.01*pi*x))+400
        z = int(200*cos(0.01*pi*x))+400
        z2 = int(-200 * cos(0.01 * pi * x)) + 400
        # screen.fill((255, 255, 255))
        pygame.draw.circle(screen, (255, 0, 0), (x, y), 5, 0)
        static_page(screen, '200 * sin(pi * x / 100) + 400', (255, 0, 0),(50, 50))
        pygame.draw.circle(screen, (0, 255, 0), (x, y2), 5, 0)
        static_page(screen, '-200 * sin(pi * x / 100) + 400', (0, 255, 0), (50, 100))
        pygame.draw.circle(screen, (0, 0, 255), (x, z), 5, 0)
        static_page(screen, '200 * cos(pi * x / 100) + 400', (0, 0, 255), (600, 50))
        pygame.draw.circle(screen, (0, 0, 0), (x, z2), 5, 0)#(255, 127, 4)
        static_page(screen, '-200 * cos(pi * x / 100) + 400', (0, 0, 0), (600, 100))
        if x >= 1600:
            x = 0

        # 内容展示完后要更新到屏幕上
        pygame.display.update()

五、一些有趣的应用

   窗口的小球的来回碰撞效果实现

可由键盘控制移动方向的小球轨迹
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name:     05-ballgame
   Description :
   Author :       LPP
   date:          2018/7/30
-------------------------------------------------
   Change Activity:
                   2018/7/30:
-------------------------------------------------
"""
import pygame
from random import randint

def draw_ball(place, color, pos):
    """
    画一个球
    :param place:画图位置
    :param color: 颜色
    :param pos: 坐标位置
    """
    pygame.draw.circle(place, color, pos, 10)

UP = 273
DOWN =274
LEFT = 276
RIGHT = 275

rand_color = (randint(0, 255), randint(0, 255), randint(0, 255))

if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((1600, 900))
    screen.fill((255, 255, 255))

    pygame.display.flip()

    ball_x = 1600
    ball_y = 100
    x_speed = 0
    y_speed = 0
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()

            if event.type == pygame.KEYDOWN:
                if event.key == UP:
                    y_speed = -5
                    x_speed = 0
                elif event.key == DOWN:
                    y_speed = 5
                    x_speed = 0
                elif event.key == RIGHT:
                    y_speed = 0
                    x_speed = 5
                elif event.key == LEFT:
                    y_speed = 0
                    x_speed = -5
                elif event.key == 32:
                    x_speed = 0
                    y_speed = 0


        # screen.fill((255, 255, 255))

        ball_x += x_speed
        ball_y += y_speed
        draw_ball(screen, rand_color, (ball_x, ball_y))
        draw_ball(screen, (randint(0, 255), randint(0, 255), randint(0, 255)), (ball_x, ball_y))
        if ball_x + 10 >= 1600:
            ball_x = 1600-10
            x_speed *= -1
        if ball_x <= 0:
            ball_x = 0
            x_speed *= -1
        if ball_y <= 0:
            ball_y = 0
            y_speed *= -1
        if ball_y - 10 >= 900:
            ball_y = 900
            y_speed *= -1

        pygame.display.update()

相关文章

网友评论

      本文标题:day11 Pygame Ⅱ 事件处理2018-07-30

      本文链接:https://www.haomeiwen.com/subject/gqrqvftx.html