Introduction
In this tutorial, you'll learn how to create a basic robotic movement simulation using Python and the PyGame library. Inspired by the recent achievement of a humanoid robot setting a half-marathon record, we'll build a simple simulation that demonstrates the principles of autonomous robot navigation and path planning. This hands-on project will teach you fundamental concepts of robotics programming, including movement algorithms, obstacle detection, and autonomous decision-making.
Prerequisites
To follow this tutorial, you'll need:
- A computer running Windows, macOS, or Linux
- Python 3.6 or higher installed on your system
- Basic understanding of programming concepts
- PyGame library installed (we'll cover installation)
Step-by-Step Instructions
1. Setting Up Your Development Environment
1.1 Install Python
If you don't already have Python installed, download it from python.org. Make sure to check the box that says "Add Python to PATH" during installation. Verify your installation by opening a terminal or command prompt and typing:
python --version
1.2 Install PyGame Library
PyGame is a set of Python modules designed for writing video games, but it's also perfect for creating robotics simulations. Install it using pip:
pip install pygame
This library will allow us to create visual representations of our robot and simulate its movements.
2. Creating the Basic Robot Simulation
2.1 Create the Main Simulation File
Create a new file called robot_simulation.py and start with the basic imports:
import pygame
import math
import random
# Initialize Pygame
pygame.init()
# Set up display
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Robot Path Planning Simulation')
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
# Robot class
class Robot:
def __init__(self, x, y):
self.x = x
self.y = y
self.radius = 15
self.speed = 2
self.angle = 0
def draw(self, screen):
pygame.draw.circle(screen, BLUE, (int(self.x), int(self.y)), self.radius)
# Draw direction indicator
end_x = self.x + self.radius * math.cos(self.angle)
end_y = self.y + self.radius * math.sin(self.angle)
pygame.draw.line(screen, BLACK, (self.x, self.y), (end_x, end_y), 3)
def move(self):
self.x += self.speed * math.cos(self.angle)
self.y += self.speed * math.sin(self.angle)
# Main game loop
running = True
robot = Robot(100, 300)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Fill screen with white
screen.fill(WHITE)
# Move and draw robot
robot.move()
robot.draw(screen)
pygame.display.flip()
pygame.quit()
2.2 Understanding the Robot Class
The Robot class is the foundation of our simulation. It has:
- Position: x and y coordinates
- Size: radius for visualization
- Speed: how fast the robot moves
- Angle: direction the robot is facing
This basic structure allows us to create a robot that can move around the screen.
3. Adding Obstacle Detection
3.1 Create Obstacle Class
Let's enhance our simulation by adding obstacles that the robot must navigate around:
class Obstacle:
def __init__(self, x, y, width, height):
self.rect = pygame.Rect(x, y, width, height)
self.color = RED
def draw(self, screen):
pygame.draw.rect(screen, self.color, self.rect)
# Create obstacles
obstacles = [
Obstacle(200, 100, 100, 20),
Obstacle(400, 200, 20, 150),
Obstacle(300, 400, 150, 20),
Obstacle(600, 300, 20, 100)
]
3.2 Implement Collision Detection
Modify the robot's movement method to detect and avoid obstacles:
def move(self):
# Store original position
old_x, old_y = self.x, self.y
# Calculate new position
new_x = self.x + self.speed * math.cos(self.angle)
new_y = self.y + self.speed * math.sin(self.angle)
# Check for collisions with obstacles
robot_rect = pygame.Rect(new_x - self.radius, new_y - self.radius,
self.radius * 2, self.radius * 2)
collision = False
for obstacle in obstacles:
if robot_rect.colliderect(obstacle.rect):
collision = True
break
# Only move if no collision
if not collision:
self.x = new_x
self.y = new_y
else:
# Change direction randomly when hitting obstacle
self.angle += random.uniform(-0.5, 0.5)
4. Implementing Path Planning
4.1 Add Destination Point
Let's add a destination point that the robot should reach:
# Add to main variables
destination = (700, 500)
# Add to draw function
pygame.draw.circle(screen, GREEN, destination, 10)
pygame.draw.circle(screen, BLACK, destination, 10, 2)
4.2 Implement Simple Path Following
Update the robot's movement to include basic path following:
def move(self):
# Calculate direction to destination
dx = destination[0] - self.x
dy = destination[1] - self.y
distance = math.sqrt(dx*dx + dy*dy)
# If close enough to destination, stop
if distance < 20:
return
# Calculate angle to destination
target_angle = math.atan2(dy, dx)
# Gradually turn towards target
angle_diff = target_angle - self.angle
# Normalize angle difference
while angle_diff > math.pi:
angle_diff -= 2 * math.pi
while angle_diff < -math.pi:
angle_diff += 2 * math.pi
# Rotate towards target (small step)
self.angle += angle_diff * 0.05
# Store original position
old_x, old_y = self.x, self.y
# Calculate new position
new_x = self.x + self.speed * math.cos(self.angle)
new_y = self.y + self.speed * math.sin(self.angle)
# Check for collisions with obstacles
robot_rect = pygame.Rect(new_x - self.radius, new_y - self.radius,
self.radius * 2, self.radius * 2)
collision = False
for obstacle in obstacles:
if robot_rect.colliderect(obstacle.rect):
collision = True
break
# Only move if no collision
if not collision:
self.x = new_x
self.y = new_y
else:
# Change direction randomly when hitting obstacle
self.angle += random.uniform(-0.5, 0.5)
5. Running the Simulation
5.1 Execute Your Program
Save your robot_simulation.py file and run it:
python robot_simulation.py
You should see a blue robot (the robot) and a green circle (destination) with red obstacles. The robot will navigate towards the destination while avoiding obstacles.
5.2 Observing Robot Behavior
Notice how the robot:
- Moves toward the destination
- Changes direction when it hits obstacles
- Adjusts its path dynamically
This demonstrates basic autonomous navigation principles used in real robots like the one that completed the half-marathon.
Summary
In this tutorial, you've built a simple robot simulation that demonstrates key concepts of autonomous navigation. You learned how to:
- Create a robot with position, speed, and direction
- Implement basic movement and collision detection
- Build simple path planning algorithms
- Simulate obstacle avoidance
While this is a simplified simulation, it mirrors the core principles used in real robotics - path planning, obstacle detection, and autonomous decision-making. The humanoid robot that completed the half-marathon used similar technologies, though with much more sophisticated sensors and processing power.
As you continue exploring robotics, you can expand this simulation by adding:
- More complex sensors
- Advanced pathfinding algorithms (like A*)
- Multiple robots working together
- Real-time data processing capabilities
This foundation gives you the building blocks to understand how robots like the one in the news article can navigate complex environments autonomously.



