-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPygame_keyboard_test.py
More file actions
74 lines (65 loc) · 2.43 KB
/
Pygame_keyboard_test.py
File metadata and controls
74 lines (65 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# 1 - Import library
import pygame
from pygame.locals import *
# 2 - Initialize the game
pygame.init()
pygame.font.init() # you have to call this at the start,
# if you want to use this module.
width, height = 64*10, 64*8
screen=pygame.display.set_mode((width, height))
player_x = 200
player_y = 200
keys = [False, False, False, False]
# 3 - Load images
player = pygame.image.load("hero.png")
# 4 - keep looping through
while 1:
# 5 - clear the screen before drawing it again
screen.fill((255,255,255))
# 6 - draw the screen elements
screen.blit(player, (player_x, player_y))
# 7 - update the screen
pygame.display.flip()
# 8 - loop through the events
for event in pygame.event.get():
# check if the event is the X button
if event.type == pygame.QUIT:
# if it is quit the game
pygame.quit()
exit(0)
if event.type == pygame.KEYDOWN:
if event.key==K_UP:
keys[0]=True
elif event.key==K_LEFT:
keys[1]=True
elif event.key==K_DOWN:
keys[2]=True
elif event.key==K_RIGHT:
keys[3]=True
if event.type == pygame.KEYUP:
if event.key==pygame.K_UP:
keys[0]=False
elif event.key==pygame.K_LEFT:
keys[1]=False
elif event.key==pygame.K_DOWN:
keys[2]=False
elif event.key==pygame.K_RIGHT:
keys[3]=False
# Update the y position
# If the up button is pressed
if keys [0]:
if player_y> 0: # If the coordinate is greater than 0 (not outside the playing field)
player_y -= 15 # Change the y position by 15 pixels. The player moves upwards
# If the down key is pressed
elif keys [2]:
if player_y <height-64: # If the coordinate is less than the height of the playing field
player_y += 15 # Change the y position by 15 pixels. The player goes down
# Update x-position
# If the left key is pressed
if keys [1]:
if player_x> 0: # If the player is inside the playing field
player_x -= 15 # Decrease x position. The player goes left
# If the right key is pressed
elif keys [3]:
if player_x <width-64: # If the player is inside the playing field
player_x += 15 # Increase x position. The player goes right