[READ-ONLY] Mirror of https://github.com/mrgnw/python-scripts.
2.5 kB
115 lines
1# Flood fill implementation fo the code
2# floodmap1.txt and floodmap2.txt
3
4
5# Preliminary functions for making flood_fill implementation and testing easier
6def map_string(map_list):
7 if map_list == None:
8 return "map_list is None"
9
10 row = ""
11 for i in map_list:
12 for c in i:
13 row += c
14 #row += "\n"
15 return row
16
17
18# Generate a map, default size 20x20
19def map_gen(w=20, h=20):
20 map_row = [''] * w
21 return [map_row] * h
22
23
24def map(filename):
25 rows = []
26 with open(filename) as f:
27 rows = f.readlines()
28 w = len(rows[0])-1
29 h = len(rows)
30
31 return rows
32
33#print map_string(map_gen(12,8))
34
35
36# BASE: char == old_char
37# work: char = new_char
38# BASE: flood_fill (x+1, y+1) / (x-1, y-1) / (x+1, y-1) / (x-1, y+1)
39def flood_fill(map, x = 0, y = 0, old =".", new = "*"):
40 if x < 0 or x > len(map[0])-1:
41 return
42 if y < 0 or y > len(map)-1:
43 return
44
45
46 if not map[y][x] == old:
47 return map# STOP - Base case
48
49 # CHANGE THE STRING AT POSITION
50 if map[y][x] == old:
51 #print map[y]
52 map[y] = map[y][:x] + new + map[y][x+1:]
53 #print map_string(map)
54
55 print map[y][x]
56
57 flood_fill(map, x+1, y, old, new) # right
58 flood_fill(map, x-1, y, old, new) # left
59 flood_fill(map, x, y+1, old, new) # up
60 flood_fill(map, x, y-1, old, new) # down
61
62
63# Locate a char on the map
64def find(map, char = '.'):
65 y = -1
66 x = -1
67 for row in map:
68 y += 1
69 x = row.find(char)
70 if x >= 0:
71 return (x, y)
72
73 return None
74
75#BASE: Rooms are full
76def count_rooms(map, char = '.'):
77 rooms = 0 # I'm considering the hallway a room - Assuming
78
79 while find(map, char) != None:
80 x, y = find(map, char)
81 #x = t[0]
82 #y = t[1]
83
84 flood_fill(map, x, y, char)
85 rooms += 1
86 else :
87 return rooms
88
89world = map('rooms.txt')
90#print map_string(map())
91#print map()
92
93#print map_string(flood_fill(world, 5,5))
94#world = map()
95
96#print map_string(flood_fill(world, 8,1))
97#world = map()
98#
99#print map_string(flood_fill(world, 8,0))
100
101#print type(find(map()))
102#
103print ".\t", count_rooms(world)
104print "2\t", count_rooms(world, '2')
105print ".\t", count_rooms(world), "(world wasn't reset)"
106
107world = map('rooms.txt')
108print ".\t", count_rooms(world)
109
110world = map('rooms.txt')
111print "#\t", count_rooms(world, '#')
112
113world = map('text_map.txt')
114print "Text map:\t", count_rooms(world, '.')
115