-
Notifications
You must be signed in to change notification settings - Fork 10
/
ship.rb
49 lines (42 loc) · 860 Bytes
/
ship.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
class Ship
attr_reader :length
def initialize(length)
@length = length
@positions = []
@hits = []
end
def place(x, y, across)
return false unless @positions.empty?
if across
(x...x+@length).each do |i|
@positions << [i, y]
end
else
(y...y+@length).each do |j|
@positions << [x, j]
end
end
true
end
def covers?(x, y)
@positions.include?([x, y])
end
def overlaps_with?(other_ship)
@positions.any? {|p| other_ship.covers?(p[0],p[1])}
# @positions.each |place|
# return true if other_ship.covers?(place[0],place[1])
# end
# false
end
def fire_at(x, y)
if covers?(x, y) && !@hits.include?([x, y])
@hits << [x, y]
end
end
def sunk?
@hits.length == @length
end
def hit_on?(x, y)
@hits.include?([x, y])
end
end