Module 6 - Section 0 - Repeat!
Site: | ΕΛ/ΛΑΚ Moodle |
Course: | Python Lab |
Book: | Module 6 - Section 0 - Repeat! |
Printed by: | Guest user |
Date: | Sunday, 24 November 2024, 9:16 PM |
Description
6.0.1 - Animate
If we want to animate an object that we are going to draw inside the main loop using the pygame template we should:
- First : create an initialization block of commands outside the Main program loop where we define the starting position (x , y) of the object and the starting speed in each axis:
rect_x = 50 # X starting position of rectangle
rect_y = 50 # Y starting position of rectangle
speed_x = 5 # X speed of rectangle
speed_y = 5 # Y speed of rectangle - Second : inside the main loop change the position according to the speed:
rect_x += speed_x
rect_y += speed_y - Third : Change the drawing command using the defined variables:
pygame.draw.rect(screen, WHITE, [rect_x, rect_y, 50,50])
6.0.2 - Bounce
To bounce the object at the edges of the screen we change the direction of the object's speed when it reaches the edges.
if rect_x >= 650 or rect_x <= 0:
speed_x *= -1
if rect_y >= 450 or rect_y <= 0:
speed_y *= -1
If the object is larger or smaller or if it is different (circle) we have to change the borders in the previous commands accordingly.
6.0.3 - Using the mouse
To get the position of the mouse inside a graphics screen created with pygame we use the command,
pos = pygame.mouse.get_pos()
inside the main loop, so depending of the clock.tick() command the position is read constantly.
The variable pos is a tuple of two numbers that we can use to move a shape using the tuples numbers as coordinates. The commands are:
x = pos[0] # assign the x position of the mouse to variable x
y = pos[1] # assign the y position of the mouse to variable y
and to draw a shape at the position x,y :
pygame.draw.circle(screen, RED, [ x, y], 30, 0)