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()
广告
© . All rights reserved.