July 30-day13-Python中Pygame

2018-07-30  本文已影响0人  慢节拍_2709

触碰事件

有鼠标、键盘等等

import pygame

if __name__ == '__main__':
    pygame.init()
    desktop = pygame.display.set_mode((800,600))

    pygame.display.set_caption('游戏事件')
    desktop.fill((255,255,255))


    pygame.display.flip()
    """
    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))
结果:
鼠标移动 (780, 5)
鼠标移动 (780, 6)
鼠标按下 (780, 6)
鼠标弹起 (780, 6)
鼠标移动 (779, 6)
鼠标移动 (778, 6)
键盘按钮按下 Ĕ
键盘按钮弹起 Ĕ
键盘按钮按下 Ē
键盘按钮弹起 Ē
键盘按钮按下 ē
键盘按钮弹起 ē
键盘按钮按下 đ
键盘按钮弹起 đ

对鼠标事件的应用

import pygame
from random import randint

def random_color():
    # 产生随机颜色
    return randint(0,255),randint(0,255),randint(0,255)
# 画个圆
def draw_ball(screen,pos):
    pygame.draw.circle(screen, random_color(), pos, randint(10, 20))

    # 只要屏幕上的内容有更新, 都需要调用下面这两个方法
    # pygame.display.flip()
    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

def draw_button(screen,bth_color, title_color):
    # 画个按钮
    # 矩形框
    pygame.draw.rect(screen, bth_color, (300, 300, 100, 60))
    # 矩形框中文字
    font = pygame.font.SysFont('Times', 30)
    title = font.render('B', True, title_color)
    desktop.blit(title, (330, 330))

if __name__ == '__main__':
    pygame.init()
    desktop = pygame.display.set_mode((800,600))
    pygame.display.set_caption('鼠标事件')
    desktop.fill((255,255,255))

    # 画个按钮
    draw_button(desktop,(0,255,0),(255,0,0))

    pygame.display.flip()

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

        if event.type == pygame.MOUSEBUTTONDOWN:
            if is_in_rect(event.pos,(300,300,100,60)):
                draw_button(desktop,(0,100,0),(100,0,0))
                pygame.display.update()
                print('点击鼠标')
        if event.type == pygame.MOUSEBUTTONUP:
            if is_in_rect(event.pos,(300,300,100,60)):
                draw_button(desktop,(0, 255, 0),(255, 0, 0))
                pygame.display.update()

        if event.type == pygame.MOUSEMOTION:
            desktop.fill((255,255,255))
            draw_button(desktop, (0, 255, 0), (255, 0, 0))
            draw_ball(desktop,event.pos)
结果:
点击鼠标
图片 1

鼠标点击事件的应用(对鼠标的拖拽)

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()
    desktop = pygame.display.set_mode((800,600))
    pygame.display.set_caption('图片拖拽')
    desktop.fill((255,255,255))

    # 获取一个图片的尺寸
    # image_size = image.get_size()
    # print(image_size)
    image = pygame.image.load('./20018.png')
    image_x = 300
    image_y = 300
    is_move = False

    # 将图片渲染
    desktop.blit(image, (image_x,image_y))

    # 弄到屏幕上
    pygame.display.flip()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()

            # 鼠标点击效果
            if event.type == pygame.MOUSEBUTTONDOWN:
                image_w, image_h = image.get_size()
                if is_in_rect(event.pos, (image_x, image_y, image_w,image_h)):
                    is_move = True

            # 鼠标弹出效果
            if event.type == pygame.MOUSEBUTTONUP:
                is_move = False

            # 鼠标移动效果
            if event.type ==pygame.MOUSEMOTION:
                if is_move:
                    desktop.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
                    desktop.blit(image, (image_x,image_y))
                    pygame.display.update()
图片2

字体动画的效果

import pygame
from random import randint
"""
动画原理:不断的刷新界面上的内容(一帧一帧的画)
"""
def static_page(screen):
    # 静态文字
    font = pygame.font.SysFont('Times', 40)
    title = font.render('Hello,Python',True,(255,0,0))
    screen.blit(title, (200,200))

def animation_title(screen):
    # 产生随机颜色的字体
    font = pygame.font.SysFont('Times', 40)
    title = font.render('Python', True, random_color())
    screen.blit(title, (300, 300))

def random_color():
    # 产生随机颜色
    return randint(0,255),randint(0,255),randint(0,255)

if __name__ == '__main__':
    pygame.init()
    desktop = pygame.display.set_mode((800, 600))
    pygame.display.set_caption('动画效果')
    desktop.fill((255, 255, 255))

    static_page(desktop)

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

        # 程序执行到这个位子,CPU休息一段时间再执行后面的代码(线程在这儿阻塞指定的时间)
        # 单位:毫秒(1000ms = 1s) 由于颜色变化太快看不清,所以delay
        pygame.time.delay(60)
        # 在下面去写每一帧显示的内容
        desktop.fill((255,255,255))
        static_page(desktop)
        animation_title(desktop)
        pygame.display.update()
图片3

键盘事件的应用

import pygame

def draw_ball(place,color,pos):
    #画球
    pygame.draw.circle(place,color,pos,40)

if __name__ == '__main__':
    pygame.init()
    desktop = pygame.display.set_mode((800,600))
    pygame.display.set_caption('球球游戏')
    desktop.fill((255,255,255))

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

    # 方向对应的key值
    Up = 273
    Down = 274
    Left = 276
    Right = 275

    pygame.display.flip()
    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 == Left:
                    y_speed = 0
                    x_speed = -5
                elif event.key == Right:
                    y_speed = 0
                    x_speed = +5

        pygame.time.delay(10)
        # 刷新屏幕
        desktop.fill((255,255,255))

        ball_x += x_speed
        ball_y += y_speed
        if ball_x+40 >= 800:
            ball_x = 800-40
            x_speed *= -1
            print('game over!')
            exit()

        if ball_x-40 <= 0:
            ball_x = 0+40
            x_speed += 5
        draw_ball(desktop,(255,0,0),(ball_x,ball_y))
        pygame.display.update()
结果:
game over!
图片4

多个球一起动

import pygame
import random

def ran_color():
    return random.randint(0,255),random.randint(0,255),random.randint(0,255)

if __name__ == '__main__':
    pygame.init()
    desktop = pygame.display.set_mode((800, 600))
    pygame.display.set_caption('多个球一起动')
    desktop.fill((255, 255, 255))

    """
    all_balls中保存多个球
    每个球要保存:半径、圆心坐标、颜色、x速度、y速度
    """
    all_balls = []
    pygame.display.flip()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()

            if event.type == pygame.MOUSEBUTTONDOWN:
                ball = {
                        'r' : random.randint(10,25),
                        'pos': event.pos,
                        'color': ran_color(),
                        'x_speed': random.randint(-3, 3),
                        'y_speed': random.randint(-3, 3)
                }
                all_balls.append(ball)
                # is_move =True
        desktop.fill((255,255,255))
        for ball_dict in all_balls:
            # if  is_move:
            x,y = ball_dict['pos']
            x_speed = ball_dict['x_speed']
            y_speed = ball_dict['y_speed']
            x += x_speed
            y += y_speed
            pygame.draw.circle(desktop,ball_dict['color'],(x,y),ball_dict['r'])
            # 更新球对应的坐标
            ball_dict['pos'] = x,y

        pygame.time.delay(60)
        pygame.display.update()
图片5
上一篇下一篇

猜你喜欢

热点阅读