cube3d.py

Created by rockingchair1196

Created on April 06, 2025

1.67 KB


import kandinsky as kd
import time
import math
def project_vertex(vertex, distance=5):
    x, y, z = vertex
    factor = 100 / (z + distance) 
    x_proj = int(x * factor + 160) 
    y_proj = int(y * factor + 120) 
    return (x_proj, y_proj)
def dpos(sx, sy, ex, ey):
    cx = sx
    cy = sy
    for i in range(100):
        difx = float((ex - cx) / (100 - i))
        dify = float((ey - cy) / (100 - i))
        cx = cx + difx
        cy = cy + dify
        kd.set_pixel(int(cx), int(cy), kd.color(255, 255, 255))
def rotate_vertex(vertex, angle_x, angle_y, angle_z):
    x, y, z = vertex
    y, z = y * math.cos(angle_x) - z * math.sin(angle_x), y * math.sin(angle_x) + z * math.cos(angle_x)
    x, z = x * math.cos(angle_y) + z * math.sin(angle_y), -x * math.sin(angle_y) + z * math.cos(angle_y)
    x, y = x * math.cos(angle_z) - y * math.sin(angle_z), x * math.sin(angle_z) + y * math.cos(angle_z)
    return [x, y, z]
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]  
]
edges = [
    (0, 1), (1, 2), (2, 3), (3, 0),
    (4, 5), (5, 6), (6, 7), (7, 4),
    (0, 4), (1, 5), (2, 6), (3, 7)  
]
distance = 5
angle_x = 0
angle_y = 0
angle_z = 0
rotation_speed = 0.1
while True:
    kd.fill_rect(0, 0, 320, 240, kd.color(0, 0, 0))
    projected_vertices = [project_vertex(rotate_vertex(v, angle_x, angle_y, angle_z), distance) for v in vertices]
    for edge in edges:
        start, end = edge
        sx, sy = projected_vertices[start]
        ex, ey = projected_vertices[end]
        dpos(sx, sy, ex, ey)

    angle_x += rotation_speed
    angle_y += rotation_speed
    angle_z += rotation_speed
    time.sleep(0.01)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.