Created
November 22, 2011 12:51
-
-
Save dustMason/1385597 to your computer and use it in GitHub Desktop.
ScoreKeeper.rb : A quick command-line app written in Ruby for keeping score during Gin Rummy games. Run `ruby scorekeeper.rb` to start the game.
This file contains hidden or 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
module ScoreKeeper | |
class Player | |
attr_accessor :name, :scores | |
def initialize(name) | |
@name = name | |
@scores = [] | |
end | |
def <<(points) | |
@scores << points | |
end | |
def calculate_score([email protected]) | |
@scores.first(turn_number).to_a.reduce(:+) | |
end | |
end | |
class Game | |
def initialize | |
@players = [] | |
@turn = 0 | |
@printer = Printer.new(25) | |
# ask for players' names | |
loop do | |
print "Player ##{@players.size+1}: " | |
new_player = gets.strip | |
break if new_player == "" | |
@players << Player.new(new_player) | |
end | |
end | |
def print_names | |
@printer.print( @players.collect(&:name),true ) | |
end | |
def print_scores | |
print_names | |
@turn.times do |i| | |
@printer.print( @players.collect{ |p| if p.scores[i] > 0 then "+ "+p.scores[i].to_s else p.scores[i] end }) | |
@printer.print( @players.collect{ |p| p.calculate_score(i+1)},true ) | |
end | |
end | |
def turn | |
# loop through all players, ask score for each one | |
# at the end, print all the scores | |
puts "Turn #{@turn+1}" | |
@players.each do |player| | |
print "#{player.name}: " | |
player << gets.strip.to_i | |
end | |
@turn += 1 | |
print_scores | |
end | |
end | |
class Printer | |
def initialize(columns=20) | |
@columns = columns | |
end | |
def print(values,div=false) | |
out = "| " | |
values.each do |v| | |
out << "%#{@columns}s |" % v | |
end | |
out << "\n" | |
puts out | |
line_break(values.size) if div | |
end | |
def line_break(width) | |
out = "|-" | |
width.times { out << ("-"*@columns) + "-+" } | |
out[-1] = "|" | |
puts out | |
end | |
end | |
end | |
# start the game | |
game = ScoreKeeper::Game.new | |
game.print_names | |
loop { game.turn } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment