Difference between revisions of "Keyboard input"
Line 8: | Line 8: | ||
elif(user_input[pygame.K_DOWN]): | elif(user_input[pygame.K_DOWN]): | ||
Y=Y+1 | Y=Y+1 | ||
− | + | if(user_input[pygame.K_LEFT]): | |
X=X-1 | X=X-1 | ||
elif(user_input[pygame.K_RIGHT]): | elif(user_input[pygame.K_RIGHT]): | ||
Line 28: | Line 28: | ||
elif event.key == pygame.K_RIGHT: | elif event.key == pygame.K_RIGHT: | ||
X=X+1 | X=X+1 | ||
− | + | if event.key == pygame.K_UP: | |
Y=Y-1 | Y=Y-1 | ||
elif event.key == pygame.K_DOWN: | elif event.key == pygame.K_DOWN: | ||
Y=Y+1 | Y=Y+1 | ||
</syntaxhighlight> | </syntaxhighlight> |
Revision as of 12:11, 5 July 2018
Within the game loop of your code, we can firstly get the status of the keyboard and store it in a variable called user_input. We can then check this for certain keys:
user_input = pygame.key.get_pressed()
if(user_input[pygame.K_UP]):
Y=Y-1
elif(user_input[pygame.K_DOWN]):
Y=Y+1
if(user_input[pygame.K_LEFT]):
X=X-1
elif(user_input[pygame.K_RIGHT]):
X=X+1
If these variables are used to draw something to the screen, then the object will move around the screen.
The alternative way of doing this is within the pygame.events:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit(); #sys.exit() if sys is imported
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
X+X-1
elif event.key == pygame.K_RIGHT:
X=X+1
if event.key == pygame.K_UP:
Y=Y-1
elif event.key == pygame.K_DOWN:
Y=Y+1