Skip to content

Instantly share code, notes, and snippets.

@nextacademy-private
Created August 31, 2014 09:08
Show Gist options
  • Save nextacademy-private/ebb2aa24d8961d42f45d to your computer and use it in GitHub Desktop.
Save nextacademy-private/ebb2aa24d8961d42f45d to your computer and use it in GitHub Desktop.
R-r-r-r-r-ruby Racer!
class Die
def initialize(sides = 6)
@sides = sides
end
# Remember: rand(N) randomly returns one of N consecutive integers, starting at 0
# So rand(N) returns a random integer in (0..N-1)
# And 1 + rand(N) returns a random integer in (1..N)
# See: http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-rand
def roll
1 + rand(@sides)
end
end
# Use "reputs" to print over a previously printed line,
# assuming the cursor is positioned appropriately.
def reputs(str = '')
puts "\e[0K" + str
end
# Clear the screen
def clear_screen!
print "\e[2J"
end
# Moves cursor to the top left of the terminal
def move_to_home!
print "\e[H"
end
# Flushes the STDOUT buffer.
# By default STDOUT is only flushed when it encounters a newline (\n) character
def flush!
$stdout.flush
end
require_relative 'racer_utils'
class RubyRacer
attr_reader :players, :length
def initialize(players, length = 30)
end
# Returns +true+ if one of the players has reached
# the finish line, +false+ otherwise
def finished?
end
# Returns the winner if there is one, +nil+ otherwise
def winner
end
# Rolls the dice and advances +player+ accordingly
def advance_player!(player)
end
# Prints the current game board
# The board should have the same dimensions each time
# and you should use the "reputs" helper to print over
# the previous board
def print_board
end
end
players = ['a', 'b']
game = RubyRacer.new(players)
# This clears the screen, so the fun can begin
clear_screen!
until game.finished?
players.each do |player|
# This moves the cursor back to the upper-left of the screen
move_to_home!
# We print the board first so we see the initial, starting board
game.print_board
game.advance_player!(player)
# We need to sleep a little, otherwise the game will blow right past us.
# See http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-sleep
sleep(0.5)
end
end
# The game is over, so we need to print the "winning" board
game.print_board
puts "Player '#{game.winner}' has won!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment