draw a 3d rotating cube in python

You can use the pyplot module from the popular matplotlib library to draw a 3D rotating cube in Python. Here is an example code:

main.py
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# define cube vertices
vertices = np.array([[-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 edges joining the vertices
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)]

# define the plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# set plot limits
ax.set_xlim([-2, 2])
ax.set_ylim([-2, 2])
ax.set_zlim([-2, 2])

# define the animation function
def rotate(angle):
    ax.clear()
    # rotate the vertices around the x and y axes
    c, s = np.cos(angle), np.sin(angle)
    rotx = np.array([[1, 0, 0],
                     [0, c, -s],
                     [0, s, c]])
    roty = np.array([[c, 0, s],
                     [0, 1, 0],
                     [-s, 0, c]])
    vertices_rot = np.dot(roty, np.dot(rotx, vertices.T)).T
    # plot the rotated cube
    for edge in edges:
        ax.plot3D(vertices_rot[edge, 0], vertices_rot[edge, 1], vertices_rot[edge, 2], 'blue')

# create the animation object
anim = animation.FuncAnimation(fig, rotate, frames=np.linspace(0, 2*np.pi, 50), interval=50)

# show the plot
plt.show()
1459 chars
51 lines

The code defines the vertices of the cube and the edges joining them. It then sets up the plot and defines an animation function (rotate()) that rotates the vertices around the x and y axes at each frame specified by the animation object. Finally, it creates and shows the animation object.

gistlibby LogSnag