python pygame事件与事件处理

本期是接上期python pygame库的略学内容最后一个步骤,游戏与玩家交互的内容。

一、什么是事件

游戏需要与玩家交互,因此它必须能够接收玩家的操作,并根据玩家的不同操作做出有针对性的响应。程序开发中将玩家会对游戏进行的操作称为事件(Event),根据输入媒介的不同,游戏中的事件分为键盘事件、鼠标事件和手柄事件等。

pygame.locals中常见事件的产生及参数:

事件产生途径参数解释
KEYDOWN键盘上的按键被按下unicode记录安静Unicode值
key按下或放开的键的键值
mod包含组合键信息
KEYUP键盘上的键被放开key
mod
MOUSEMOTION鼠标移动pos鼠标指针操作的位置,包含(x,y)
rel当前位置与上次鼠标事件时鼠标指针位置间的距离
buttons含有3个数字的元组,元组中数字的取值为(0,1,3),依次代表为左键、滚轮和右键
MOUSEUTTONDOWN鼠标键按下pos
button整型数值,1表示单击鼠标左键,2表示单击滚轮,3表示单击右键,4表示向上滑动滚轮,5表示向下滑动滚轮
MOUSEBUTTONUP鼠标键放开pos
button

代码演示:

# 导入模块
import pygame,time
from pygame.locals import *

# 定义窗口高度和宽度、颜色
WIN_WIDTH = 658
WIN_HEIGHT = 243
# 设置颜色变量
BG_COLOR = (125,125,0)
MS_COLOR=(95,200,255)
MSGBG_COLOR=(23,78,20)


FPS=60
def main():
    # 初始化模块
    pygame.init()
    # 创建窗体,即创建Surface
    WINSET=pygame.display.set_mode((WIN_WIDTH,WIN_HEIGHT))
    # 为窗口填充背景色
    WINSET.fill(BG_COLOR)
    # 设置窗口标题
    pygame.display.set_caption('小游戏')

    # 加载图片
    # image=pygame.image.load('D:/Software/pycharm/网页请求/小游戏/image/wallhaven-j5mj3w_1920x1080.png')
    # 绘制图片
    # WINSET.blit(image,(0,0))
    # 创建字体对象
    BASICFONT=pygame.font.Font("D:/Software/字体/思源黑体/字体文件/SourceHanSansCN-Bold.otf",25)
    # 渲染字体
    msg_surf=BASICFONT.render('初始化…',True,MS_COLOR,MSGBG_COLOR)
    # 绘制渲染到游戏窗口
    WINSET.blit(msg_surf,(0,0))
    # 制作背景副本
    base_surf=WINSET.copy()
    # 渲染字体
    auto_surf=BASICFONT.render('自动',True,MS_COLOR,MSGBG_COLOR)
    # 获取矩形属性
    auto_rect=auto_surf.get_rect()
    # 重设横坐标
    auto_rect.x=WIN_WIDTH-auto_rect.width-10
    # 重设纵坐标
    auto_rect.y=WIN_HEIGHT-auto_rect.height-10
    # 绘制字体
    WINSET.blit(auto_surf,auto_rect)
    # 设置游戏时间钟,创建Colock对象
    FPSCOLOCK = pygame.time.Clock()
    # 在背景的不同位置绘制方块,制造移动效果
    for i in range(0,WIN_HEIGHT,2):
        FPSCOLOCK.tick(FPS)
        # 绘制
        WINSET.blit(auto_surf,auto_rect)
        pygame.display.update()
        auto_rect.x-=10
        if i+2 <WIN_HEIGHT:
            WINSET.blit(base_surf,(0,0))
    # 刷新窗口
    pygame.display.update()
    # 睡眠十秒
    time.sleep(10)
    # 利用无线循环
    while True:
        # 控制帧率
        FPSCOLOCK.tick(FPS)
        for event in pygame.event.get():
            if event.type==MOUSEBUTTONUP:
                if auto_rect.collidepoint(event.pos):
                    print("单击了按钮")
                else:
                    print("单击了空白区域")
            elif event.type == KEYUP:
                if event.key in (K_LEFT,K_a):
                    print('向右键')
                elif event.key in (K_RIGHT,K_d):
                    print('向左键')
                elif event.key in (K_UP,K_w):
                    print('向上键')
                elif event.key in (K_DOWN,K_s):
                    print('向下键')
                elif event.key == K_ESCAPE:
                    print('退出游戏')
                    pygame.quit()


    # 卸载所有模块
    pygame.quit()

if __name__ =='__main__':
    main()

二、接苹果小游戏:

import random
from sys import exit
import pygame
from pygame.locals import *

# 屏幕宽度和高度
screen_width = 450
screen_height = 560

# 模块初始化
pygame.init()
# 绘制窗口
screen = pygame.display.set_mode((screen_width, screen_height), 0, 32)
# 游戏标题
pygame.display.set_caption("小人接苹果")
# 分数字体,字号
run_time_font = pygame.font.SysFont('D:/Software/字体/思源黑体/字体文件/SourceHanSansCN-Bold.otf', 48)

def game_start():
    # 加载图片
    peasant = pygame.image.load('peasant.png')
    apples = pygame.image.load('apples.png')
    game_background = pygame.image.load('background.png')
    # 苹果下落的速度
    speed = 1
    # 分数
    score = 0
    # 农民的位置信息
    peasant_x = 200
    peasant_y = 470
    # 设置移动速度
    peasant_x_speed = 1
    peasant_move = {K_LEFT: 0, K_RIGHT: 0}
    # 苹果坐标列表
    pos_list = []
    # 绘制初始化苹果
    for i in range(7):
        x = random.randint(0, 390)
        y = random.randint(0, 560)
        pos_list.append([x, y])
    # 帧率控制Clock对象
    clock = pygame.time.Clock()
    while True:
        screen.blit(game_background, (0, 0))
        # 接收信息处理
        for event in pygame.event.get():
            if event.type == QUIT:
                exit()
            if event.type == KEYDOWN:
                if event.key in peasant_move:
                    peasant_move[event.key] = 1
            elif event.type == KEYUP:
                if event.key in peasant_move:
                    peasant_move[event.key] = 0
            # 距上次调用clock对象时间
            second_time_passed = clock.tick(60)
            # 定位农民移动后坐标
            peasant_x -= peasant_move[K_LEFT] * \
                         peasant_x_speed * second_time_passed
            peasant_x += peasant_move[K_RIGHT] * \
                         peasant_x_speed * second_time_passed
            # 判断农民边界条件
            if peasant_x > 450 - peasant.get_width():
                peasant_x = 450 - peasant.get_width()
            elif peasant_x < 0:
                peasant_x = 0

            screen.blit(peasant, (peasant_x, peasant_y))
            # 坐标循环,从y轴的上限往下限方向飘落
            for y in pos_list:
                y[1] = y[1] + speed
                # 打印苹果
                screen.blit(apples, (y[0], y[1]))
                if y[1] >= 560:
                    y[1] = -apples.get_height()
                # 碰撞检测
                if peasant_x < y[0] < peasant_x + peasant.get_width() and peasant_y - apples.get_height() < y[
                    1] < peasant_y:
                    score += 10
                    pos_list.remove([y[0], y[1]])
                    x, y = random.randint(0, 390), random.randint(0, 560)
                    if len(pos_list) <= 6:
                        pos_list.append([x, -y])
            screen_score = run_time_font.render(
                '分数:' + str(score), True, (255, 0, 0)
            )
            screen.blit(screen_score, (0, 0))
            # 刷新显示
            pygame.display.update()


if __name__ == '__main__':
    while True:
        game_start()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笔落难起

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值