Creating a 3D Snake Game in Python is an exciting project that involves 3D graphics, game logic, and user interaction. While Python isn't traditionally known for high-performance 3D games, libraries like Panda3D make it possible to create engaging 3D games efficiently.
Below is a comprehensive guide to building a 3D Snake Game using Python and Panda3D.
Table of Contents
- Prerequisites
- Project Setup
- Basic Game Structure
- Creating the Snake
- Implementing Snake Movement
- Food Spawning
- Collision Detection
- Growing the Snake
- Score System
- Game Over Conditions
- Enhancements
- Complete Code
- Conclusion
Prerequisites
Before diving into the development, ensure you have the following:
-
Python 3.7+: Make sure Python is installed on your system. You can download it from Python's official website.
-
Panda3D: A powerful 3D engine for Python. Install it using pip:
pip install panda3d
-
Basic Python Knowledge: Familiarity with Python programming concepts.
Project Setup
-
Create Project Directory
Create a new directory for your project, e.g., 3D_Snake_Game.
mkdir 3D_Snake_Game
cd 3D_Snake_Game
-
Create Virtual Environment (Optional but Recommended)
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install Dependencies
Ensure Panda3D is installed:
pip install panda3d
-
Project Structure
3D_Snake_Game/
├── assets/
│ ├── models/
│ │ ├── snake_head.bam
│ │ ├── snake_body.bam
│ │ └── food.bam
│ └── textures/
│ ├── snake_head.png
│ ├── snake_body.png
│ └── food.png
├── main.py
└── README.md
Note: You can create simple 3D models using software like Blender and export them in formats compatible with Panda3D (like .bam or .egg). For simplicity, we'll use built-in shapes.
Basic Game Structure
We'll start by setting up the basic window and initializing Panda3D.
# main.py
from direct.showbase.ShowBase import ShowBase
from panda3d.core import WindowProperties
class SnakeGame(ShowBase):
def __init__(self):
super().__init__()
# Set window title
props = WindowProperties()
props.setTitle("3D Snake Game")
self.win.requestProperties(props)
# Disable default camera controls
self.disableMouse()
# Set camera position
self.camera.setPos(0, -20, 10)
self.camera.setHpr(0, -20, 0)
# Setup lighting
self.setup_lighting()
def setup_lighting(self):
from panda3d.core import AmbientLight, DirectionalLight
ambient_light = AmbientLight("ambient_light")
ambient_light.setColor((0.5, 0.5, 0.5, 1))
ambient_light_np = self.render.attachNewNode(ambient_light)
self.render.setLight(ambient_light_np)
directional_light = DirectionalLight("directional_light")
directional_light.setDirection((-5, -5, -5))
directional_light.setColor((1, 1, 1, 1))
directional_light_np = self.render.attachNewNode(directional_light)
self.render.setLight(directional_light_np)
if __name__ == "__main__":
game = SnakeGame()
game.run()
Explanation:
-
ShowBase: The base class for Panda3D applications. It initializes the window and rendering pipeline.
-
Camera Setup: Positioning the camera to have a good view of the game area.
-
Lighting: Adding ambient and directional lights to illuminate the scene.
Creating the Snake
Let's create the snake's head and body segments.
# main.py (continued)
from panda3d.core import loader, NodePath, LVector3
class SnakeGame(ShowBase):
def __init__(self):
super().__init__()
# ... previous initialization ...
# Initialize snake attributes
self.snake_segments = []
self.segment_spacing = 1.0
self.direction = LVector3(1, 0, 0) # Initial direction: positive X-axis
# Create snake head
self.create_snake_head()
def create_snake_head(self):
# Using built-in models for simplicity
self.snake_head = self.loader.loadModel("models/box") # Simple cube as head
self.snake_head.setScale(0.5, 0.5, 0.5)
self.snake_head.setColor(0, 1, 0, 1) # Green color
self.snake_head.reparentTo(self.render)
self.snake_head.setPos(0, 0, 0)
self.snake_segments.append(self.snake_head)
Explanation:
Implementing Snake Movement
We'll enable the snake to move forward continuously and change direction based on user input.
# main.py (continued)
from panda3d.core import ClockObject
class SnakeGame(ShowBase):
def __init__(self):
super().__init__()
# ... previous initialization ...
# Movement parameters
self.speed = 5.0 # Units per second
self.turning_speed = 90 # Degrees per second
# Accepting user input
self.accept("arrow_left", self.set_direction, [LVector3(-1, 0, 0)])
self.accept("arrow_right", self.set_direction, [LVector3(1, 0, 0)])
self.accept("arrow_up", self.set_direction, [LVector3(0, 1, 0)])
self.accept("arrow_down", self.set_direction, [LVector3(0, -1, 0)])
# Task to update movement
self.taskMgr.add(self.update_movement, "UpdateMovement")
def set_direction(self, new_dir):
# Prevent the snake from reversing
if (new_dir + self.direction).length() != 0:
self.direction = new_dir
def update_movement(self, task):
dt = globalClock.getDt()
displacement = self.direction * self.speed * dt
new_pos = self.snake_head.getPos() + displacement
self.snake_head.setPos(new_pos)
# Update positions of body segments
for i in range(1, len(self.snake_segments)):
prev_segment = self.snake_segments[i - 1]
current_segment = self.snake_segments[i]
current_segment.setPos(prev_segment.getPos())
return task.cont
Explanation:
-
User Input: Listening to arrow keys to change the snake's direction.
-
Direction Handling: Ensures the snake cannot reverse directly.
-
Movement Task: Continuously updates the snake's position based on the current direction and speed.
-
Body Movement: Each body segment follows the previous segment's position.
Food Spawning
Implement food objects that the snake can consume to grow.
# main.py (continued)
import random
from panda3d.core import CollisionNode, CollisionSphere, CollisionHandlerEvent
class SnakeGame(ShowBase):
def __init__(self):
super().__init__()
# ... previous initialization ...
# Create initial food
self.food = self.create_food()
def create_food(self):
food = self.loader.loadModel("models/sphere") # Simple sphere as food
food.setScale(0.3, 0.3, 0.3)
food.setColor(1, 0, 0, 1) # Red color
food.reparentTo(self.render)
self.place_food(food)
# Add collision detection
food_collider = CollisionNode('food_collider')
food_collider.addSolid(CollisionSphere(0, 0, 0, 0.3))
food_collider_np = food.attachNewNode(food_collider)
food_collider_np.setCollideMask(0x10)
# Add collision handler
self.cHandler = CollisionHandlerEvent()
self.cHandler.addInPattern('%fn-into-%in')
self.cHandler.addOutPattern('%fn-out-%in')
self.cTrav = self.cTrav
self.cTrav.addCollider(food_collider_np, self.cHandler)
self.accept('snake_head-into-food_collider', self.on_eat)
return food
def place_food(self, food):
x = random.randint(-10, 10)
y = random.randint(-10, 10)
z = 0
food.setPos(x, y, z)
def on_eat(self, entry):
print("Food eaten!")
self.food.removeNode()
self.food = self.create_food()
self.grow_snake()
def grow_snake(self):
new_segment = self.loader.loadModel("models/box")
new_segment.setScale(0.5, 0.5, 0.5)
new_segment.setColor(0, 1, 0, 1) # Same color as head
new_segment.reparentTo(self.render)
last_pos = self.snake_segments[-1].getPos()
new_segment.setPos(last_pos - self.direction * self.segment_spacing)
self.snake_segments.append(new_segment)
Explanation:
-
Food Model: A simple red sphere represents the food.
-
Random Placement: Food spawns at random positions within the game area.
-
Collision Detection: Uses Panda3D's collision system to detect when the snake head intersects with the food.
-
Eating Food: Upon collision, the food is removed, new food is spawned, and the snake grows.
Collision Detection
Apart from food collision, we need to handle collisions with boundaries and self-collisions to end the game.
# main.py (continued)
class SnakeGame(ShowBase):
def __init__(self):
super().__init__()
# ... previous initialization ...
# Setup collision for snake head
self.setup_head_collision()
# Define game boundaries
self.boundary_size = 10
self.create_boundaries()
def setup_head_collision(self):
head_collider = CollisionNode('snake_head')
head_collider.addSolid(CollisionSphere(0, 0, 0, 0.5))
head_collider_np = self.snake_head.attachNewNode(head_collider)
head_collider_np.setCollideMask(0x10)
# Add collision handler
self.cHandler = CollisionHandlerEvent()
self.cHandler.addInPattern('%fn-into-%in')
self.cTrav = self.cTrav
self.cTrav.addCollider(head_collider_np, self.cHandler)
self.accept('snake_head-into-wall_collider', self.on_collision)
self.accept('snake_head-into-body_collider', self.on_collision)
def create_boundaries(self):
# Create walls around the play area
wall_thickness = 1
wall_height = 5
# Front and Back walls
for z in [-wall_thickness / 2, self.boundary_size + wall_thickness / 2]:
wall = self.loader.loadModel("models/box")
wall.setScale(self.boundary_size, wall_thickness, wall_height)
wall.setColor(0.5, 0.5, 0.5, 1)
wall.reparentTo(self.render)
if z < 0:
wall.setPos(0, z, wall_height / 2)
else:
wall.setPos(0, z, wall_height / 2)
# Add collision
collider = CollisionNode('wall_collider')
collider.addSolid(CollisionBox((0, 0, wall_height / 2), self.boundary_size, wall_thickness, wall_height / 2))
wall.attachNewNode(collider)
collider.setCollideMask(0x10)
# Left and Right walls
for x in [-wall_thickness / 2, self.boundary_size + wall_thickness / 2]:
wall = self.loader.loadModel("models/box")
wall.setScale(wall_thickness, self.boundary_size, wall_height)
wall.setColor(0.5, 0.5, 0.5, 1)
wall.reparentTo(self.render)
if x < 0:
wall.setPos(x, 0, wall_height / 2)
else:
wall.setPos(x, 0, wall_height / 2)
# Add collision
collider = CollisionNode('wall_collider')
collider.addSolid(CollisionBox((0, 0, wall_height / 2), wall_thickness, self.boundary_size, wall_height / 2))
wall.attachNewNode(collider)
collider.setCollideMask(0x10)
def on_collision(self, entry):
print("Collision detected! Game Over.")
self.game_over()
def game_over(self):
# Display game over message and exit
from direct.gui.OnscreenText import OnscreenText
game_over_text = OnscreenText(text="Game Over!",
pos=(0, 0),
scale=0.1,
fg=(1, 0, 0, 1))
self.taskMgr.doMethodLater(3, self.exit_game, 'ExitGame')
def exit_game(self, task):
self.userExit()
return task.done
Explanation:
-
Snake Head Collision: Added a CollisionSphere to the snake head to detect collisions with walls and body segments.
-
Game Boundaries: Created walls around the play area using scaled boxes and added collision nodes to them.
-
Collision Handling: If the snake head collides with a wall or its own body, the game ends.
-
Game Over: Displays a "Game Over" message and exits after a short delay.
Score System
Implement a simple score system that increases when the snake eats food.
# main.py (continued)
from direct.gui.OnscreenText import OnscreenText
class SnakeGame(ShowBase):
def __init__(self):
super().__init__()
# ... previous initialization ...
# Initialize score
self.score = 0
self.score_text = OnscreenText(text=f"Score: {self.score}",
pos=(-1.3, 0.9),
scale=0.07,
fg=(1, 1, 1, 1),
align=TextNode.ALeft)
def on_eat(self, entry):
print("Food eaten!")
self.food.removeNode()
self.food = self.create_food()
self.grow_snake()
self.update_score()
def update_score(self):
self.score += 10
self.score_text.setText(f"Score: {self.score}")
Explanation:
Game Over Conditions
Implement self-collision detection where the game ends if the snake collides with itself.
# main.py (continued)
class SnakeGame(ShowBase):
def __init__(self):
super().__init__()
# ... previous initialization ...
self.setup_self_collision()
def setup_self_collision(self):
# Collision setup for body segments
for segment in self.snake_segments[1:]:
collider = CollisionNode('body_collider')
collider.addSolid(CollisionSphere(0, 0, 0, 0.5))
segment.attachNewNode(collider)
collider.setCollideMask(0x10)
# Update collision handler
self.accept('snake_head-into-body_collider', self.on_collision)
def grow_snake(self):
new_segment = self.loader.loadModel("models/box")
new_segment.setScale(0.5, 0.5, 0.5)
new_segment.setColor(0, 1, 0, 1) # Same color as head
new_segment.reparentTo(self.render)
last_segment = self.snake_segments[-1]
new_segment.setPos(last_segment.getPos() - self.direction * self.segment_spacing)
self.snake_segments.append(new_segment)
# Add collision to new segment
collider = CollisionNode('body_collider')
collider.addSolid(CollisionSphere(0, 0, 0, 0.5))
new_segment.attachNewNode(collider)
collider.setCollideMask(0x10)
Explanation:
-
Body Collision Nodes: Each body segment has a CollisionSphere to detect collisions with the snake head.
-
Handling Self-Collision: If the snake head collides with any body segment, the game ends.
Enhancements
To make the game more engaging, consider adding the following enhancements:
-
Camera Follow: Make the camera follow the snake smoothly.
-
Speed Increase: Gradually increase the snake's speed as the score increases.
-
Sound Effects: Add sounds for eating food and game over events.
-
3D Models and Textures: Use detailed 3D models and textures for the snake and food.
-
Pause Functionality: Allow the player to pause and resume the game.
-
High Score Tracking: Keep track of and display high scores.
-
Mobile Controls: Implement touch controls for mobile devices.
Complete Code
Here's the complete main.py script combining all the components:
# main.py
from direct.showbase.ShowBase import ShowBase
from panda3d.core import WindowProperties, LVector3, CollisionSphere, CollisionNode, CollisionHandlerEvent, CollisionTraverser, TextNode, CollisionBox
from direct.gui.OnscreenText import OnscreenText
import random
class SnakeGame(ShowBase):
def __init__(self):
super().__init__()
# Window setup
props = WindowProperties()
props.setTitle("3D Snake Game")
self.win.requestProperties(props)
self.disableMouse()
self.camera.setPos(0, -20, 10)
self.camera.setHpr(0, -20, 0)
# Lighting
self.setup_lighting()
# Initialize snake attributes
self.snake_segments = []
self.segment_spacing = 1.0
self.direction = LVector3(1, 0, 0) # Initial direction: positive X-axis
self.speed = 5.0 # Units per second
# Create snake head
self.create_snake_head()
# Initialize score
self.score = 0
self.score_text = OnscreenText(text=f"Score: {self.score}",
pos=(-1.3, 0.9),
scale=0.07,
fg=(1, 1, 1, 1),
align=TextNode.ALeft)
# Accepting user input
self.accept("arrow_left", self.set_direction, [LVector3(-1, 0, 0)])
self.accept("arrow_right", self.set_direction, [LVector3(1, 0, 0)])
self.accept("arrow_up", self.set_direction, [LVector3(0, 1, 0)])
self.accept("arrow_down", self.set_direction, [LVector3(0, -1, 0)])
# Collision setup
self.cTrav = CollisionTraverser()
self.cHandler = CollisionHandlerEvent()
self.cHandler.addInPattern('%fn-into-%in')
self.accept('snake_head-into-food_collider', self.on_eat)
self.accept('snake_head-into-wall_collider', self.on_collision)
self.accept('snake_head-into-body_collider', self.on_collision)
# Create initial food
self.food = self.create_food()
# Create game boundaries
self.boundary_size = 10
self.create_boundaries()
# Setup self-collision
self.setup_self_collision()
# Task to update movement
self.taskMgr.add(self.update_movement, "UpdateMovement")
def setup_lighting(self):
from panda3d.core import AmbientLight, DirectionalLight
ambient_light = AmbientLight("ambient_light")
ambient_light.setColor((0.5, 0.5, 0.5, 1))
ambient_light_np = self.render.attachNewNode(ambient_light)
self.render.setLight(ambient_light_np)
directional_light = DirectionalLight("directional_light")
directional_light.setDirection((-5, -5, -5))
directional_light.setColor((1, 1, 1, 1))
directional_light_np = self.render.attachNewNode(directional_light)
self.render.setLight(directional_light_np)
def create_snake_head(self):
self.snake_head = self.loader.loadModel("models/box") # Simple cube as head
self.snake_head.setScale(0.5, 0.5, 0.5)
self.snake_head.setColor(0, 1, 0, 1) # Green color
self.snake_head.reparentTo(self.render)
self.snake_head.setPos(0, 0, 0)
self.snake_segments.append(self.snake_head)
# Setup collision for snake head
head_collider = CollisionNode('snake_head')
head_collider.addSolid(CollisionSphere(0, 0, 0, 0.5))
head_collider_np = self.snake_head.attachNewNode(head_collider)
head_collider_np.setCollideMask(0x10)
self.cTrav.addCollider(head_collider_np, self.cHandler)
def set_direction(self, new_dir):
# Prevent the snake from reversing
if (new_dir + self.direction).length() != 0:
self.direction = new_dir
def update_movement(self, task):
dt = globalClock.getDt()
displacement = self.direction * self.speed * dt
new_pos = self.snake_head.getPos() + displacement
self.snake_head.setPos(new_pos)
# Update positions of body segments
for i in range(1, len(self.snake_segments)):
prev_segment = self.snake_segments[i - 1]
current_segment = self.snake_segments[i]
current_segment.setPos(prev_segment.getPos())
return task.cont
def create_food(self):
food = self.loader.loadModel("models/sphere") # Simple sphere as food
food.setScale(0.3, 0.3, 0.3)
food.setColor(1, 0, 0, 1) # Red color
food.reparentTo(self.render)
self.place_food(food)
# Add collision detection
food_collider = CollisionNode('food_collider')
food_collider.addSolid(CollisionSphere(0, 0, 0, 0.3))
food_collider_np = food.attachNewNode(food_collider)
food_collider_np.setCollideMask(0x10)
self.cTrav.addCollider(food_collider_np, self.cHandler)
return food
def place_food(self, food):
x = random.randint(-self.boundary_size + 1, self.boundary_size -1)
y = random.randint(-self.boundary_size +1, self.boundary_size -1)
z = 0
food.setPos(x, y, z)
def on_eat(self, entry):
print("Food eaten!")
self.food.removeNode()
self.food = self.create_food()
self.grow_snake()
self.update_score()
def grow_snake(self):
new_segment = self.loader.loadModel("models/box")
new_segment.setScale(0.5, 0.5, 0.5)
new_segment.setColor(0, 1, 0, 1) # Same color as head
new_segment.reparentTo(self.render)
last_segment = self.snake_segments[-1]
new_segment.setPos(last_segment.getPos() - self.direction * self.segment_spacing)
self.snake_segments.append(new_segment)
# Add collision to new segment
collider = CollisionNode('body_collider')
collider.addSolid(CollisionSphere(0, 0, 0, 0.5))
new_segment.attachNewNode(collider)
collider.setCollideMask(0x10)
def update_score(self):
self.score += 10
self.score_text.setText(f"Score: {self.score}")
def create_boundaries(self):
from panda3d.core import CollisionBox
# Front and Back walls
for z in [-self.boundary_size, self.boundary_size]:
wall = self.loader.loadModel("models/box")
wall.setScale(self.boundary_size*1.1, 1, 5)
wall.setColor(0.5, 0.5, 0.5, 1)
wall.reparentTo(self.render)
wall.setPos(0, z, 2.5)
# Add collision
collider = CollisionNode('wall_collider')
collider.addSolid(CollisionBox((0, 0, 2.5), self.boundary_size*1.1, 1, 2.5))
wall.attachNewNode(collider)
collider.setCollideMask(0x10)
self.cTrav.addCollider(wall.find('**/wall_collider'), self.cHandler)
# Left and Right walls
for x in [-self.boundary_size, self.boundary_size]:
wall = self.loader.loadModel("models/box")
wall.setScale(1, self.boundary_size*1.1, 5)
wall.setColor(0.5, 0.5, 0.5, 1)
wall.reparentTo(self.render)
wall.setPos(x, 0, 2.5)
# Add collision
collider = CollisionNode('wall_collider')
collider.addSolid(CollisionBox((0, 0, 2.5), 1, self.boundary_size*1.1, 2.5))
wall.attachNewNode(collider)
collider.setCollideMask(0x10)
self.cTrav.addCollider(wall.find('**/wall_collider'), self.cHandler)
def setup_self_collision(self):
# Collision setup for body segments
for segment in self.snake_segments[1:]:
collider = CollisionNode('body_collider')
collider.addSolid(CollisionSphere(0, 0, 0, 0.5))
segment.attachNewNode(collider)
collider.setCollideMask(0x10)
self.cTrav.addCollider(segment.find('**/body_collider'), self.cHandler)
def on_collision(self, entry):
print("Collision detected! Game Over.")
self.game_over()
def game_over(self):
from direct.gui.OnscreenText import OnscreenText
game_over_text = OnscreenText(text=f"Game Over! Final Score: {self.score}",
pos=(0, 0),
scale=0.1,
fg=(1, 0, 0, 1),
align=TextNode.ACenter)
self.taskMgr.doMethodLater(3, self.exit_game, 'ExitGame')
def exit_game(self, task):
self.userExit()
return task.done
if __name__ == "__main__":
game = SnakeGame()
game.run()
Notes:
-
Models: For simplicity, we're using built-in Panda3D models like box and sphere. For a more polished game, consider creating custom models in Blender and importing them.
-
Collision Traverser: Manages collision detection. Ensure colliders are added correctly to all relevant objects.
-
Error Handling: The current implementation is basic. Consider adding error handling and edge case management for a robust game.
Conclusion
Building a 3D Snake Game in Python using Panda3D provides a hands-on experience with 3D graphics, user input handling, collision detection, and game logic. While Python may not match the performance of engines like Unity or Unreal for complex 3D games, Panda3D is a powerful tool that balances ease of use with functionality.
Next Steps:
-
Enhance Graphics: Use detailed models and textures to improve visual appeal.
-
Add Sound: Incorporate sound effects for eating food, collisions, and background music.
-
Implement UI: Design a start menu, pause functionality, and other UI elements.
-
Optimize Performance: As the snake grows, optimize collision checks and rendering.
-
Explore Advanced Features: Introduce levels, obstacles, or special food items with unique effects.
Happy Coding!
If you encounter any issues or have specific questions about the implementation, feel free to ask!