pytron-web/pytron_run/refresh.py

78 lines
2.0 KiB
Python
Raw Normal View History

2019-03-28 10:56:22 +01:00
#!/usr/bin/env python3
import os
import pathlib
import sys
import json
sys.path.append('../pytron')
from tron.map import Map
from tron.game import Game, PositionPlayer
from tron.player import Direction, ConstantPlayer
import ai_manager
from utils import run_battle
ASSETS_PATH = "assets/data.json"
LAST_REFRESH_PATH = "assets/refresh.dat"
width = 10
height = 10
def main():
print('Welcome to pytron refresh!')
sys.stdout.flush()
# Read the last moment when this script was run
last_refresh = os.path.getmtime(LAST_REFRESH_PATH)
# Set last update time
pathlib.Path(LAST_REFRESH_PATH).touch()
# Find the ais that need to be refreshed
ais_to_refresh = [ai for ai in ai_manager.__all__ if ai.date > last_refresh]
print('New ais: ', list(map(lambda x: x.name, ais_to_refresh)))
print('Ais: ', list(map(lambda x: x.name, ai_manager.__all__)))
# Read current state
with open(ASSETS_PATH, 'r') as file:
dictionnary = json.loads(file.read())
# Dictionnary to record battles that already occured
battles_done = {}
for ai1 in ais_to_refresh:
for ai2 in ai_manager.__all__:
if ai1.name == ai2.name:
continue
# Sort ais by name just to be sure
if ai1.name > ai2.name:
(sai2, sai1) = (ai1, ai2)
else:
(sai1, sai2) = (ai1, ai2)
slash_name = sai1.name + "/" + sai2.name
# Record battle to be done, skip if already done
if battles_done.get(slash_name, None) is None:
battles_done[slash_name] = True
else:
continue
print("Battling {} vs {}".format(sai1.name, sai2.name))
sys.stdout.flush()
(score1, score2, nulls) = run_battle(sai1, sai2, width, height)
dictionnary[slash_name] = [score1, score2, nulls]
with open(ASSETS_PATH, "w") as f:
f.write(json.dumps(dictionnary))
print('Pytron run has finished')
if __name__ == '__main__':
main()