Skip to content

Instantly share code, notes, and snippets.

@scottmascio2115
Last active December 20, 2015 22:48
Show Gist options
  • Save scottmascio2115/6207749 to your computer and use it in GitHub Desktop.
Save scottmascio2115/6207749 to your computer and use it in GitHub Desktop.
Ruby Racer 2
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.rb'
class RubyRacer
attr_reader :players, :length
def initialize(players, length = 30)
@players = players
@length = length
@apos = 0
@bpos = 0
@player_one= players[0].chr
@player_two= players[1].chr
@aWinner = false
@bWinner = false
@counter = 0
end
def finished?
if @apos > @length || @bpos > @length
true
end
end
def winner
if @apos >= @length
@player_one
elseif @pos >= @length
@player_two
else
nil
end
end
def advance_player!(player)
move_to_home!
if @counter == 0
@apos += Die.new.roll
reputs( " | " * (@apos-1) + player + " | " * (@length - @apos))
@counter += 1
elsif @counter == 1
puts
@bpos += Die.new.roll
reputs( " | " * (@bpos-1) + player + " | " * (@length - @bpos))
@counter = 0
end
end
def print_board
move_to_home!
reputs("#{@player_one}" + " | " * @length)
reputs("#{@player_two}" + " | " * @length)
sleep(1)
end
end
players = ['a', 'b']
game = RubyRacer.new(players)
clear_screen!
game.print_board
sleep(1)
until game.finished?
players.each do |player|
game.advance_player!(player)
break if @aWinner == true
break if @bWinner == true
sleep(0.25)
end
end
puts "Player '#{game.winner}' has won!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment