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
Food
class, create a special function called__init__
.
💡 Hint
- Use the
def
keyword to define the method. - The
__init__
method should accept 4 inputs: name
image
position_x
position_y
- Your Food class should have more than 4 properties though, being
name
,image
,size
,position_x
,position_y
andsprite
- 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.load
function. - Scale the loaded image to the correct size using Pygame's
transform scale
function. - Save the final scaled image into the object (e.g.,
self.sprite
).
🚩 Checkpoint
- A
Food
class (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!