前面的知识和案例中我们也用了一下键盘,那时候是用了pygame.event.get()获取所有的事件,当event.type == KEYDOWN的时候,再判断event.key的种类。今天我们再介绍一个方法,pygame.key.get_pressed()来获得所有按下的键值,它会返回一个元组。这个元组的索引就是键值,对应的就是是否按下,比如说:

当我们按下右键时,得到的 get_pressed 元组列表如下(注意有一个1):

(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

pygame.K_RIGHT 是一个常量, 值是275.

key_pressed[pygame.K_RIGHT] 实质上就是key_pressed[275]==1代表右键被按下

当然key模块下还有很多函数:

key.get_focused —— 返回当前的pygame窗口是否激活

key.get_pressed —— 刚刚解释过了

key.get_mods —— 按下的组合键(Alt, Ctrl, Shift)

key.set_mods —— 你也可以模拟按下组合键的效果(KMOD_ALT, KMOD_CTRL, KMOD_SHIFT)

key.set_repeat —— 无参数调用设置pygame不产生重复按键事件,二参数(delay, interval)调用设置重复事件发生的时间

key.name —— 接受键值返回键名

使用键盘控制方向

根据坐标变化规律,通过这张图帮助理解键盘如何控制方向:

用python和pygame游戏编程入门-键盘设备

我们使用key.get_pressed()修改之前的程序:


background_image_filename = './img/Underwater.png'
sprite_image_filename = './img/fish-b.png'

import pygame
from pygame.locals import *
from sys import exit
from Vec2d import *
 
pygame.init()
 
screen = pygame.display.set_mode((640, 480), 0, 32)
 
background = pygame.image.load(background_image_filename).convert()
sprite = pygame.image.load(sprite_image_filename).convert_alpha()
 
clock = pygame.time.Clock()
sprite_pos = Vec2d(200, 150)
sprite_speed = 300.
 
while True:
 
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
 
    pressed_keys = pygame.key.get_pressed()

    key_direction = Vec2d(0, 0)
    if pressed_keys[K_LEFT]:
        print(pressed_keys)
        key_direction.x = -1
    elif pressed_keys[K_RIGHT]:
        key_direction.x = +1
    if pressed_keys[K_UP]:
        key_direction.y = -1
    elif pressed_keys[K_DOWN]:
        key_direction.y = +1

    key_direction.normalized()

    screen.blit(background, (0,0))
    screen.blit(sprite, sprite_pos)

    time_passed = clock.tick(30)
    time_passed_seconds = time_passed / 1000.0

    sprite_pos+= key_direction * sprite_speed * time_passed_seconds

    pygame.display.update()


如果你不知道Vec2d是什么,传送门-->pygame游戏编程入门-向量类的使用


本站内容未经许可,禁止任何网站及个人进行转载。