PyGame - Moving with Numeric Pad Keys
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 - Using keys to Move Image
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.
main.py
import pygame
from pygame.locals import *
from sys import exit
image_filename = 'pygame.png'
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()
Output
The Pygame logo image can be moved in multiple directions using keys.
Advertisements