Creating a rotating cube using Pygame and Python involves using some basic 3D math to rotate the cube and project it onto a 2D surface. Below is a simple example to get you started:
import pygame
import sys
import math
# Initialize Pygame
pygame.init()
# Set up display
screen_size = (800, 600)
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption("Rotating Cube")
# Define colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# Define the cube's 8 vertices
vertices = [
[-1, -1, -1],
[-1, -1, 1],
[-1, 1, -1],
[-1, 1, 1],
[ 1, -1, -1],
[ 1, -1, 1],
[ 1, 1, -1],
[ 1, 1, 1]
]
# Define the edges that connect these vertices
edges = [
(0, 1), (1, 3), (3, 2), (2, 0),
(4, 5), (5, 7), (7, 6), (6, 4),
(0, 4), (1, 5), (2, 6), (3, 7)
]
# Function to draw a cube
def draw_cube(screen, vertices, edges):
for edge in edges:
points = []
for vertex in edge:
x, y, z = vertices[vertex]
# 3D to 2D projection
# Perspective projection
f = 200 / (z + 5)
x, y = x * f, y * f
# Translate to screen space
x += screen_size[0] / 2
y += screen_size[1] / 2
points.append((x, y))
pygame.draw.line(screen, WHITE, points[0], points[1], 1)
# Function to rotate point around its center
def rotate(vertices, angle_x, angle_y, angle_z):
cos_x, sin_x = math.cos(angle_x), math.sin(angle_x)
cos_y, sin_y = math.cos(angle_y), math.sin(angle_y)
cos_z, sin_z = math.cos(angle_z), math.sin(angle_z)
rotated_vertices = []
for x, y, z in vertices:
# Rotate around X-axis
new_y = y * cos_x - z * sin_x
new_z = y * sin_x + z * cos_x
y, z = new_y, new_z
# Rotate around Y-axis
new_x = x * cos_y + z * sin_y
new_z = -x * sin_y + z * cos_y
x, z = new_x, new_z
# Rotate around Z-axis
new_x = x * cos_z - y * sin_z
new_y = x * sin_z + y * cos_z
x, y = new_x, new_y
rotated_vertices.append([x, y, z])
return rotated_vertices
# Main loop
clock = pygame.time.Clock()
angle_x, angle_y, angle_z = 0, 0, 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Rotate the cube
angle_x += 0.01
angle_y += 0.02
angle_z += 0.03
rotated_vertices = rotate(vertices, angle_x, angle_y, angle_z)
# Fill the background color
screen.fill(RED)
# Draw the cube
draw_cube(screen, rotated_vertices, edges)
# Update the display
pygame.display.flip()
clock.tick(60)
This code creates a simple 3D cube and displays it in a Pygame window. The cube is rendered in a 2D perspective by projecting its 3D coordinates onto the 2D screen. It continuously rotates around its x, y, and z axes.
Instructions to run this script:
-
Make sure you have the pygame library installed. You can install it using pip:
pip install pygame
-
Save the script to a file, for example, rotating_cube.py.
-
Run the script using Python:
python rotating_cube.py
This will open a Pygame window displaying a rotating cube. Adjust the rotation speed or other parameters as needed to see different effects.