day_010 Python中的pygame_2

一、事件

  • 鼠标的事件:
    QUIT:关闭按键被点击事件
    MOUSEBUTTONDOWN:鼠标按键按下事件
    MOUSEBUTTONUP:鼠标按键弹起事件
    MOUSEMOTION:鼠标移动事件
  • 键盘的事件:
    KEYDOWN:键盘上的按键按下
    KEYUP:键盘上的按键弹起
import pygame


if __name__ == '__main__':
    # 初始化
    pygame.init()
    # 定义窗口大小
    screen = pygame.display.set_mode((800, 450))
    # 填充背景色
    screen.fill((255, 255, 255))
    # 设置窗口标题
    pygame.display.set_caption('小游戏_游戏事件')
    # 显示
    pygame.display.flip()

    while True:
        # 每次循环检测有没有事件发生
        for event in pygame.event.get():
            # 不同类型的事件type值不一样
            if event.type == pygame.QUIT:
                # 退出程序
                exit(0)

            # 鼠标按下事件
            if event.type == pygame.MOUSEBUTTONDOWN:
                # 打印鼠标按下时的位置
                print('鼠标被按下', event.pos)

            # 鼠标按键弹起
            if event.type == pygame.MOUSEBUTTONUP:
                # 打印鼠标弹起时的位置
                print('鼠标弹起', event.pos)

            # 鼠标移动事件
            # if event.type == pygame.MOUSEMOTION:
            #     print('鼠标移动')

            # 键盘相关事件
            # 按键按下
            # key属性,被按的按键对应的值的ascii码
            if event.type == pygame.KEYDOWN:
                 # 查看按下按键对应的ascii码
                print('按键按下', chr(event.key))

            # 按键弹起
            if event.type == pygame.KEYUP:
                print('按键弹起')

示例1:

import pygame
import random


# 产生随机的RGB色
def rand_color():
    return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)


# 画球
def draw_ball(local, pos):
    pygame.draw.circle(local, rand_color(), pos, random.randint(20, 50))
    # 只要屏幕上的内容有更新,都要调用下面这两个方法中的一个
    # pygame.display.flip()
    pygame.display.update()


# 写一个函数,换一个按键
def draw_button(local, btn_color, title_color):
    # 画个按键
    # 矩形框
    pygame.draw.rect(local, btn_color, (200, 150, 100, 50))
    # 文字
    font = pygame.font.SysFont('SimSun', 30)
    title = font.render('click me', True, title_color)
    screen.blit(title, (210, 165))
    pygame.display.update()


# 写一个函数,判断指定的点是否在指定的矩形范围中
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((800, 450))
    screen.fill((255, 255, 255))

    # 画个按键
    # 矩形框
    pygame.draw.rect(screen, (0, 255, 0), (200, 150, 100, 50))
    # 文字
    font = pygame.font.SysFont('SimSun', 30)
    title = font.render('click me', True, (255, 0, 0))
    screen.blit(title, (210, 165))

    pygame.display.flip()

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

            # 鼠标按下的事件
            if event.type == pygame.MOUSEBUTTONDOWN:
                # 判断鼠标是否在按键上
                if is_in_rect(event.pos, (200, 150, 100, 50)):
                    # 当鼠标按下按键时画一个其他颜色的按键
                    draw_button(screen, rand_color(), rand_color())

            # 当鼠标弹起时
            if event.type == pygame.MOUSEBUTTONUP:
                # 判断鼠标是否在按键上
                if is_in_rect(event.pos, (200, 150, 100, 50)):
                    # 鼠标弹起时,画一个原来样式的按键
                    draw_button(screen, (0, 255, 0), (255, 0, 0))
            
            # 鼠标移动时
            if event.type == pygame.MOUSEMOTION:
                screen.fill((255, 255, 255))
                # 鼠标每移动一次就在指定的位置画一个按键
                draw_button(screen, (0, 255, 0), (255, 0, 0))
                # 鼠标每移动一次就在鼠标的位置画一个随机颜色的球
                draw_ball(screen, event.pos)

mouse_event1.gif

示例2:鼠标拖拽图片移动

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((800, 450))
    screen.fill((255, 255, 255))
    pygame.display.set_caption('图片拖拽')

    image_x = 0
    image_y = 0
    image = pygame.image.load('./images/2.png')
    screen.blit(image, (image_x, image_y))
    # rect = (0, 0, 120, 56)

    pygame.display.flip()

    # 用来存储图片是否可以移动的状态
    is_move = False

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

            # 鼠标按下,让状态变为可以移动
            if event.type == pygame.MOUSEBUTTONDOWN:
                image_w, image_h = image.get_size()
                is_move = is_in_rect(event.pos, (image_x, image_y, image_w, image_h))

            # 鼠标弹起,状态变为不可移动
            if event.type == pygame.MOUSEBUTTONUP:
                # x, y = event.pos
                # image_w, image_h = image.get_size()
                # rect = (x - image_w/2, y - image_h/2, image_w, image_h)
                is_move = False

            if event.type == pygame.MOUSEMOTION:
                if is_move:
                    screen.fill((255, 255, 255))
                    x, y = event.pos
                    image_w, image_h = image.get_size()
                    image_x = x - (image_w/2)
                    image_y = y - (image_h/2)
                    screen.blit(image, (image_x, image_y))
                    pygame.display.update()
mouse_event2.gif

示例3: pygame实现动画功能

"""
动画原理:不断刷新界面上的内容(一帧一帧的画)
"""
import pygame
import random


def static_page(screen):
    """
    页面上的静态内容
    :param screen: 画布
    :return: None
    """
    # 静态文字
    font = pygame.font.SysFont('Times', 30)
    title = font.render('hello pygame', True, (0, 150, 255))
    screen.blit(title, (200, 200))


def animation_title(screen):
    font = pygame.font.SysFont('Times', 30)
    title = font.render('welcome', True, (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
    screen.blit(title, (400, 300))


if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((800, 450))
    screen.fill((255, 255, 255))
    pygame.display.set_caption('pygame动画')

    static_page(screen)

    pygame.display.flip()

    while True:
        # for里面的代码只有事件发生后才会执行
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit(0)

        # 在下面写每一帧要显示的内容
        # delay,线程在这里阻塞指定的时间
        pygame.time.delay(100)
        # 动画前要将原来的内容全部清空
        screen.fill((255, 255, 255))
        static_page(screen)
        animation_title(screen)
        # 内容展示完成后,要更新到屏幕上
        pygame.display.update()

animation.gif

示例4:在限定范围内移动且可以控制方向的小球

import pygame


def draw_ball(local, color, pos):
    """
    画球
    :param local:
    :return:
    """
    pygame.draw.circle(local, color, pos, 20)


# 方向对应的key值
up = 273
down = 274
left = 276
right = 275



if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((800, 450))
    screen.fill((255, 255, 255))
    pygame.display.set_caption('ball game')

    pygame.display.flip()

    # 保存初始坐标
    ball_x = 100
    ball_y = 100
    x_speed = 10
    y_speed = 0

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

            if event.type == pygame.KEYDOWN:
                if event.key == up:
                    y_speed = -10
                    x_speed = 0
                elif event.key == down:
                    y_speed = 10
                    x_speed = 0
                elif event.key == right:
                    x_speed = 10
                    y_speed = 0
                elif event.key == left:
                    x_speed = -10
                    y_speed = 0


        # 刷新屏幕
        # 设置初始方向
        ball_x += x_speed
        ball_y += y_speed
        # 边界检测
        if ball_x + 20 >= 800:
            ball_x = 800 - 20
            x_speed *= -1

        if ball_x <= 20:
            ball_x = 20
            x_speed *= -1

        if ball_y + 20 >= 450:
            ball_y = 450 - 20
            y_speed *= -1

        if ball_y <= 20:
            ball_y = 20
            y_speed *= -1

        screen.fill((255, 255, 255))
        pygame.time.delay(17)
        draw_ball(screen, (255, 255, 0), (ball_x, ball_y))
        pygame.display.update()
ball_game1.gif

示例5:多个移动的小球且鼠标每点击一次产生一个移动的小球

import pygame
import random


# random_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((800, 450))
    screen.fill((255, 255, 255))
    pygame.display.set_caption('bll game 2')

    pygame.display.flip()

    # all_balls中保存多个球
    # 每个球要保存:半径、圆心坐标、颜色、x速度、y速度
    all_balls = [
        {
            'r': random.randint(10,30),
            'pos':(100, 100),
            'color': (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)),
            'x_speed': random.randint(-3, 3),
            'y_speed': random.randint(-3, 3)
         },
        {
            'r': random.randint(10, 30),
            'pos': (200, 200),
            'color': (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)),
            'x_speed': random.randint(-3, 3),
            'y_speed': random.randint(-3, 3)
        },
        {
            'r': random.randint(10, 30),
            'pos': (300, 300),
            'color': (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)),
            'x_speed': random.randint(-3, 3),
            'y_speed': random.randint(-3, 3)
        }
    ]

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

            if event.type == pygame.MOUSEBUTTONDOWN:
                ball_new = {
                    'r': random.randint(10, 30),
                    'pos': event.pos,
                    'color': (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)),
                    'x_speed': random.randint(-3, 3),
                    'y_speed': random.randint(-3, 3)
                }
                all_balls.append(ball_new)

        # 刷新界面
        screen.fill((255, 255, 255))
        pygame.time.delay(10)

        for ball in all_balls:
            x, y = ball['pos']
            x_speed = ball['x_speed']
            y_speed = ball['y_speed']
            x += x_speed
            y += y_speed
            # 边界检测
            if x + ball['r'] >= 800:
                ball['x_speed'] *= -1

            if x <= ball['r']:
                ball['x_speed'] *= -1

            if y + ball['r'] >= 450:
                ball['y_speed'] *= -1

            if y <= ball['r']:
                ball['y_speed'] *= -1
            pygame.draw.circle(screen, ball['color'], (x,y), ball['r'])
            # 更新球对应的坐标
            ball['pos'] = x, y



        pygame.display.update()
ball_game2.gif

你可能感兴趣的:(day_010 Python中的pygame_2)