所以前几天我看到了这个模拟降雪到终端的 bash 脚本。我认为用 C 语言学习 ncurses 是一个简单的项目,但我把它搞得一团糟。我的方法只是用随机的雪花填充一些字符串并将它们写到屏幕上。我没有得到任何我期望的东西。基本上只是一个以光速飞过的大烂摊子。
任何人都可以让我走上正轨吗?这是我要复制其行为的脚本。
#!/bin/bash
LINES=$(tput lines)
COLUMNS=$(tput cols)
declare -A snowflakes
declare -A lastflakes
clear
function move_flake() {
i="$1"
if [ "${snowflakes[$i]}" = "" ] || [ "${snowflakes[$i]}" = "$LINES" ]; then
snowflakes[$i]=0
else
if [ "${lastflakes[$i]}" != "" ]; then
printf "\033[%s;%sH \033[0;0H " ${lastflakes[$i]} $i
fi
fi
printf "\033[%s;%sH*\033[0;0H" ${snowflakes[$i]} $i
lastflakes[$i]=${snowflakes[$i]}
snowflakes[$i]=$((${snowflakes[$i]}+1))
}
while :
do
i=$(($RANDOM % $COLUMNS))
move_flake $i
for x in "${!lastflakes[@]}"
do
move_flake "$x"
done
sleep 0.1
done
最佳答案
好吧,如果您可以在没有假装积雪在地面上的屏幕底部的线条的情况下生活,那就非常简单了。主要技巧是向下滚动屏幕而不是向上滚动。但是,如果您确实想要那个底线,那就更难了,您可能需要尝试除此之外的其他方法。
我只是在我的机器上测试了这个,所以在所有事情中都会诅咒关于终端里程变化应用的常见警告。无论如何,有一些东西可以让你咀嚼和玩耍。 Cntl-C 应该会杀死它,但进行一些适当的错误处理也是一个很好的练习。
#include <ncurses.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int main(int argc, char *argv[])
{
srand (time(NULL));
initscr();
int maxRows, maxCols;
getmaxyx(stdscr, maxRows, maxCols);
int flakesPerRow = maxCols * 0.02;
scrollok(stdscr, TRUE);
while (true)
{
//setup top line
for (int i = 0; i < flakesPerRow; ++i)
{
int x = rand() % maxCols;
mvaddch(0, x, '*');
}
move(0,0); //keeps cursor from bouncing around
scrl(-1); //scroll down, not up
refresh();
napms(200); //delay 200ms
}
endwin();
}
关于c - 在ncurses/C中模拟bash "snow fall"脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8608226/