Pygame 简明教程

Pygame - Moving with Numeric Pad Keys

如果我们要实现对象在游戏窗口上的对角线移动,我们需要使用数字键盘键。当键 4、6、8 和 2 分别对应于左、右、上和下箭头时,数字键 7、9、3 和 1 可以用来将对象移动到左上、右上、右下和左下的对角线运动中。这些键由 Pygame 根据以下值标识 −

If we want to effect diagonal movement of an object on game window, we need to use numeric key pad keys. While keys 4,6,8 and 2 correspond to left, right, up and down arrows, num keys 7, 9, 3 and 1 can be used to move the object in up-left, up-right, down-right and down-left diagonal movements. These keys are identified by Pygame with following values −

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

Example

对于左、右、上和下箭头按下,x 和 y 坐标像之前一样进行增量/减量。对于对角线移动,两个坐标根据方向进行更改。例如,对于 K_KP7 按键,x 和 y 都递减 5,对于 K_KP9,x 增量,y 递减。

For left, right, up and down arrow press, x and y coordinates are incremented/decremented as before. For diagonal movement, both coordinates are changed as per direction. For instance, for K_KP7 key-press, both x and y are decremented by 5, for K_KP9 x is incremented and y is decremented.

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()