-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmapparse.py
121 lines (108 loc) · 2.28 KB
/
mapparse.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import re
import sys
from common.map import Map
from common.tileset import TileSet
from common.direction import *
def ident(scanner, token): return token
def number(scanner, token):
if "." in token:
return float(token)
else:
return int(token)
def lbrace(scanner, token): return "("
def rbrace(scanner, token): return ")"
def string(scanner, token): return token[1:-1]
def ttrue(scanner, token): return True
def tfalse(scanner, token): return False
scanner = re.Scanner([
(r"[+-]?[0-9]+(\.[0-9]*)?", number),
(r"[a-zA-Z_-]+", ident),
(r'"[^"]*"', string),
(r"\(", lbrace),
(r"\)", rbrace),
(r"\#t", ttrue),
(r"\#f", tfalse),
("\s+", None),
])
def parse_map(input):
def next_token():
global i
global token
global tokens
if i >= len(tokens):
token = None
return
token = tokens[i]
i += 1
def parse_tilemap():
width = None
height = None
tiles = None
while True:
if token == "(":
next_token()
if token == "width":
next_token()
width = token
next_token()
next_token()
elif token == "height":
next_token()
height = token
next_token()
next_token()
elif token == "tiles":
next_token()
tiles = []
while token != ")":
tiles.append(token)
next_token()
else:
next_token()
count = 1
while count > 0:
if token == "(":
count += 1
elif token == ")":
count -= 1
next_token()
elif token == ")":
next_token()
break
else:
next_token()
assert len(tiles) == width * height
return (width,height,tiles)
global i
global tokens
global remainder
text = input.read()
tokens, remainder = scanner.scan(text)
i = 0
next_token()
map = None
while True:
if token == "(":
next_token()
if token == "tilemap":
next_token()
(width,height,tiles) = parse_tilemap()
if map == None:
tileset = TileSet(None, 16, 16)
map = Map(width, height, tileset)
map.generate()
dest = map.background
else:
dest = map.blocks
for y in range(height):
for x in range(width):
dest[x][y].type = tiles[y*width+x]
if map.tileset.tiles[dest[x][y].type].rotateable:
dest[x][y].direction = randomDirection()
else:
next_token()
elif token == None:
break
else:
next_token()
return map