Pages

Thursday, 24 December 2020

Merry Christmas 2020! A Christmas Tree bash script!

0 Screenshot



1 Source code

#!/bin/bash

#SIGINT

trap "tput reset; tput cnorm; exit" 2

# SIGWINCH

trap "clear" 28

init()

{

    tput setab 0

    tput civis

    tput bold

    flag=0

    clear

}

# $1: y, $2: text

center_print()

{

    local text="$2"

    local len=${#text}

    local cols=$(tput cols)


    if [[ $cols -lt $len ]]; then

        len=$cols

        text=${text:0:$cols}

    fi


    local x=$(((cols-len)/2))

    tput cup "$1" "$x"

    echo -n "$text"

}


draw_tree()

{

    local cols=$(tput cols)

    local lines=$(tput lines)

    local x=$((cols/2))

    local y=0

    local head_height=$((lines*2/3))


    # draw tree head

    for((y=0; y<head_height; y++))

    do

        local n=$((y*2+1)) # line length

        local t=''

        for((j=0;j<n;j++))

        do

            if [[ $((RANDOM % 100)) -lt 20 ]]; then

                t+='+'

            else

                t+='^'

            fi

        done

        # draw leaves

        tput setaf 2

        center_print "$y" "$t"

    done

    # draw tree trunk

    tput setaf 3

    for((y=head_height; y<lines; y++))

    do

        t='****'

        center_print "$y" "$t"

    done

}


draw_msg()

{

    local lines=$(tput lines)

    local msg_y=$((lines/2))

    local msg="Merry $(date +%Y) Christmas!"


    # draw new

    tput setaf $((RANDOM%4+1))

    tput cup $msg_y $msg_x

    center_print $msg_y "$msg"

}


draw_star()

{

    flag=$(((flag+1) % 2))

    local cols=$(tput cols)

    local lines=$(tput lines)

    local max=$((cols*lines))

    local star_count=5

    declare -a pts; # star positions

    for((i=0;i<star_count;i++))

    do

        pts+=( $((RANDOM % max)) )

    done


    for pt in ${pts[@]}

    do

        y=$((pt/cols))

        x=$((pt%cols))

        color=$((RANDOM%8))

        tput setaf $color

        tput cup $y $x

        if [[ $flag -eq 0 ]]; then

            echo -n '*'

        else

            echo -n ' '

        fi

    done

}


main()

{

    init

    timer_tick=0

    while true

    do

        draw_tree

        draw_star

        draw_msg

        sleep 0.3

        timer_tick=$((timer_tick+1))

    done

}


main


No comments:

Post a Comment