-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoo_rps.rb
136 lines (113 loc) · 2.4 KB
/
oo_rps.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
class Move
VALUES = ['rock', 'paper', 'scissors']
def initialize(value)
@value = value
end
def scissors?
@value == 'scissors'
end
def rock?
@value == 'rock'
end
def paper?
@value == 'paper'
end
def >(other_move)
(rock? && other_move.scissors?) ||
(paper? && other_move.rock?) ||
(scissors? && other_move.paper?)
end
def <(other_move)
(rock? && other_move.paper?) ||
(paper? && other_move.scissors?) ||
(scissors? && other_move.rock?)
end
def to_s
@value
end
end
class Player
attr_accessor :move, :name
def initialize
set_name
end
end
class Human < Player
def set_name
n = ''
loop do
puts "What's your name?"
n = gets.chomp
break unless n.empty?
puts "Sorry, must enter a value."
end
self.name = n
end
def choose
choice = nil
loop do
puts "Plase choose rock, paper or scissors:"
choice = gets.chomp
break if Move::VALUES.include? choice
puts "sorry, invalid choice."
end
self.move = Move.new(choice)
end
end
class Computer < Player
def set_name
self.name = ['R2D2', 'Hal', 'Chappie', 'Sonny', 'Number 5'].sample
end
def choose
self.move = Move.new(Move::VALUES.sample)
end
end
class RPSGame
attr_accessor :human, :computer
def initialize
@human = Human.new
@computer = Computer.new
end
def display_welcome_message
puts "Welcome to Rock, Paper, Scissors!"
end
def display_goodbye_message
puts "Thanks for playing Rock, Paper, Scissors. Good bye!"
end
def display_moves
puts "#{human.name} chose #{human.move}"
puts "#{computer.name} chose #{computer.move}"
end
def display_winner
if human.move > computer.move
puts "#{human.name} won!"
elsif human.move < computer.move
puts "#{computer.name} won!"
else
puts "It's a tie!"
end
end
def play_again?
answer = nil
loop do
puts "Would you like to play again? (y/n)"
answer = gets.chomp
break if ['y', 'n'].include? answer.downcase
puts "Sorry, must be y or n."
end
return false if answer.downcase == 'n'
return true if answer.downcase == 'y'
end
def play
display_welcome_message
loop do
human.choose
computer.choose
display_moves
display_winner
break unless play_again?
end
display_goodbye_message
end
end
RPSGame.new.play