ascii donuts art in rust

Here is an example program that creates an ASCII donut animation in Rust using terminal handling libraries:

main.rs
use std::{io::{stdout, Write}, thread, time::Duration};

fn main() {
    let donut_width = 50;
    let donut_height = 25;
    let donut_chars = vec![
        ' ', '.', '`', ',', ':', ';', 'i', 'l', '!', 'i', 'l', ':', ';', ':', '.', ',', '\'',
        '.',
    ];
    let donut_radius1 = 1.0;
    let donut_radius2 = 2.0;
    let mut a1 = 0.0;
    let mut a2 = 0.0;
    let mut output = String::new();
    loop {
        output.clear();
        for j in 0..donut_height {
            for i in 0..donut_width {
                let x = (i as f64 - donut_width as f64 / 2.0) / (donut_width as f64 / 2.0);
                let y = (j as f64 - donut_height as f64 / 2.0) / (donut_height as f64 / 2.0);
                let mut z = 0.0;
                z += (donut_radius1.powi(2) - x.powi(2) - y.powi(2)).sqrt();
                let r2 = donut_radius2.powi(2);
                let x2 = x * (a1 as f64).cos() - y * (a1 as f64).sin();
                let y2 = x * (a1 as f64).sin() + y * (a1 as f64).cos();
                z += (r2 - x2.powi(2) - y2.powi(2) - (a2 as f64).sin()).sqrt();
                let index = ((z * donut_chars.len() as f64) / 3.0).round() as usize;
                output.push(donut_chars[index]);
            }
            output.push('\n');
        }
        print!("{esc}[2J{esc}[1;1H", esc = 27 as char);
        print!("{}", output);
        stdout().flush().unwrap();
        a1 += 0.07;
        a2 += 0.03;
        thread::sleep(Duration::from_millis(50));
    }
}
1486 chars
40 lines

The program uses two nested loops to iterate over the characters in the output grid. For each character, it calculates the corresponding 3D point in the donut shape, and maps it to the appropriate ASCII character by indexing into the donut_chars vector.

The program then clears the terminal, prints the output grid, flushes the standard output stream, and waits for a short duration before repeating the process with updated rotation angles.

gistlibby LogSnag