Module 8 - Section 5 - spaceship
|Book:||Module 8 - Section 5 - spaceship|
|Printed by:||Guest user|
|Date:||Friday, 1 December 2023, 9:27 PM|
After the completion of this module the students will be able to:
- identify various classes inside Python code game
- describe the parts of the class and it's use
- identify the objects of a class
- recognize the characteristics and the values of the objects
- modify the code of the game to make it easier or harder
8.5.1 - I have spaceship, do you want a ride?
Most of the time we do not create objects using the draw command of pygame but we use sprites.
One of this sprites that we will use is a spaceship
Sprites are usually in png or gif format. To use this sprite it must be in the same folder as our program.
Right click on the spaceship and save it or click here.
Also download and open this file (avoid_v0.1.0) to Thonny, or copy and paste it from below. Make sure that the sprites and the code are in the same directory. Run the program.
What is the result?
This is another sprite of a meteor
Look at the lines 19 and 50 and try to show (blit) the meteor inside the screen.
Can you show multiple rocks?
8.5.2 - Move with the KeyboardStudy the following lines:
In these lines pygame checks if arrow keys LEFT, RIGHT, UP, DOWN or keys d, a , s, w are pressed down (KEYDOWN) or released (KEYUP) and moves spaceship accordingly.
8.5.4 - Parameters instead of constantsIn the version v0.6.0 of the game what should we do to change the size of the screen? How many changes?
Instead of making all these changes we can use variables for the size of the screen, the size of the spaceship and the screen borders.
The updated code is the following and you can download it from here (avoid_v0.7.0.py)
8.5.5 - Background
To change the background from a dull color to an image we need:
- An image of our choice as a background
- A command to convert the image for the pygame
- A command to blit the image instead of filling with uniform color
For the background image download it from here and save it as background.jpg inside the working folder.
The commands to draw the background are:
background_image = pygame.image.load("background.jpg").convert()
before the main loop but after the screen's set mode and :
screen.blit(background_image, [0, 0])
8.5.6 - Spaceship class
Instead of creating game logic for every object inside the main loop we can create classes for the objects and inside the classes methods. In this way it is easy to create multiple objects with the same logic. You can see the spaceship class in the following code: