pytron-web/pytron_run/run.py

90 lines
2.4 KiB
Python
Raw Normal View History

2019-03-19 16:44:34 +01:00
#!/usr/bin/env python3
import sys
2019-03-19 17:00:43 +01:00
import json
import random
random.seed()
2019-03-19 16:44:34 +01:00
sys.path.append('pytron')
from tron.map import Map
2019-03-19 17:00:43 +01:00
from tron.game import Game, PositionPlayer
2019-03-19 16:44:34 +01:00
from tron.player import Direction, ConstantPlayer
from importlib import import_module
import ai_manager
# Find all the AIs
class AiClass:
def __init__(self, name, builder):
self.name = name
self.builder = builder
ais = []
for real_ai in ai_manager.__all__:
ai_name = real_ai.split('/')[-2]
ai_module = import_module('.'.join(real_ai.split('/')[-3:]))
ai_class = getattr(ai_module, "Ai")
ais.append(AiClass(ai_name, ai_class))
# This script shows how to create a game with AI, that will run automatically.
# It is made to be fast and not to be used by humans. It especially doesn't
# display and window and doesn't listen to any keystrokes.
width = 40
height = 40
def run_battle(ai1, ai2):
ai1_victories = 0
ai2_victories = 0
for _ in range(50):
2019-03-19 17:00:43 +01:00
initial_position_one = [random.randint(0, width - 1), random.randint(0, height - 1)]
initial_position_two = [random.randint(0, width - 1), random.randint(0, height - 1)]
2019-03-19 16:44:34 +01:00
game = Game(width, height, [
PositionPlayer(1, ai1.builder(), initial_position_one),
PositionPlayer(2, ai2.builder(), initial_position_two),
])
game.main_loop()
2019-03-19 17:00:43 +01:00
if game.winner == 1:
2019-03-19 16:44:34 +01:00
ai1_victories += 1
2019-03-19 17:00:43 +01:00
elif game.winner == 2:
2019-03-19 16:44:34 +01:00
ai2_victories += 1
# Inverse positions and replay to be symmetrical
game = Game(width, height, [
PositionPlayer(1, ai1.builder(), initial_position_two),
PositionPlayer(2, ai2.builder(), initial_position_one),
])
game.main_loop()
2019-03-19 17:00:43 +01:00
if game.winner == 1:
2019-03-19 16:44:34 +01:00
ai2_victories += 1
2019-03-19 17:00:43 +01:00
elif game.winner == 2:
2019-03-19 16:44:34 +01:00
ai1_victories += 1
return (ai1_victories, ai2_victories)
def main():
2019-03-19 17:00:43 +01:00
dictionnary = {"ais": list(map(lambda x: x.name, ais)), "battles": {}}
2019-03-19 16:44:34 +01:00
for (id1, ai1) in enumerate(ais):
for (id2, ai2) in enumerate(ais):
if id1 >= id2:
continue
print("Battling {} vs {}".format(ai1.name, ai2.name))
2019-03-19 17:00:43 +01:00
(score1, score2) = run_battle(ai1, ai2)
dictionnary["battles"][ai1.name + "/" + ai2.name] = score1 / (score1 + score2)
with open("assets/data.json", "w") as f:
f.write(json.dumps(dictionnary))
2019-03-19 16:44:34 +01:00
if __name__ == '__main__':
main()