Created
January 30, 2015 00:46
-
-
Save nickserv/66c0316ee15145ea794a to your computer and use it in GitHub Desktop.
Functional car racing game
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
# See https://github.com/paircolumbus/Functional-101/blob/nicks-solution/ex4-remove-state.rb | |
# Constants | |
DEFAULT_ROUNDS = [Array.new(3, 1)] | |
DEFAULT_TIME = 4 | |
NEWLINE = "\n" | |
# Game functions | |
def should_move_position? | |
rand(0..5) > 3 | |
end | |
def move_positions(round) | |
round.map { |position| position + (should_move_position? ? 1 : 0) } | |
end | |
def add_round(rounds) | |
rounds << move_positions(rounds.last) | |
end | |
def functional_game(time = DEFAULT_TIME, rounds = DEFAULT_ROUNDS) | |
time >= 0 ? functional_game(time - 1, add_round(rounds)) : rounds | |
end | |
# String conversion functions | |
def position_to_s(position, index) | |
"#{index} #{'-' * position}" | |
end | |
def round_to_s(round) | |
round.each.with_index.map(&method(:position_to_s)).join(NEWLINE) | |
end | |
def rounds_to_s(rounds) | |
rounds.map(&method(:round_to_s)).join(NEWLINE * 2) | |
end | |
# Main | |
puts rounds_to_s functional_game |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment