Skip to content

Instantly share code, notes, and snippets.

@alanjcfs
Created March 16, 2012 21:33
Show Gist options
  • Save alanjcfs/2052873 to your computer and use it in GitHub Desktop.
Save alanjcfs/2052873 to your computer and use it in GitHub Desktop.
A Small Game
# Rock Paper Scissors is a usual game
class Opponent
def initialize
@rps = ['rock', 'paper', 'scissors']
end
def play
@rps[rand 3]
end
end
class Player
def initialize
@opponent = Opponent.new
@beat = { scissors: 'paper', paper: 'rock', rock: 'scissors' }
@defeat = { scissors: 'rock', paper: 'scissors', rock: 'paper' }
@tie = { scissors: 'scissors', paper: 'paper', rock: 'rock' }
end
def play_game
while true
puts "Rock, Paper or Scissors? (Type exit to quit.)"
print "> "
answer = gets.chomp.downcase
until ['rock', 'paper', 'scissors', 'exit', 'quit'].include? answer
print "I didn't understand that. Try again: "
answer = gets.chomp.downcase
end
@opp_answer = @opponent.play
def tell answer
return "You win!" if @beat[answer.to_sym] == @opp_answer
return "You lose." if @defeat[answer.to_sym] == @opp_answer
return "It's a tie!" if @tie[answer.to_sym] == @opp_answer
end
puts "The computer played #{@opp_answer}. #{self.tell answer}"
end
end
end
Player.new.play_game
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment