- Pygame 教程
- Pygame - 主页
- Pygame - 概述
- Pygame - 你好世界
- Pygame - 显示模式
- Pygame - 本地模块
- Pygame - 颜色对象
- Pygame - 事件对象
- Pygame - 键盘事件
- Pygame - 鼠标事件
- Pygame - 绘制形状
- Pygame - 加载图像
- Pygame - 在窗口中显示文本
- Pygame - 移动图像
- Pygame - 使用数字键盘移动
- Pygame - 用鼠标移动
- Pygame - 移动矩形对象
- Pygame - 使用文本作为按钮
- Pygame - 转换图像
- Pygame - 声音对象
- Pygame - 混合器通道
- Pygame - 播放音乐
- Pygame - 玩电影
- Pygame - 使用相机模块
- Pygame - 加载光标
- Pygame - 访问 CDROM
- Pygame - 精灵模块
- Pygame - PyOpenGL
- Pygame - 错误和异常
- Pygame 有用资源
- Pygame - 快速指南
- Pygame - 有用的资源
- Pygame - 讨论
Pygame - 使用数字键盘移动
如果我们想在游戏窗口上实现对象的对角线移动,我们需要使用数字键盘按键。4、6、8、2 键对应左、右、上、下箭头,而数字键 7、9、3、1 可用于左上、右上、右下、下移动对象-左对角线运动。这些键由 Pygame 使用以下值标识 -
K_KP1 keypad 1 K_KP2 keypad 2 K_KP3 keypad 3 K_KP4 keypad 4 K_KP5 keypad 5 K_KP6 keypad 6 K_KP7 keypad 7 K_KP8 keypad 8 K_KP9 keypad 9
例子
对于左、右、上、下箭头按下,x 和 y 坐标会像以前一样递增/递减。对于对角线移动,两个坐标都会根据方向发生变化。例如,对于 K_KP7 按键,x 和 y 均减 5,对于 K_KP9,x 递增,y 递减。
image_filename = 'pygame.png'
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((400,300))
pygame.display.set_caption("Moving with arrows")
img = pygame.image.load(image_filename)
x = 0
y= 150
while True:
screen.fill((255,255,255))
screen.blit(img, (x, y))
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == KEYDOWN:
if event.key == K_KP6:
x= x+5
if event.key == K_KP4:
x=x-5
if event.key == K_KP8:
y=y-5
if event.key == K_KP2:
y=y+5
if event.key == K_KP7:
x=x-5
y=y-5
if event.key == K_KP9:
x=x+5
y=y-5
if event.key == K_KP3:
x=x+5
y=y+5
if event.key == K_KP1:
x=x-5
y=y+5
pygame.display.update()