forked from tailhook/battleship
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.nim
86 lines (76 loc) · 2.14 KB
/
lib.nim
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
type Cell* = enum
cEmpty, cShip, cDead
type
Matrix*[W, H: static[int]] =
array[1..W, array[1..H, Cell]]
proc getHSize(field: Matrix, i,j: int): int =
result = 0
for k in j..10:
if field[i][k] == cShip:
result += 1
else:
break
for k in countdown(j - 1, 1, 1):
if field[i][k] == cShip:
result += 1
else:
break
proc getVSize(field: Matrix, i,j: int): int =
result = 0
for k in i..10:
if field[k][j] == cShip:
result += 1
else:
break
for k in countdown(i - 1, 1, 1):
if field[k][j] == cShip:
result += 1
else:
break
proc validateField*(field: Matrix): bool =
result = false
var oneCells = 4
var twoCells = 6
var threeCells = 6
var fourCells = 4
for i in 1..10:
for j in 1..10:
if field[i][j] == cEmpty:
continue
#check diagonals
if i > 1 and j > 1 and field[i - 1][j - 1] != cEmpty:
return
if i < 10 and j < 10 and field[i + 1][j + 1] != cEmpty:
return
if i > 1 and j < 10 and field[i - 1][j + 1] != cEmpty:
return
if i < 10 and j > 1 and field[i + 1][j - 1] != cEmpty:
return
var size = max(getHSize(field, i, j), getVSize(field, i, j))
if size > 4:
return
if size == 4:
if fourCells == 0:
result = false
return
fourCells -= 1
if size == 3:
if threeCells == 0:
return
threeCells -= 1
if size == 2:
if twoCells == 0:
return
twoCells -= 1
if size == 1:
if oneCells == 0:
return
oneCells -= 1
result = true
proc isFilled*(field: Matrix): bool =
var sum = 0
for i in 1..10:
for j in 1..10:
if field[i][j] == cShip:
sum += 1
result = sum == 20