-
Notifications
You must be signed in to change notification settings - Fork 0
/
map_generator.py
59 lines (49 loc) · 1.52 KB
/
map_generator.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
import json
from tkinter.filedialog import *
def generate_map(json_data):
width, height = json_data['mapsize'] # map size set up
karel_world = [[0 for x in range(width)] for y in range(height)] #world created
for data in json_data['diamond']:
x, y, z = data
karel_world[x][y] = z # 2 = diamond
for data in json_data['wall']:
x, y = data
karel_world[x][y] = -1 # 1 = wall
x, y = json_data['karel']
karel_world[x][y] = 'K'
return karel_world
def open_file():
filename = askopenfilename()
if filename:
with open(filename, 'r') as f:
datastore = json.load(f)
return datastore
def map_to_json(world):
n = len(world)
m = len(world[0])
wall = []
karel = ()
diamond = []
for i in range(n):
for j in range(m):
elem = world[i][j]
if elem == 'K':
karel = (i, j)
elif elem == -1:
wall.append((i, j))
elif elem > 0:
diamond.append((i, j, elem))
son = json.dumps(({'wall':wall, 'diamond':diamond, 'mapsize':(n, m), 'karel':karel}), indent=4, sort_keys=True)
f = asksaveasfile(mode='w', defaultextension=".json")
if f is None: # asksaveasfile return `None` if dialog closed with "cancel".
return
f.write(son)
f.close() # `()` was missing.
#print(son)
def print_world(world):
for i in world:
print(*i)
print('\n')
def test():
mapp = generate_map(open_file())
print_world(mapp)