Last active
August 29, 2015 14:26
-
-
Save JoshCheek/b6a23c8526b721315ee4 to your computer and use it in GitHub Desktop.
A visualizer for the game of life
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ===== Game of Life visualizer ===== | |
# You need to fill out these three methods | |
# and it will visualize your game | |
# input: an array of xy pairs, an xy pair is an array of 2 integers for a living cell | |
# output: whatever object you made to implement the game of life | |
def init(xy_pairs) | |
cells = Array.new(200) do |y| | |
Array.new(200) { |x| xy_pairs.include? [x, y] } | |
end | |
GameOfLife.new cells | |
end | |
# input: whatever comes back from init/tomorrow | |
# output: a string representation of your world (this will be displayed) | |
def show(game_of_life, width, height) | |
game_of_life.to_s(width, height) | |
# mine didn't initially have the ability to handle such things, so I edited the bounds of the string with: | |
# game_of_life.to_s.lines.take(height).map { |line| line[0...width].chomp }.join("\n") | |
end | |
# input: whatever came back from init | |
# output: an object for your game in tomorrow's state | |
def tomorrow(game_of_life) | |
game_of_life.tomorrow | |
end | |
# ----- | |
# x, y coordinate pairs for the gosper's glider gun | |
game = init [ | |
# left_square | |
[ 1, 5], [ 2, 5], [ 1, 6], [ 2, 6], | |
# half_circle | |
[14, 3], [13, 3], [12, 4], [11, 5], [11, 6], [11, 7], [12, 8], [13, 9], [14, 9], | |
# arrow | |
[16, 4], [17, 5], [15, 6], [17, 6], [18, 6], [17, 7], [16, 8], | |
# frog | |
[25, 1], [25, 2], [23, 2], [21, 3], [22, 3], [21, 4], [22, 4], [21, 5], [22, 5], [23, 6], [25, 6], [25, 7], | |
# right_square | |
[35, 3], [36, 3], [35, 4], [36, 4], | |
] | |
require 'io/console' | |
clear = "\e[H\e[2J" | |
hide_cursor = "\e[?25l" | |
show_cursor = "\e[?25h" | |
begin | |
print hide_cursor | |
loop do | |
height, width = $stdin.winsize | |
to_display = show(game, width, height) | |
print "#{clear}#{to_display.gsub(/.$/, '|')}" | |
print to_display.lines.first.gsub(/./, '-') | |
game = tomorrow(game) | |
sleep 0.05 | |
end | |
ensure | |
print show_cursor | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment