Here’s a simple key handle in Pygame wheres you move a circle using keyboard.
import pygame
from pygame.locals import *
def main():
x,y = (100,100)
pygame.init()
screen = pygame.display.set_mode((400, 400))
while 1:
pygame.time.delay(1000/60)
# exit handle
for event in pygame.event.get():
if event.type == QUIT:
return
elif event.type == KEYDOWN and event.key == K_ESCAPE:
return
# keys handle
key=pygame.key.get_pressed()
if key[K_LEFT]:
x-=1
if key[K_RIGHT]:
x+=1
if key[K_UP]:
y-=1
if key[K_DOWN]:
y+=1
# fill background and draw a white circle
screen.fill((255,255,255))
pygame.draw.circle(screen, (0,0,0), [x,y], 30)
pygame.display.flip()
if __name__ == '__main__': main()
Here’s a video of it working:
Function pygame.key.get_pressed Returns a sequence of boolean values representing the state of every key on the keyboard. It’s very useful because usually on others game platforms I have to create it by myself.
This approach allow me to handle more than one key at time. For example, left and up keys can be pressed and each one is handled separately creating a diagonal movement.
Be First to Comment