draw spinning cube ascii in python

You can draw a spinning cube using ASCII art in Python by first defining the shape of the cube as a list of strings. Then, you can rotate the cube by swapping the positions of the characters in each string with the positions of the adjacent strings.

Here's an example code:

main.py
import time

cube = [
    "    _____",
    "  /   / /|",
    " /___/ / |",
    "|   | | |/",
    "|___|/_|/",
]

while True:
    # Clear console
    print("\033c", end="")

    # Rotate cube
    for i in range(len(cube)):
        line = cube[i]
        if i == 0:
            cube[i] = line[2] + line[5:] + line[1]
        elif i == len(cube) - 1:
            cube[i] = line[4] + line[1:4]
        else:
            cube[i] = line[-1] + line[1:-1] + line[0]

    # Print cube
    for line in cube:
        print(line)
    
    # Wait for next rotation
    time.sleep(0.2)
572 chars
31 lines

This code draws a 5x5x5 cube, which is represented as a list of strings. The while loop continuously rotates the cube by swapping characters in the strings. The print("\033c", end="") command clears the console before each rotation so that the spinning cube appears to be animated. The time.sleep(0.2) command adds a short delay between each rotation to control the speed of the animation.

You can modify this code to create different shapes of ASCII art, or adjust the rotation speed and direction to create different animations.

related categories

gistlibby LogSnag