Module 5 - Section 1 - Graphics
5.1.1 - Move On
Starting from the pygame basic template the screen that we have created is updated 60 times per second with the command clock.tick(60).
Change the color of the screen to BLACK changing the line 44 to :
screen.fill(BLACK)
To draw a rectangle write the following command in line 47 (don't forget the correct indentation).
pygame.draw.rect(screen,WHITE, [50, 50, 50, 50])
The screen is still refreshing at a rate of 60 frames per second but we cannot see it because the rectangle is always at the same position.
Now we are going to move the rectangle. How can we do this? Which of the four numbers [50, 50, 50, 50] is the starting position of the rectangle? If you don't remember look at the picture below and rethink.
First of all we are going to replace the constant numbers with variables, then replace the draw command in line 47 with these eight lines. (don't forget the correct identation)
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
pygame.draw.rect(screen, WHITE, [rect_x, rect_y, 50,50])
rect_x += speed_x
rect_y += speed_y
print ("rect_x =", rect_x, "rect_y =", rect_y)
Nothing is happening. Why? Because 60 times per second rect_x and rect_y become 50 and then 55. Check the CLI area to see where is the starting point of the rectangle. The print command is used to inform us for the position of the rectangle. When we succeed in moving the rectangle we can comment or delete this line of code.
What should we do?
- First : create an initialization block of commands outside the Main program loop and move the first four commands there, taking care of indentation.
- Second : move the next two commands in the Game logic block (it is not necessary but it is better to put commands in the right place, so it is easier to make changes and fix errors).
If you made a mistake that you cannot fix you can download the finished code from here.
Wow!! A moving rectangle!!
Wow!! The rectagle after a while vanishes outside the screen....
Look at the CLI to understand what happened to the rectangle. To stop and Reset Thonny press the button