-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
277 lines (255 loc) · 8.33 KB
/
main.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import argparse
import os
import io
import json
from pathlib import Path
from contextlib import redirect_stderr
from pydoc import describe
from sqlite3 import paramstyle
import numpy as np
from src.logger import Logger
from src.image_gen import ImageGen
from src.gui import *
from src.map_loader import MapLoader
from util.gen_ex_maps import generate_toys
from run_tests import LocalTestRunner
from blokboi import Game
from src.pycolors import Colors
def test(**kwargs):
logger = Logger.log_setup(
"blokboiTest", detail=kwargs["detail"], suppress_datetime=False, console=True
)
logger.info("Running local tests...")
with redirect_stderr(io.StringIO()) as f:
results = LocalTestRunner.run_tests()
logger.info(f"Test results:\n{f.getvalue()}")
if results.wasSuccessful():
logger.info("Python tests ran successfully.")
else:
logger.exception("Python tests failed.")
logger.info("Running a simple test of Blokboi API.")
game_instance = Game()
logger.info("Got map:\n" + str(game_instance))
arr = np.array(game_instance.array())
strfull = ""
for row in range(game_instance.width()):
strrow = ""
for col in range(game_instance.height()):
strrow += f"[{(arr[row, col, 0])},{arr[row, col, 1]}] "
strfull += strrow + "\n"
logger.info("Game array representation:\n" + strfull)
ImageGen.make_image_from_str(game_instance.__repr__(), Path("imagetest.png"))
def generate(**kwargs):
logger = Logger.log_setup(
"blokboiGen", detail=kwargs["detail"], suppress_datetime=False, console=True
)
logger.info("Beginning generating random scenes...")
datapath = Path(kwargs["path"])
files_grabbed = []
[
files_grabbed.extend(Path(datapath).glob(f"*/*.{ext}"))
for ext in MapLoader.filetypes()
]
if files_grabbed != None:
if kwargs["yes"]:
confirmation = "yes"
else:
confirmation = input("Overwrite existing files? [Y/n]: ")
if confirmation not in ["y", "yes", "Yes", "yes", ""]:
print("Exiting.")
exit()
for path in files_grabbed:
os.remove(path)
loader = MapLoader()
count = 0
game_instance = Game()
while count < kwargs["number"]:
try:
game_instance.newGame()
except RuntimeError:
logger.exception()
logger.info(f"Failed to make a playable scene. Asking for input...")
if kwargs["yes"]:
confirmation = "yes"
else:
confirmation = input(
"Failed to make a playable scene. Would you like to continue? [y/N]: "
)
if confirmation in ["yes", "Yes", "y", "Y"]:
logger.info("...Continuing.")
continue
else:
break
else:
loader.save(game_instance)
count += 1
logger.info(f"Finished making {count} scenes.")
def gui(**kwargs):
logger = Logger.log_setup(
"blokboi", detail=kwargs["detail"], suppress_datetime=False, console=True
)
logger.debug("Running game app...")
size = (15, 20)
scale = kwargs["scale"]
loader = MapLoader()
if kwargs["list"]:
print(f"{Colors.underline}Maps available:{Colors.reset}")
[print(name) for name in sorted(loader.list())]
else:
if kwargs["loadn"]:
scene, obj, relation, coords, features, truth = loader.loadn(
kwargs["loadn"]
)
app = App(
game_instance=Game(scene, obj, relation, coords, features),
width=size[1],
height=size[0],
scale=scale,
datapath=Path(kwargs["path"]),
)
elif kwargs["loadm"]:
scene, obj, relation, coords, features, truth = loader.loadm(
kwargs["loadm"]
)
app = App(
game_instance=Game(scene, obj, relation, coords, features),
width=size[1],
height=size[0],
scale=scale,
datapath=Path(kwargs["path"]),
)
elif kwargs["load"]:
scene, obj, relation, coords, features, truth = loader.load(kwargs["load"])
app = App(
game_instance=Game(scene, obj, relation, coords, features),
width=size[1],
height=size[0],
scale=scale,
datapath=Path(kwargs["path"]),
)
else:
app = App(game_instance=Game(), width=size[1], height=size[0], scale=scale)
app.mainloop()
"""
################
ARGUMENT PARSING
################
"""
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Command line control for the Blokboi game API."
)
subparsers = parser.add_subparsers(title="subcommands")
parser_gui = subparsers.add_parser(
"gui", description="The GUI App for blokboi.", help="Run the GUI app."
)
parser_gui.add_argument(
"-S", "--scale", type=int, default=2, help="Set the GUI scaling."
)
gui_loadgroup = parser_gui.add_mutually_exclusive_group()
gui_loadgroup.add_argument(
"-ln",
"--loadn",
nargs="?",
const="demo",
type=str,
metavar="NAME",
help="Load a toy example scene NAME.",
)
gui_loadgroup.add_argument(
"-lm",
"--loadm",
type=int,
metavar="NUM",
help="Load the mechanically-generated scene NUM.",
)
gui_loadgroup.add_argument(
"-l",
"--load",
nargs="?",
const=1,
type=int,
metavar="NUM",
help="Load the demo scene number NUM.",
)
gui_loadgroup.add_argument(
"--list", action="store_true", help="List the named scenes available."
)
parser_gui.add_argument(
"--path",
type=str,
default="data",
help="Path to the data directory (default: data).",
)
parser_gui.add_argument(
"--detail",
default="debug",
choices=["debug", "info", "warning", "error", "critical"],
help="Level of detail to python log (default: info).",
)
parser_gui.set_defaults(func=gui)
parser_test = subparsers.add_parser(
"test", description="Simple test of blokboi.", help="Run a simple test."
)
parser_test.add_argument(
"--detail",
default="debug",
choices=["debug", "info", "warning", "error", "critical"],
help="Level of detail to python log (default: info).",
)
parser_test.set_defaults(func=test)
parser_gen = subparsers.add_parser(
"generate",
description="Generate scene dataset.",
help="Generate scene dataset.",
)
parser_gen.add_argument(
"number",
type=int,
default=5000,
help="The number of scenes to generate. (default: 5000)",
)
parser_gen.add_argument(
"--image_only", action="store_true", help="Only generate images."
)
parser_gen.add_argument(
"--path",
type=str,
default="data",
help="Path to the data directory (default: data).",
)
parser_gen.add_argument(
"--detail",
default="debug",
choices=["debug", "info", "warning", "error", "critical"],
help="Level of detail to python log (default: info).",
)
parser_gen.add_argument(
"--heuristic_limit",
default=100,
type=int,
metavar="NUM",
help="The number of times to try building a playable scene. (default: 100)",
)
parser_gen.add_argument(
"-y", "--yes", action="store_true", help="Yes to all prompts."
)
parser_gen.set_defaults(func=generate)
parser_util = subparsers.add_parser(
"util", description="Utility commands.", help="Utility commands."
)
util_parsers = parser_util.add_subparsers(title="utilities")
parser_toy = util_parsers.add_parser(
"toygen",
description="Generate toy examples scenes.",
help="Generate toy example scenes.",
)
parser_toy.add_argument(
"--path",
type=str,
default="data",
help="Path to the data directory (default: data).",
)
parser_toy.set_defaults(func=generate_toys)
args = parser.parse_args()
args.func(**vars(args))