forked from BrainJarOrg/battleships-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
grid.rb
109 lines (90 loc) · 2.1 KB
/
grid.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
class Grid
attr_accessor :hit, :missed, :not_targeted
MIN_X = 0
MAX_X = 7
MIN_Y = 0
MAX_Y = 7
:not_targeted
:hit
:missed
def initialize(json)
@grid = Array.new(8)
(0..7).each { |i|
@grid[i] = Array.new(8)
}
@hit = Array.new
init_table(@hit, json['hit'], :hit)
@missed = Array.new
init_table(@missed, json['missed'], :missed)
@not_targeted = Array.new
(MIN_X..MAX_X).each { |x|
(MIN_Y..MAX_Y).each { |y|
if @grid[x][y].nil?
point = Point.new(x, y, :not_targeted)
@grid[x][y] = point
not_targeted.push(point)
end
}
}
(MIN_X..MAX_X).each { |x|
(MIN_Y..MAX_Y).each { |y|
if Grid.valid_coordinates(x-1, y)
@grid[x][y].left_neighbor = @grid[x-1][y]
end
if Grid.valid_coordinates(x, y+1)
@grid[x][y].top_neighbor = @grid[x][y+1]
end
if Grid.valid_coordinates(x+1, y)
@grid[x][y].right_neighbor = @grid[x+1][y]
end
if Grid.valid_coordinates(x, y-1)
@grid[x][y].bottom_neighbor = @grid[x][y-1]
end
}
}
end
def get(x, y)
@grid[x][y]
end
def available_for_shoot?(x, y)
Grid.valid_coordinates(x, y) && !@grid[x][y].already_targeted?
end
def already_targeted?(x, y)
@grid[x][y].already_targeted?
end
# @param [Integer] x
# @param [Integer] y
def self.valid_coordinates(x, y)
x >= MIN_X && x <= MAX_X && y >= MIN_Y && y <= MAX_Y
end
def to_s
grid = ''
(MIN_X..MAX_X).each { |x|
(MIN_Y..MAX_Y).each { |y|
case @grid[x][y].state
when :not_targeted
grid += ' O'
when :hit
grid += ' X'
when :missed
grid += ' #'
else
end
}
grid += "\n"
}
grid
end
private
# @param [Array] table
# @param [Array] points
def init_table(table, points, state)
points.each do |point|
x = Integer(point[0])
y = Integer(point[1])
point = Point.new(x, y, state)
table.push(point)
@grid[x][y] = point
end
end
end