Last active
August 29, 2015 14:24
-
-
Save falonofthetower/c82e5369ba6c9aaa9c7f to your computer and use it in GitHub Desktop.
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
# 1. PRS is a game between two players. Players pick a hand; either "Rock", "Paper", or "Scissors". | |
# 2. One hand is compared against the other and either 1) it is a tie, 2) rock > scissors; 3) scissors > paper; 4) paper > rock. | |
require 'pry' | |
class Player | |
attr_accessor :choice | |
attr_reader :name | |
def initialize(name = nil) | |
if name | |
@name = name | |
else | |
puts "Please enter your name:" | |
@name = gets.chomp | |
end | |
end | |
end | |
class Human < Player | |
def pick_hand | |
begin | |
puts "#{name}, please choose your weapon (p, r, s):" | |
c = gets.chomp.downcase | |
end until Game::CHOICES.keys.include?(c) | |
self.choice = c | |
end | |
end | |
class Computer < Player | |
def pick_hand | |
self.choice = Game::CHOICES.keys.sample | |
end | |
end | |
class Game | |
CHOICES = {'p' => 'Paper', 'r' => 'Rock', 's' => 'Scissors'} | |
attr_reader :human, :computer | |
def initialize | |
welcome | |
@human = Human.new | |
@computer = Computer.new("Hal9000") | |
end | |
def welcome | |
puts "Let's play Paper, Rock, Scissors!" | |
end | |
def display_hand(player) | |
case player.choice | |
when 'p' | |
puts "#{player.name} has Paper." | |
when 'r' | |
puts "#{player.name} has Rock." | |
when 's' | |
puts "#{player.name} has Scissors." | |
end | |
sleep(1) | |
end | |
def display_hands | |
display_hand human | |
display_hand computer | |
end | |
def display_winning_move | |
choices = [human.choice, computer.choice] | |
case choices.sort | |
when ["p", "r"].sort | |
puts "Paper wraps Rock, so..." | |
when ["r", "s"].sort | |
puts "Rock crushes Scissors, so..." | |
when ["s", "p"].sort | |
puts "Scissors cuts Paper, so..." | |
else | |
puts "Each of you has the same weapon, so..." | |
end | |
end | |
def compare_hands | |
if human.choice == computer.choice | |
puts "It's a tie!" | |
elsif (human.choice == 'p' && computer.choice == 'r') || | |
(human.choice == 'r' && computer.choice == 's') || | |
(human.choice == 's' && computer.choice == 'p') | |
puts "#{human.name} wins!" | |
else | |
puts "#{computer.name} wins!" | |
end | |
end | |
def play_again? | |
puts "Would you like to play again? (y/n)" | |
play_again = gets.chomp.downcase | |
if play_again != 'y' | |
false | |
end | |
end | |
def play | |
begin | |
human.pick_hand | |
computer.pick_hand | |
display_hands | |
display_winning_move | |
compare_hands | |
end until play_again? == false | |
end | |
end | |
Game.new.play |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment