-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeyboard.py
115 lines (91 loc) · 2.55 KB
/
keyboard.py
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import pygame, sys
import pygame.locals as GAME_GLOBALS
import pygame.event as GAME_EVENTS
# Pygame Variables
pygame.init()
clock = pygame.time.Clock()
windowWidth = 800
windowHeight = 800
surface = pygame.display.set_mode((windowWidth, windowHeight))
pygame.display.set_caption('Pygame Keyboard!')
# Square Variables
playerSize = 20
playerX = (windowWidth / 2) - (playerSize / 2)
playerY = windowHeight - playerSize
playerVX = 1.0
playerVY = 0.0
jumpHeight = 75.0
moveSpeed = 8.0
maxSpeed = 15.0
gravity = 0.2
# Keyboard Variables
leftDown = False
rightDown = False
haveJumped = False
def move():
global playerX, playerY, playerVX, playerVY, haveJumped, gravity
# Move left
if leftDown:
#If we're already moving to the right, reset the moving speed and invert the direction
if playerVX > 0.0:
playerVX = moveSpeed
playerVX = -playerVX
# Make sure our square doesn't leave our window to the left
if playerX > 0:
playerX += playerVX
# Move right
if rightDown:
# If we're already moving to the left reset the moving speed again
if playerVX < 0.0:
playerVX = moveSpeed
# Make sure our square doesn't leave our window to the right
if playerX + playerSize < windowWidth:
playerX += playerVX
if playerVY > 1.0:
playerVY = playerVY * 0.9
else :
playerVY = 0.0
haveJumped = False
# Is our square in the air? Better add some gravity to bring it back down!
if playerY < windowHeight - playerSize:
playerY += gravity
gravity = gravity * 1.1
else :
playerY = windowHeight - playerSize
gravity = 1.0
playerY -= playerVY
if playerVX > 0.0 and playerVX < maxSpeed or playerVX < 0.0 and playerVX > -maxSpeed:
if haveJumped == False:
playerVX = playerVX * 1.1
# How to quit our program
def quitGame():
pygame.quit()
sys.exit()
while True:
surface.fill((0,0,0))
pygame.draw.rect(surface, (255,0,0), (playerX, playerY, playerSize, playerSize))
# Get a list of all events that happened since the last redraw
for event in GAME_EVENTS.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
leftDown = True
if event.key == pygame.K_RIGHT:
rightDown = True
if event.key == pygame.K_UP:
if not haveJumped:
haveJumped = True
playerVY += jumpHeight
if event.key == pygame.K_ESCAPE:
quitGame()
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
leftDown = False
playerVX = moveSpeed
if event.key == pygame.K_RIGHT:
rightDown = False
playerVX = moveSpeed
if event.type == GAME_GLOBALS.QUIT:
quitGame()
move()
clock.tick(60)
pygame.display.update()