博主未授权任何人或组织机构转载博主任何原创文章,感谢各位对原创的支持!
博主链接
博客内容主要围绕:
5G/6G协议讲解
高级C语言讲解
Rust语言讲解
文章目录
- 一起用Rust绘制一颗圣诞树吧
- 一、 Rust Cargo.toml配置文件
- 二、代码实现
一起用Rust绘制一颗圣诞树吧
又是一年圣诞节,我们使用Rust的控制台输出来绘制一颗动态的圣诞树,效果如下:
一、 Rust Cargo.toml配置文件
[package]
name = "helloworld"
version = "0.1.0"
edition = "2021"
[dependencies]
text-colorizer = "1.0.0"
rand = "0.8.5"
clearscreen = "3.0.0"
二、代码实现
- print_rand_leaf():随机化树叶的形状;
- triangle():绘制圣诞树的每一层;
- print_tree():调用triangle()完成整个树冠的绘制;
- print_log():完成整个树杆的绘制;
几个关键常量含义如下:
- REF_RATE:圣诞树的刷新频率,越小刷新越快;
- RANDOMNESS:控制树叶中‘ * ’的密度,越大密度越高;
- WIDTH_FACTOR:控制圣诞树在窗口中的位置,最小值为2。值越大越往右边偏移;
use text_colorizer::*;
use std::thread::sleep;
use std::time::Duration;
use rand::Rng;
static RANDOMNESS:u8 = 5; // 越高树叶越少
static REF_RATE:u64 = 500;
static WIDTH_FACTOR:u16 = 4;
fn print_rand_leaf()
{
let leaf_types:[&str;5] = [".", "*", "⭐", "🍎", "0"];
let mut rng = rand::thread_rng();
let temp = rng.gen_range(0..RANDOMNESS);
// Giving preference to *
if temp == 1
{
let other = rng.gen_range(0..leaf_types.len());
if other == 3
{
print!("{} ", leaf_types[other].red());
}
else if other == 2
{
print!("{} ", leaf_types[other].yellow());
}
else
{
print!("{} ", leaf_types[other]);
}
}
else
{
print!("{} ", leaf_types[1].green());
}
}
fn triangle(f:u16, n:u16, toth:u16)
{
let _i = WIDTH_FACTOR * toth - 2;
let _j = WIDTH_FACTOR * toth - 2;
let mut k = WIDTH_FACTOR * toth - 2;
for _i in 0..f-1
{
k -= 1;
}
// number of rows
for i in f - 1..n
{
// space handler
for _j in 0..k
{
print!(" ");
}
// decrementing k after each loop
k = k - 1;
// number of columns, printing stars
for _j in 0..=i
{
print_rand_leaf();
}
print!("\n");
}
}
// Prints bottom part.
fn print_log(n:u16)
{
let _i = WIDTH_FACTOR * n - 4;
let _j = WIDTH_FACTOR * n - 4;
let k = WIDTH_FACTOR * n - 4;
for _i in 1..7
{
// space handler
for _j in 0..k
{
print!(" ");
}
for _j in 1..7
{
print!("\x1b[38;5;58m#\x1b[0m");
}
print!("\n");
}
}
// Prints multiple triangles
fn print_tree(h:u16)
{
let mut start = 1;
let mut stop = 0;
let mut diff = 3;
while stop < h + 1
{
stop = start + diff;
triangle(start, stop, h);
diff += 1;
start = stop - 2;
}
}
fn main() {
let ht:u16 = 9;
println!("\n*********MERRY CHRISTMAS*********\n\n");
loop {
clearscreen::clear().expect("failed to clear screen");
print!("\n\n\n");
print_tree(ht);
print_log(ht);
sleep(Duration::from_millis(REF_RATE));
}
}
祝各位读者,圣诞节快乐
《【2023】Merry Christmas!一起用C语言绘制一个动态的圣诞树吧》