2.82M

Pygame Lesson 5 (1)

1.

Python. PyGame.
Keyboard events
12.5.3.4 control characters with the keyboard;

2.

Keyboard Control
https://b2a.kz/9Tp
Keyboard event
KEYDOWN
event.type
KEYDOWN
KEYUP
KEYUP
attributes
key, mod (например, shift, ctrl...), unicode
key, mod
key – a specific key that was pressed or pressed. Example:pygame.K_LEFT
mod – modifier keys (Shift, Ctrl, etc.) that were clamped at the time of pressing or pressing a normal
key. Example: pygame.KMOD_SHIFT
unicode - records the character of the pressed key (data type str)

3.

Object control using the keys: pressed every
time
for event in pygame.event.get():
if event.type == pygame.QUIT:
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN: # reacts to pressing buttons on the keyboard
if event.key == pygame.K_LEFT: # movement to the left
x -= 3
elif event.key == pygame.K_RIGHT: # movement to the right
x += 3
elif event.key == pygame.K_UP: # movement upward
y -= 3
elif event.key == pygame.K_DOWN: # movement downward
y += 3

4.

Object control using the keys: pressed only
once and can hold the button
pygame.key.get_pressed() – a method that gets the status of all keyboard buttons,
i.e. with this method we can check whether any key has been pressed.
To check whether the key has been pressed/released, use the following code:
if event.type == pygame.KEYDOWN:
if pygame.key.get_pressed():
#do smth
OR
if event.type == pygame.KEYUP:
if pygame.key.get_pressed():
#do smth

5.

Symbols of the keys (https://b2a.kz/QHj )

6.

Task 1
Write code which will print to the console the name of the key which
you pressed.

7.

Task 2
• Write program to emulate MOVING of blue
circle in game window.
• Use keys up, down, left, right for moving
#how the difference between
get_pressed() and without
using it.

8.

Task 3
Continue the task 2 program to extend abilities of
blue circle in game window.
1.
Use key + to make size of circle bigger
2.
Use keys – to make size smaller
3.
Use any key to randomly change color of the
circle

9.

Task 4
• write a program where the ball will
pass through an obstacle and it can
be controlled through the arrow
buttons, and through the letters
• A (move left)
• W (jump)
• D (move right)

10.

Task+
• Create a program of a simple
labyrinth
Example:

11.

Resources
• https://younglinux.info/pygame/key
• https://www.pygame.org/docs/ref/key.html
• Get_pressed: Pygame Keyboard Input Tutorial
English     Русский Rules