Skip to content

Instantly share code, notes, and snippets.

@scarow
Created August 12, 2013 01:24
Show Gist options
  • Save scarow/6207689 to your computer and use it in GitHub Desktop.
Save scarow/6207689 to your computer and use it in GitHub Desktop.
Ruby Racer: COMPLETE Note: Both players will still finish the race; but correct winner will be reported.
require_relative 'racer_utils'
require 'pry'
class RubyRacer
attr_reader :players, :length
def initialize(players, length = 30)
@playerA = players[0]
@playerB = players[1]
@scoreA = 0
@scoreB = 0
@last_index = length -1
end
# Returns +true+ if one of the players has reached
# the finish line, +false+ otherwise
def finished?
@scoreA == @last_index || @scoreB == @last_index
end
# Returns the winner if there is one, +nil+ otherwise
def winner
if @scoreA == @last_index
@playerA
elsif @scoreB == @last_index
@playerB
else nil
end
end
# Rolls the dice and advances +p
#layer+ accordingly
def advance_player!(player)
die = Die.new
#binding.pry
if player == @playerA
if @scoreA <= @last_index
@scoreA += die.roll
@scoreA = @last_index if @scoreA > @last_index
end
elsif player == @playerB
if @scoreB <= @last_index
@scoreB += die.roll
@scoreB = @last_index if @scoreB > @last_index
end
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
@trackA = "_"*30
@trackB = "_"*30
# reput the track and whereever @cur_spot is for each track, insert a/b
@trackA[@scoreA] = @playerA
@trackB[@scoreB] = @playerB
reputs @trackA
reputs @trackB
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
move_to_home!
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