-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmarching_squares.py
78 lines (64 loc) · 1.66 KB
/
marching_squares.py
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
def create_polygon(data):
p = getStartingPoint(data)
return marchingSquares(data, p)
def getStartingPoint(data):
for j, r in enumerate(data):
for i, a in enumerate(r):
if a > 0:
return (i,j)
def getSquareValue(data, x, y):
val = 0
if data[y-1][x-1] > 0:
val += 1
if data[y-1][x] > 0:
val += 2
if data[y][x-1] > 0:
val += 4
if data[y][x] > 0:
val += 8
return val
def marchingSquares(data, startingPoint):
ret = []
px = startingPoint[0]
py = startingPoint[1]
stepX = 0
stepY = 0
prevX = 0
prevY = 0
closedLoop = False
while not closedLoop:
val = getSquareValue(data, px, py)
if val == 1 or val == 5 or val == 13:
stepX = 0
stepY = -1
elif val == 8 or val == 10 or val == 11:
stepX = 0
stepY = 1
elif val == 4 or val == 12 or val == 14:
stepX = -1
stepY = 0
elif val == 2 or val == 3 or val == 7:
stepX = 1
stepY = 0
elif val == 6:
if prevX == 0 and prevY == -1:
stepX = -1
stepY = 0
else:
stepX = 1
stepY = 0
elif val == 9:
if prevX == 1 and prevY == 0:
stepX = 0
stepY = -1
else:
stepX = 0
stepY = 1
px += stepX
py += stepY
ret.append((px, py))
prevX = stepX
prevY = stepY
if px == startingPoint[0] and py == startingPoint[1]:
closedLoop=True;
return ret