- Pygame 教程
- Pygame - 主页
- Pygame - 概览
- Pygame - Hello World
- Pygame - 显示模式
- Pygame - Locals 模块
- Pygame - 颜色对象
- Pygame - 事件对象
- Pygame - 键盘事件
- Pygame - 鼠标事件
- Pygame - 绘制形状
- Pygame - 加载图片
- Pygame - 在窗口中显示文本
- Pygame - 移动图片
- Pygame - 使用数字小键盘键移动
- Pygame - 使用鼠标移动
- Pygame - 移动矩形对象
- Pygame - 使用文本作为按钮
- Pygame - 转换图片
- Pygame - 声音对象
- Pygame - 混音通道
- Pygame - 播放音乐
- Pygame - 播放电影
- Pygame - 使用相机模块
- Pygame - 加载光标
- Pygame - 访问光盘
- Pygame - Sprite 模块
- 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()
广告