-
Notifications
You must be signed in to change notification settings - Fork 12
/
template.cr
77 lines (61 loc) · 1.29 KB
/
template.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
# Defines and invariant part of the algorithm in a base class
# and encapsulates the variable parts in methods that are
# defined by a number of subclasses.
abstract class Fighter
abstract def damage_rate
abstract def attack_message
setter health
getter health, name
def initialize(@name : String)
@damage_rate = damage_rate.as(Int32)
@attack_message = attack_message.as(String)
@health = 100
end
def attack(fighter)
fighter.damage(@damage_rate)
puts "#{@name} attacks #{fighter.name} saying '#{@attack_message}'"
puts "#{fighter.name} is dead." if fighter.dead?
end
def dead?
@health <= 0
end
def damage(rate)
if @health > rate
@health -= rate
else
@health = 0
end
end
end
class Scorpion < Fighter
def initialize
super("Scorpion")
end
def damage_rate
30
end
def attack_message
"Vengeance will be mine."
end
end
class Noob < Fighter
def initialize
super("Noob")
end
def damage_rate
50
end
def attack_message
"Fear me!"
end
end
# Sample
scor = Scorpion.new
noob = Noob.new
noob.attack scor
# Noob attacks Scorpion saying 'Fear me!'
scor.attack noob
# Scorpion attacks Noob saying 'Vengeance will be mine.'
noob.attack scor
# Noob attacks Scorpion saying 'Fear me!'
# Scorpion is dead.