Skip to content

Instantly share code, notes, and snippets.

@lordhumunguz
Created March 15, 2013 08:00
Show Gist options
  • Save lordhumunguz/5168204 to your computer and use it in GitHub Desktop.
Save lordhumunguz/5168204 to your computer and use it in GitHub Desktop.
This gist has been created from CodeCred.me
require_relative './racer_utils'
#assume 'racer_utils' works
class RubyRacer
attr_reader :players, :length
def initialize(players, length = 30)
@players = players
@length = length
@die = Die.new
@player_a_location = 0
@player_b_location = 0
end
# Returns +true+ if one of the players has reached
# the finish line, +false+ otherwise
def finished?
if @player_a_location == 29 || @player_b_location == 29
return true
end
end
# Returns the winner if there is one, +nil+ otherwise
def winner
if @player_a_location > @player_b_location
"Player A"
elsif @player_a_location < @player_b_location
"Player B"
else
nil
end
end
# Rolls the dice and advances +player+ accordingly
def advance_player!(player)
if player == 'a'
@player_a_location += @die.roll
else
@player_b_location += @die.roll
end
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
reputs
#board = Array.new(2, Array.new(30, ' '))
# board[0] << " "
# board[1] << " "
# end
@board = []
@board[0] = Array.new(30, ' ')
@board[1] = Array.new(30, ' ')
@board[0][@player_a_location] = 'a'
@board[1][@player_b_location] = 'b'
puts @board[0].join('|')
puts @board[1].join('|')
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