-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtile.rb
78 lines (69 loc) · 1.37 KB
/
tile.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
#require_relative 'board.rb'
class Tile
attr_accessor :bombed, :flagged, :revealed, :position, :neighbors
attr_reader :board
DIRECTIONS = [
[1, 0],
[0, 1],
[1, 1],
[-1, 1],
[-1, 0],
[-1, -1],
[0, -1],
[1, -1]
]
def initialize(board, pos)
@board = board
@bombed = false
@flagged = false
@revealed = false
@position = pos
@neighbors = get_neighbors
end
def reveal
self.revealed = true unless flagged
if neighbor_count == "_" && !bombed
neighbors.each do |neighbor|
neighbor_tile = board[*neighbor]
neighbor_tile.reveal unless neighbor_tile.revealed
end
end
end
def flag
self.flagged = !flagged unless revealed
end
def inspect
if flagged
return "⚐"
elsif revealed
return "💣" if bombed
return neighbor_count
else
"*"
end
end
def to_s
inspect.to_s
end
def neighbor_count
count = 0
neighbors.each do |neighbor|
if board[*neighbor].bombed
count += 1
end
end
if count == 0
return "_"
else
return count
end
end
def get_neighbors
neighbors = []
DIRECTIONS.each do |direction|
neighbor = [position[0] + direction[0], position[1] + direction[1]]
neighbors << neighbor if neighbor.all? { |coord| coord.between?(0, 8) }
end
neighbors
end
end