-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathchain_of_responsibility.cr
106 lines (93 loc) · 1.75 KB
/
chain_of_responsibility.cr
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
# The chain of responsibility pattern is a design pattern that defines a
# linked list of handlers, each of which is able to process requests.
# When a request is submitted to the chain, it is passed to the first
# handler in the list that is able to process it.
BATTLE_PLAN = %w(
Scorpion
Mileena
Baraka
Jax
Johnny Cage
Kitana
Liu\ Kang
Reptile
Subzero
Raiden
Kung\ Lao
Shang\ Tsung
Kintaro
Shao\ Khan
).reverse
class NoMoreOpponents < Exception; end
class Fighter
getter name : String
getter successor : Fighter?
def initialize(@name, @successor)
@alive = true
end
def defeat
if @alive
@alive = false
puts "Defeated #{name}"
elsif successor
successor.as(Fighter).defeat
else
raise NoMoreOpponents.new "All opponents defeated!"
end
self
end
end
struct Player
getter name : String
getter opponent : Fighter
def initialize(@name, @opponent)
@victorious = false
end
def fight
puts "Fight!"
opponent.defeat
rescue NoMoreOpponents
puts "#{name} Wins!"
@victorious = true
end
def victorious?
@victorious
end
end
first_opponent = BATTLE_PLAN.reduce(nil) do |next_fighter, this_fighter|
Fighter.new(this_fighter, next_fighter)
end.as(Fighter)
player = Player.new("Subzero", first_opponent)
until player.victorious?
player.fight
end
# Fight!
# Defeated Scorpion
# Fight!
# Defeated Mileena
# Fight!
# Defeated Baraka
# Fight!
# Defeated Jax
# Fight!
# Defeated Johnny Cage
# Fight!
# Defeated Kitana
# Fight!
# Defeated Liu Kang
# Fight!
# Defeated Reptile
# Fight!
# Defeated Subzero
# Fight!
# Defeated Raiden
# Fight!
# Defeated Kung Lao
# Fight!
# Defeated Shang Tsung
# Fight!
# Defeated Kintaro
# Fight!
# Defeated Shao Khan
# Fight!
# Subzero Wins!