-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevtools.py
More file actions
431 lines (348 loc) · 14.1 KB
/
Copy pathdevtools.py
File metadata and controls
431 lines (348 loc) · 14.1 KB
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
from index import GOAL_INDEX
import os
import argparse
import re
import json
from datetime import datetime
def createGoalFunctions():
path = './template/data/lockout/function/goals'
# This is used to automatically generate all the functions that are called when a goal is achieved.
print('[devtools] Creating goal functions...')
try:
os.mkdir(path)
except FileExistsError:
print('[devtools] Directory already exists. Proceeding...')
pass
for goal in GOAL_INDEX:
file = open(f'{path}/{goal.lower()}.mcfunction', 'w')
number = goal[1:]
# Write most function for most goals
if 'M' in goal:
file.write("execute as @s run function lockout:goals/template/most {" + f'"goalid": "{goal}", "goalnum": "{ord(goal[0])}{number}", "goalname": "{GOAL_INDEX[goal][0]}"' + '}')
# Write reversed function for Opponent goals
elif 'N' in goal:
file.write("execute as @s run function lockout:goals/template/opponent {" + f'"goalid": "{goal}", "goalnum": "{ord(goal[0])}{number}", "goalname": "{GOAL_INDEX[goal][0]}"' + '}')
else:
# Write goal triggers for all other goals
file.write("execute as @s run function lockout:goals/template/default {" + f'"goalid": "{goal}", "goalnum": "{ord(goal[0])}{number}", "goalname": "{GOAL_INDEX[goal][0]}"' + '}')
file.close()
print('[devtools] Success!')
def createGrantFunctions():
path = './template/data/lockout/function/grant'
print('[devtools] Creating grant functions...')
try:
os.mkdir(path)
except FileExistsError:
print('[devtools] Directory already exists. Proceeding...')
pass
for id, goal in GOAL_INDEX.items():
if id.startswith('N'): continue
if id.startswith('M'): continue
functionname = goal[0].lower().replace(' ', '_')
goalnum = str(ord(id[0])) + id[1:]
goalname = goal[0]
file = open(f'{path}/{functionname}.mcfunction', 'w')
file.write('execute as @s run function lockout:goals/template/default {"goalid": "' + id + '", "goalnum": "' + goalnum + '", "goalname": "' + goalname + '"}')
file.close()
print('[devtools] Success!')
def createRevokeFunctions():
path = './template/data/lockout/function/revoke'
print('[devtools] Creating revoke functions...')
try:
os.mkdir(path)
except FileExistsError:
print('[devtools] Directory already exists. Proceeding...')
pass
for id, goal in GOAL_INDEX.items():
if id.startswith('N'): continue
if id.startswith('M'): continue
functionname = goal[0].lower().replace(' ', '_')
goalnum = str(ord(id[0])) + id[1:]
goalname = goal[0]
file = open(f'{path}/{functionname}.mcfunction', 'w')
file.write('execute as @a run function lockout:goals/template/revoke {"goalid": "' + id + '", "goalnum": "' + goalnum + '", "goalname": "' + goalname + '"}')
file.close()
print('[devtools] Success!')
def createGoalListeners():
'''
Attempts to auto-generate as many goal listeners as possible.
'''
try:
os.mkdir('./listeners')
except FileExistsError:
print('Listeners directory already exists. Proceeding...')
pass
for goalId in GOAL_INDEX:
template = '''{
"criteria": {
"<CRITERIA>": {
"trigger": "minecraft:<TRIGGER>",
"conditions": {
"<CONDITION>": {
<CONDITION_VALUE>
}
}
}
},
"requirements": [
[
"<CRITERIA>"
]
],
"rewards": {
"function": "lockout:goals/<GOALID>"
}
}'''
item_template = '''{
"criteria": {
"<CRITERIA>": {
"trigger": "minecraft:<TRIGGER>",
"conditions": {
"<CONDITION>": [
{
<CONDITION_VALUE>
}
]
}
}
},
"requirements": [
[
"<CRITERIA>"
]
],
"rewards": {
"function": "lockout:goals/<GOALID>"
}
}'''
goal = GOAL_INDEX[goalId]
goalType = goalId[0]
if goalType == 'I':
criteria = 'getitem'
item = goal[1]
trigger = 'inventory_changed'
condition = 'items'
if '64' in goal[0]:
condition_value = f'"items": "minecraft:{item}",\n"count": 64'
else:
condition_value = f'"items": "minecraft:{item}"'
file = open(f'listeners/{goalId.lower()}.json', 'w')
item_template = item_template.replace('<CRITERIA>', criteria)
item_template = item_template.replace('<TRIGGER>', trigger)
item_template = item_template.replace('<CONDITION>', condition)
item_template = item_template.replace('<CONDITION_VALUE>', condition_value)
item_template = item_template.replace('<GOALID>', goalId.lower())
file.write(item_template)
file.close()
elif goalType == 'K':
criteria = 'killentity'
entity = goal[0][5:].lower().replace(' ', '_')
trigger = 'player_killed_entity'
condition = 'entity'
condition_value = f'"type": "minecraft:{entity}"'
file = open(f'listeners/{goalId.lower()}.json', 'w')
template = template.replace('<CRITERIA>', criteria)
template = template.replace('<TRIGGER>', trigger)
template = template.replace('<CONDITION>', condition)
template = template.replace('<CONDITION_VALUE>', condition_value)
template = template.replace('<GOALID>', goalId.lower())
file.write(template)
file.close()
elif goalType == 'D':
criteria = 'dieto'
entity = goal[0][7:].lower().replace(' ', '_')
trigger = 'entity_killed_player'
condition = 'entity'
condition_value = f'"type": "minecraft:{entity}"'
file = open(f'listeners/{goalId.lower()}.json', 'w')
template = template.replace('<CRITERIA>', criteria)
template = template.replace('<TRIGGER>', trigger)
template = template.replace('<CONDITION>', condition)
template = template.replace('<CONDITION_VALUE>', condition_value)
template = template.replace('<GOALID>', goalId.lower())
file.write(template)
file.close()
elif goalType == 'E':
criteria = 'eat'
food = goal[0][4:].lower().replace(' ', '_')
trigger = 'consume_item'
condition = 'item'
condition_value = f'"items": "minecraft:{food}"'
file = open(f'listeners/{goalId.lower()}.json', 'w')
template = template.replace('<CRITERIA>', criteria)
template = template.replace('<TRIGGER>', trigger)
template = template.replace('<CONDITION>', condition)
template = template.replace('<CONDITION_VALUE>', condition_value)
template = template.replace('<GOALID>', goalId.lower())
file.write(template)
file.close()
elif goalType == 'X' and goalId[1] == '1':
criteria = 'effect'
effect = goal[0][4:].lower().replace(' ', '_')
trigger = 'effects_changed'
condition = 'effects'
condition_value = f'"minecraft:{effect}": ' + '{}'
file = open(f'listeners/{goalId.lower()}.json', 'w')
template = template.replace('<CRITERIA>', criteria)
template = template.replace('<TRIGGER>', trigger)
template = template.replace('<CONDITION>', condition)
template = template.replace('<CONDITION_VALUE>', condition_value)
template = template.replace('<GOALID>', goalId.lower())
file.write(template)
file.close()
def createGoalIdStrings(letter, length):
'''
Prints goal id numbers.
'''
for i in range(length):
zeros = 4 - len(str(i+1))
print(letter + ("0" * zeros) + str(i+1))
def createTextureTestFile():
path = './template/data/lockout/function/settings'
print('[devtools] Creating texture test file...')
with open(f'{path}/test_textures.mcfunction', 'w') as file:
for key, goal in GOAL_INDEX.items():
file.write("give @s minecraft:" + goal[1] + "[custom_model_data={'strings':['" + key + "']}]\n")
file.close()
print('[devtools] Success!')
def filterGoalsForGoalPool():
goals = []
for id, goal in GOAL_INDEX.items():
while True:
is_to_add = input(f'Add goal {id} ({goal[0]}) to the pool? [y/n]')
if is_to_add.lower() == 'y':
goals.append(id)
break
elif is_to_add.lower() == 'n' or is_to_add == '':
break
else:
print('Invalid response')
for g in goals:
print(f'"{g}",')
def parseLogFile(file):
log = open(file, '+r')
mode = 'scanning'
goals = []
start_time = datetime(year=1, month=1, day=1)
end_type = None
players = {}
for line in log:
if mode == 'scanning':
start = re.match(r'\[(.*)\] \[.*Running function lockout.*', line)
if start:
start_time = datetime.strptime(start.groups()[0], '%H:%M:%S')
print('Located Start Command at time', start_time)
mode = 'game'
elif mode == 'game':
goal = re.match(r'\[(.*)\] \[.*\[(.*)\] completed \"(.*)\".*', line)
failed_goal = re.match(r'\[(.*)\] \[.*\[(.*)\] failed \"(.*)\".*', line)
if goal:
time, player, goal = goal.groups()
timecode = datetime.strptime(time, '%H:%M:%S')
timestamp = timecode - start_time
goals.append({
"time": time,
"timestamp": f"{int(timestamp.total_seconds() // 60)}:{int(timestamp.total_seconds() % 60)}",
"player": player,
"goal": goal,
"failed": False,
"log_line": line,
})
if failed_goal:
time, player, goal = failed_goal.groups()
timecode = datetime.strptime(time, '%H:%M:%S')
timestamp = timecode - start_time
goals.append({
"time": time,
"timestamp": f"{int(timestamp.total_seconds() // 60)}:{int(timestamp.total_seconds() % 60)}",
"player": player,
"goal": goal,
"failed": True,
"log_line": line,
})
# end_type = re.match(".*Game Over - (.*)$", line)
end = re.match(".*wins!.*", line)
if end:
mode = 'end'
print(f'Game Over')
elif mode == 'end':
pass
# max_time =
# duration =
# team1score =
# team2score =
# goals, failed, deaths, kills =
game_data = {
"start_time": start_time.strftime('%H:%M:%S'),
"goals": goals,
# "end_type": end_type,
# "players": players,
}
print(json.dumps(game_data, indent=4))
return game_data
def createCraftFiles():
item_ids = []
path = './template/data/lockout/advancement/unique_crafts'
print('[devtools] Creating recipe advancements...')
for recipe in open('./recipies.txt', 'r').readlines():
item_ids.append((recipe.strip(' '))[:-6])
try:
os.mkdir(path)
except FileExistsError:
print('[devtools] Directory already exists. Proceeding...')
pass
for item in item_ids:
with open(f'{path}/{item}.json', 'w') as file:
advancement = str('{"criteria": {"craft": {"trigger": "minecraft:recipe_crafted","conditions": {"recipe_id": "' + f'minecraft:{item}"' + '}}},"requirements": [["craft"]],"rewards": {"function": "lockout:goals/count/crafts"}}')
file.write(advancement)
file.close()
print('[devtools] Success!')
def convertToTriggers(file):
with open(file, 'r') as f:
advancement = json.load(f)
if 'display' in advancement:
advancement.pop('display')
if 'parent' in advancement:
advancement.pop('parent')
advancement['rewards'] = {"function": "lockout:goals/count/advancements"}
with open(file, 'w') as f:
json.dump(advancement, f, indent=4)
def main():
parser = argparse.ArgumentParser(description='Run tools for generating data pack files')
parser.add_argument('function', nargs='?', default=None, help='Run a specific development function. Options: goal, craft, texturetest, revoke, grant')
parser.add_argument('--bootstrap', action='store_true', help='Run all functions to prepare the data pack template')
parser.add_argument('--parse', help='Parse lockout log file')
parser.add_argument('--ctt', nargs='*', help='Convert Minecraft advancement files into triggers for lockout goals.')
args = parser.parse_args()
if args.function:
match args.function:
case 'goal':
createGoalFunctions()
case 'craft':
createCraftFiles()
case 'texturetest':
createTextureTestFile()
case 'revoke':
createRevokeFunctions()
case 'grant':
createGrantFunctions()
case _:
print('[devtools] You must specify a valid function. Options: goal, craft, texturetest, revoke, grant')
if args.bootstrap:
print('[devtools] Bootstrapping data pack template...')
createGoalFunctions()
createCraftFiles()
createTextureTestFile()
createRevokeFunctions()
createGrantFunctions()
print('Done!')
elif args.ctt:
print('[devtools] Converting files...')
for file in args.ctt:
convertToTriggers(file)
print('Done!')
elif args.parse:
print('[devtools] Parsing log...')
parseLogFile(args.parse)
if __name__ == '__main__':
main()