Task 4.1: Create a Food Class
- Start by creating a new class called
Food. This will be quite similar to the Player class. E.g.:
class Food:
- Inside your
Foodclass, create a special function called__init__.
💡 Hint
- Use the
defkeyword to define the method. - The
__init__method should accept 4 inputs: nameimageposition_xposition_y- Your Food class should have more than 4 properties though, being
name,image,size,position_x,position_yandsprite - Save each of these inputs into the object using
self. - Note that you can set default values for a class like so:
class Car:
# Notice how we don't have a weight parameter in the
# brackets below.
def __init__(self, colour, speed):
# We can set this when creating an instance
colour = colour
speed = speed
# Default property values
weight = 20
- Inside your
__init__()method, set a default size for your food. - Still inside the
__init__()method, load the image file using Pygame'simage.loadfunction. - Scale the loaded image to the correct size using Pygame's
transform scalefunction. - Save the final scaled image into the object (e.g.,
self.sprite).
🚩 Checkpoint
- A
Foodclass (or a class of things you want to have). - Code in the
__init__()method that: - Saves the name, image, and position.
- Sets a default size.
- Loads and scales the sprite.
- A ready-to-use object for your game!