Creating a Python game where you navigate a maze, hide from an evil robot using cabinets, avoid video cameras, and ultimately retrieve a blaster to defeat the robot is an exciting project! We'll use the Pygame library, which is ideal for such 2D game development.
Below is a step-by-step guide along with the complete code to build this game.
Prerequisites
-
Python Installed: Ensure you have Python 3.x installed on your system.
-
Pygame Installed: Install Pygame using pip if you haven't already:
pip install pygame
Game Overview
- Player: Can move around the maze, hide in cabinets, and pick up the blaster.
- Evil Robot: Patrols the maze. If a video camera detects the player, it chases the player's last known position.
- Cabinets: Hiding spots where the player can stay hidden from cameras and the robot.
- Video Cameras: Monitor specific areas of the maze. If the player is detected, the robot gets alerted.
- Blaster: Located at the center of the maze. Picking it up allows the player to defeat the robot.
Game Structure
- Setup the Game Window: Initialize Pygame and create the game window.
- Create the Maze: Define the maze layout using a grid system.
- Define Game Objects: Player, robot, cabinets, cameras, and the blaster.
- Handle User Input: Allow the player to move using keyboard inputs.
- Implement Game Mechanics:
- Hiding logic.
- Camera detection.
- Robot AI (patrolling and chasing).
- Blaster mechanics.
- Render Game Elements: Draw all elements on the screen.
- Game Loop: Continuously update the game state and render frames.
Complete Code
Here's the complete Python code using Pygame. The code includes comments to help you understand each part.
import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 800, 600
ROWS, COLS = 20, 20
TILE_SIZE = WIDTH // COLS
FPS = 60
# Colors
WHITE = (255, 255, 255)
GRAY = (70, 70, 70)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
BLACK = (0, 0, 0)
YELLOW = (255, 255, 0)
# Directions
DIRS = {'UP': (0, -1),
'DOWN': (0, 1),
'LEFT': (-1, 0),
'RIGHT': (1, 0)}
# Initialize Screen
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Hide from the Evil Robot")
clock = pygame.time.Clock()
# Font
font = pygame.font.SysFont(None, 36)
# Define Maze (0: Wall, 1: Path)
# Simple maze for demonstration
maze = [
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,1,1,1,0,1,1,1,1,0,1,1,1,1,0,1,1,1,1,0],
[0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,0,1,0],
[0,1,0,1,1,1,1,0,1,1,1,0,1,1,1,1,0,0,1,0],
[0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,1,0,0,1,0],
[0,1,1,1,1,0,1,1,1,0,1,1,1,1,0,1,1,1,1,0],
[0,0,0,0,1,0,0,0,1,0,1,0,0,1,0,0,0,0,1,0],
[0,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0],
[0,1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0],
[0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0],
[0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,1,0,0,1,0],
[0,1,1,1,1,0,1,1,1,0,1,1,1,1,0,1,1,1,1,0],
[0,0,0,0,1,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0],
[0,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0],
[0,1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0],
[0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0],
[0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0],
[0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
]
# Helper Functions
def draw_maze():
for row in range(ROWS):
for col in range(COLS):
tile = maze[row][col]
rect = pygame.Rect(col*TILE_SIZE, row*TILE_SIZE, TILE_SIZE, TILE_SIZE)
if tile == 0:
pygame.draw.rect(screen, GRAY, rect)
else:
pygame.draw.rect(screen, BLACK, rect)
def get_tile(pos):
x, y = pos
col = x // TILE_SIZE
row = y // TILE_SIZE
if 0 <= row < ROWS and 0 <= col < COLS:
return maze[row][col]
return 0
# Game Objects
class Player:
def __init__(self, x, y):
self.rect = pygame.Rect(x, y, TILE_SIZE//2, TILE_SIZE//2)
self.speed = 3
self.hidden = False
self.has_blaster = False
def move(self, dx, dy):
new_rect = self.rect.move(dx, dy)
# Check collision with walls
if get_tile((new_rect.centerx, new_rect.centery)) == 1:
self.rect = new_rect
def draw(self):
color = GREEN if not self.hidden else BLUE
pygame.draw.rect(screen, color, self.rect)
class Cabinet:
def __init__(self, x, y):
self.rect = pygame.Rect(x, y, TILE_SIZE, TILE_SIZE)
def draw(self):
pygame.draw.rect(screen, YELLOW, self.rect)
class Camera:
def __init__(self, x, y, direction, range_limit=5):
self.rect = pygame.Rect(x, y, TILE_SIZE//2, TILE_SIZE//2)
self.direction = direction # 'horizontal' or 'vertical'
self.range_limit = range_limit
self.current_range = 0
self.detected = False
def patrol(self):
# Simple back and forth patrol
if self.direction == 'horizontal':
dx = 1
dy = 0
else:
dx = 0
dy = 1
self.rect.x += dx
self.rect.y += dy
self.current_range += 1
if self.current_range >= self.range_limit:
# Change direction
self.direction = 'vertical' if self.direction == 'horizontal' else 'horizontal'
self.current_range = 0
def detect_player(self, player):
if self.rect.colliderect(player.rect) and not player.hidden:
self.detected = True
return True
return False
def draw(self):
color = RED if self.detected else WHITE
pygame.draw.rect(screen, color, self.rect)
class Robot:
def __init__(self, x, y):
self.rect = pygame.Rect(x, y, TILE_SIZE//2, TILE_SIZE//2)
self.speed = 2
self.chasing = False
self.target = None
def move_towards(self, target_pos):
if self.rect.centerx < target_pos[0]:
self.rect.x += self.speed
elif self.rect.centerx > target_pos[0]:
self.rect.x -= self.speed
if self.rect.centery < target_pos[1]:
self.rect.y += self.speed
elif self.rect.centery > target_pos[1]:
self.rect.y -= self.speed
def update(self):
if self.chasing and self.target:
self.move_towards(self.target)
def draw(self):
color = RED if self.chasing else BLUE
pygame.draw.rect(screen, color, self.rect)
class Blaster:
def __init__(self, x, y):
self.rect = pygame.Rect(x, y, TILE_SIZE//2, TILE_SIZE//2)
self.picked = False
def draw(self):
if not self.picked:
pygame.draw.rect(screen, GREEN, self.rect)
# Initialize Game Objects
player = Player(TILE_SIZE + TILE_SIZE//4, TILE_SIZE + TILE_SIZE//4)
# Place cabinets at predefined locations
cabinets = [
Cabinet(3*TILE_SIZE, 3*TILE_SIZE),
Cabinet(10*TILE_SIZE, 5*TILE_SIZE),
Cabinet(15*TILE_SIZE, 12*TILE_SIZE),
Cabinet(5*TILE_SIZE, 15*TILE_SIZE),
]
# Place cameras
cameras = [
Camera(5*TILE_SIZE, 0*TILE_SIZE, 'horizontal'),
Camera(15*TILE_SIZE, HEIGHT - TILE_SIZE, 'horizontal'),
Camera(0*TILE_SIZE, 10*TILE_SIZE, 'vertical'),
Camera(WIDTH - TILE_SIZE, 10*TILE_SIZE, 'vertical'),
]
# Initialize Robot at a corner
robot = Robot(TILE_SIZE, HEIGHT - 2*TILE_SIZE)
# Place Blaster at center
blaster = Blaster((COLS//2)*TILE_SIZE + TILE_SIZE//4, (ROWS//2)*TILE_SIZE + TILE_SIZE//4)
# Game States
game_over = False
victory = False
# Game Loop
while True:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if not game_over and not victory:
# Handle Input
keys = pygame.key.get_pressed()
dx, dy = 0, 0
if keys[pygame.K_LEFT]:
dx = -player.speed
if keys[pygame.K_RIGHT]:
dx = player.speed
if keys[pygame.K_UP]:
dy = -player.speed
if keys[pygame.K_DOWN]:
dy = player.speed
player.move(dx, dy)
# Check for hiding in cabinets
player.hidden = False
for cabinet in cabinets:
if cabinet.rect.colliderect(player.rect):
player.hidden = True
break
# Update Cameras
for camera in cameras:
camera.patrol()
if camera.detect_player(player):
robot.chasing = True
robot.target = player.rect.center
# Update Robot
robot.update()
# If player has blaster and robot is close, handle victory
if player.has_blaster and robot.rect.colliderect(player.rect):
victory = True
# Check collision with robot
if robot.rect.colliderect(player.rect) and not player.has_blaster:
game_over = True
# Check if player picks up blaster
if player.rect.colliderect(blaster.rect) and not blaster.picked:
player.has_blaster = True
blaster.picked = True
# Draw Everything
screen.fill(BLACK)
draw_maze()
for cabinet in cabinets:
cabinet.draw()
for camera in cameras:
camera.draw()
if not blaster.picked:
blaster.draw()
player.draw()
robot.draw()
# Display Messages
if game_over:
msg = font.render("Game Over! The robot caught you.", True, RED)
screen.blit(msg, (WIDTH//2 - msg.get_width()//2, HEIGHT//2))
if victory:
msg = font.render("Victory! You defeated the robot.", True, GREEN)
screen.blit(msg, (WIDTH//2 - msg.get_width()//2, HEIGHT//2))
pygame.display.flip()
Understanding the Code
-
Maze Representation:
- The maze is represented as a 2D list where
0 denotes walls and 1 denotes paths.
- You can modify the
maze variable to design different maze layouts.
-
Game Objects:
- Player: Controlled by arrow keys. Can hide in cabinets and pick up the blaster.
- Cabinets: Defined locations where the player can hide.
- Cameras: Patrol either horizontally or vertically. If the player is detected (not hidden), the robot starts chasing.
- Robot: Initially patrolling. When alerted, it moves towards the player's last known position.
- Blaster: Located at the center. Picking it up allows the player to defeat the robot upon collision.
-
Game Mechanics:
- Hiding: When the player is within a cabinet’s rectangle, they are considered hidden.
- Detection: Cameras check if the player is in their view. If detected, the robot is alerted.
- Robot AI: Basic movement towards the target position. Can be expanded for more complex behavior.
- Victory & Game Over: Achieved by defeating the robot or being caught by it, respectively.
-
Rendering:
- The maze, cabinets, cameras, player, robot, and blaster are drawn each frame.
- Different colors represent different states (e.g., hidden player, detected camera, robot chasing).
Enhancements and Customizations
This basic game can be expanded and improved in various ways:
- Maze Generation: Implement a maze generator (like DFS-based) for random mazes.
- Robot AI: Enhance the robot's intelligence with better pathfinding (like A* algorithm).
- Multiple Levels: Add multiple maze levels with increasing difficulty.
- Sound Effects: Incorporate sounds for movement, detection, victory, and game over.
- Animations: Add sprite animations for the player and robot.
- More Interactive Elements: Include additional items, obstacles, or power-ups.
Running the Game
-
Save the Code: Save the above code in a Python file, e.g., hide_robot_game.py.
-
Run the Game:
python hide_robot_game.py
-
Controls:
- Use the Arrow Keys to move the player around the maze.
- Objective: Navigate to the blaster at the center while avoiding cameras and the robot.
- Defeat the Robot: Pick up the blaster and collide with the robot.
Enjoy your game development journey! Feel free to modify and expand the game to add more features and complexity.