blog.dopana

Back

Welcome back, master builder! 🛠️

In the real world, factories don’t design every single toy car or action figure from scratch. Instead, engineers draw a Blueprint (or a mold) once, and the factory uses it to stamp out thousands of actual toys.

In programming, we use this exact same super-efficient trick to build characters and game elements. This is called Object-Oriented Programming (OOP), and it uses Classes and Objects!

Blueprints vs Toys (Classes vs Objects)#

Here is the secret formula:

  • Class: The Blueprint (or cookie cutter). It defines what information a toy should have and what actions it can perform.
  • Object: The actual Toy (or cookie) built from the blueprint.
graph TD
    Blueprint["📐 Class: ToyRobot (Blueprint)"] -->|Builds| Robot1["🤖 robot1 (Object)<br/>name='Rusty'<br/>color='red'"]
    Blueprint -->|Builds| Robot2["🤖 robot2 (Object)<br/>name='Shiny'<br/>color='blue'"]

Writing a Robot Blueprint in Python#

In Python, we declare a blueprint using the word class.

Let’s build a blueprint for a toy robot:

class ToyRobot:
    # 1. The setup (Constructor)
    def __init__(self, name, color):
        self.name = name
        self.color = color

    # 2. An action (Method)
    def dance(self):
        print(self.name + " the " + self.color + " robot is dancing! 💃")
python

Explaining the code#

  • __init__: This is a special setup function. When you build a robot, it immediately runs this code to label the robot’s name and color.
  • self: This refers to the specific robot we are currently setting up or dancing. It keeps Rusty’s name separate from Shiny’s name!

Stamping Out Real Robots (Creating Objects)#

Now that we have our blueprint, let’s start the factory line! We create objects by calling the class name like a function and passing in our name and color parameters:

robot1 = ToyRobot("Rusty", "red")
robot2 = ToyRobot("Shiny", "blue")

# Make them perform actions!
robot1.dance()  # Rusty the red robot is dancing! 💃
robot2.dance()  # Shiny the blue robot is dancing! 💃
python

Try It Yourself! 🎮#

Open your Python editor and try adding a weapon system to your toy robots:

  1. Inside the ToyRobot class, add a new action method underneath dance:
def shoot_laser(self):
    print(self.name + " shoots a " + self.color + " laser beam! ⚡")
python
  1. Run the code and call the command for both robots:
robot1.shoot_laser()
robot2.shoot_laser()
python

You just mastered Object-Oriented Programming! You can now design complex game blueprints for players, inventory items, maps, and enemies, and stamp them out on demand. You are officially ready to design your own world! 🚀🌍

References#