Skip to content

Instantly share code, notes, and snippets.

@melborne
Last active December 31, 2015 03:38
Show Gist options
  • Save melborne/7928434 to your computer and use it in GitHub Desktop.
Save melborne/7928434 to your computer and use it in GitHub Desktop.
Translate Let it Snow in the Terminal from Ruby to Ruby
# Translate Let it Snow in the Terminal from Ruby to Ruby
#
# Original code:
# ruby -e 'C=`stty size`.scan(/\d+/)[1].to_i;S=["2743".to_i(16)].pack("U*");a={}; \
# puts "\e[2J";loop{a[rand(C)]=0;a.each{|x,o|;a[x]+=1;print "\e[#{o};#{x}H \
# \e[#{a[x]};#{x}H#{S} \e[0;0H"};$stdout.flush;sleep 0.1}'
#
# Let it Snow in the Terminal of Mac OS X with This Command
# http://osxdaily.com/2013/12/06/snow-terminal-mac-os-x-command/
#
# Macのターミナルで雪が降る ~ 最後のホワイトクリスマス - #RyoAnnaBlog
# http://d.hatena.ne.jp/RyoAnna/20131211/1386769871
class Snow
MARK = ["2743".to_i(16)].pack("U*")
def self.run(x, colorize=false, mark=MARK)
new(x, colorize, mark).run
end
def initialize(x, colorize, mark)
@x = x
@colorize = colorize
@mark = mark
@screen = {}
$stdout.sync = true
end
def run
clear_screen
loop_on(0.1) do
print_snows
end
end
private
def clear_screen
print "\e[2J"
end
def loop_on(interval)
loop do
yield
sleep interval
end
end
def print_snows
@screen[rand @x] = 0
@screen.each do |x, y|
@screen[x] += 1
clear_prev_snow(x, y)
color = @colorize ? [*31..37].sample : 37
draw_snow(x, @screen[x], color)
end
end
def clear_prev_snow(x, y)
draw_mark(x, y, " ")
end
def draw_snow(x, y, color)
draw_mark(x, y, @mark, color)
end
def draw_mark(x, y, mark, color=37)
print "\e[%dm \e[%d;%dH%s \e[0;0H \e[0m" % [color, y, x, mark]
end
end
if __FILE__ == $0
# $ ruby snow.rb c
# or
# ruby -e 'C=`stty size`.scan(/\d+/)[1].to_i;S=["2743".to_i(16)].pack("U*");a={};puts "\e[2J";loop{a[rand(C)]=0;a.each{|x,o|;a[x]+=1;print "\e[#{o};#{x}H \e[#{[*31..37].sample}m \e[#{a[x]};#{x}H#{S} \e[0;0H \e[0m"};$stdout.flush;sleep 0.1}'
columns = `stty size`.scan(/\d+/)[1].to_i
colorize = ARGV[0].to_s.match(/^c/i) ? true : false
Snow.run(columns, colorize)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment