RosettaCodeData/Task/Rock-paper-scissors/Ruby/rock-paper-scissors.rb

69 lines
1.5 KiB
Ruby
Raw Permalink Normal View History

2013-04-10 23:57:08 -07:00
class RockPaperScissorsGame
2015-02-20 00:35:01 -05:00
CHOICES = %w[rock paper scissors quit]
BEATS = {
'rock' => 'paper',
'paper' => 'scissors',
'scissors' => 'rock',
}
2013-04-10 23:57:08 -07:00
def initialize()
@plays = {
2015-02-20 00:35:01 -05:00
'rock' => 1,
'paper' => 1,
2013-04-10 23:57:08 -07:00
'scissors' => 1,
}
2015-02-20 00:35:01 -05:00
@score = [0, 0, 0] # [0]:Human wins, [1]:Computer wins, [2]:draw
2013-04-10 23:57:08 -07:00
play
end
2015-02-20 00:35:01 -05:00
def humanPlay
2013-04-10 23:57:08 -07:00
loop do
2015-02-20 00:35:01 -05:00
print "\nYour choice: #{CHOICES}? "
2013-04-10 23:57:08 -07:00
answer = STDIN.gets.strip.downcase
next if answer.empty?
2015-02-20 00:35:01 -05:00
idx = CHOICES.find_index {|choice| choice.match(/^#{answer}/)}
return CHOICES[idx] if idx
puts "invalid answer, try again"
2013-04-10 23:57:08 -07:00
end
end
2015-02-20 00:35:01 -05:00
def computerPlay
2013-04-10 23:57:08 -07:00
total = @plays.values.reduce(:+)
r = rand(total) + 1
sum = 0
2015-02-20 00:35:01 -05:00
CHOICES.each do |choice|
sum += @plays[choice]
return BEATS[choice] if r <= sum
2013-04-10 23:57:08 -07:00
end
end
def play
loop do
h = humanPlay
2015-02-20 00:35:01 -05:00
break if h == "quit"
2013-04-10 23:57:08 -07:00
c = computerPlay
print "H: #{h}, C: #{c} => "
# only update the human player's history after the computer has chosen
@plays[h] += 1
if h == c
puts "draw"
2015-02-20 00:35:01 -05:00
@score[2] += 1
elsif h == BEATS[c]
2013-04-10 23:57:08 -07:00
puts "Human wins"
@score[0] += 1
else
puts "Computer wins"
@score[1] += 1
end
2015-02-20 00:35:01 -05:00
puts "score: human=%d, computer=%d, draw=%d" % [*@score]
2013-04-10 23:57:08 -07:00
end
2015-02-20 00:35:01 -05:00
@plays.each_key{|k| @plays[k] -= 1}
puts "\nhumans chose #{@plays}"
2013-04-10 23:57:08 -07:00
end
end
2015-02-20 00:35:01 -05:00
RockPaperScissorsGame.new