Anonymous user
Rock-paper-scissors: Difference between revisions
→{{header|Ruby}}: constant CHOICES,BEATS, add quit choice, output draw and chosen
(add special trampoline usage information to Clojure example) |
(→{{header|Ruby}}: constant CHOICES,BEATS, add quit choice, output draw and chosen) |
||
Line 3,603:
=={{header|Ruby}}==
<lang ruby>class RockPaperScissorsGame
def initialize()
▲ @pieces = %w[rock paper scissors]
▲ @beats = {
▲ 'rock' => 'paper',
▲ 'paper' => 'scissors',
▲ 'scissors' => 'rock',
▲ }
@plays = {
'rock' => 1,
'paper' => 1,
'scissors' => 1,
}
@score = [0, 0, 0] # [0]:Human wins, [1]:Computer wins, [2]:draw
play
end
def humanPlay
loop do
print "\nYour choice: #
answer = STDIN.gets.strip.downcase
next if answer.empty?
return
puts "invalid
else▼
▲ end
end
end
def computerPlay
total = @plays.values.reduce(:+)
r = rand(total) + 1
sum = 0
sum += @plays[choice]
if r <= sum▼
break▼
end
end
def play
loop do
h = humanPlay
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"
elsif h == BEATS[c]
puts "Human wins"
@score[0] += 1
Line 3,669 ⟶ 3,662:
@score[1] += 1
end
puts "score: human=
end
@plays.each_key{|k| @plays[k] -= 1}
puts "\nhumans chose #{@plays}"
end
end
sample game where human always chooses rock:
<pre style="height: 40ex; overflow: scroll">
Your choice: ["rock", "paper", "scissors", "quit"]? r▼
H: rock, C: rock => draw
score: human=0, computer=0, draw=1
Your choice: ["rock", "paper", "scissors", "quit"]? r
H: rock, C:
score: human=
▲Your choice: ["rock", "paper", "scissors"]? r
Your choice: ["rock", "paper", "scissors", "quit"]? r
H: rock, C: paper => Computer wins
score: human=
Your choice: ["rock", "paper", "scissors", "quit"]? r
H: rock, C: paper => Computer wins
score: human=
Your choice: ["rock", "paper", "scissors", "quit"]? r
H: rock, C: paper => Computer wins
score: human=
Your choice: ["rock", "paper", "scissors", "quit"]? r
H: rock, C: paper => Computer wins
score: human=
Your choice: ["rock", "paper", "scissors", "quit"]? r
H: rock, C: paper => Computer wins
score: human=
Your choice: ["rock", "paper", "scissors", "quit"]? r
H: rock, C: paper => Computer wins
score: human=
Your choice: ["rock", "paper", "scissors", "quit"]? r
H: rock, C:
score: human=
Your choice: ["rock", "paper", "scissors", "quit"]? r
H: rock, C: paper => Computer wins
score: human=
Your choice: ["rock", "paper", "scissors", "quit"]?
humans chose {"rock"=>10, "paper"=>0, "scissors"=>0}
</pre>
=={{header|Run BASIC}}==
|