pytron-web/pytron_run/run.py

84 lines
2.3 KiB
Python
Raw Normal View History

2019-03-19 16:44:34 +01:00
#!/usr/bin/env python3
import sys
sys.path.append('pytron')
from tron.map import Map
from tron.game import Game, PositionPlayer, Winner
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):
initial_position_one = [0, 0]
initial_position_two = [width - 1, height - 1]
game = Game(width, height, [
PositionPlayer(1, ai1.builder(), initial_position_one),
PositionPlayer(2, ai2.builder(), initial_position_two),
])
game.main_loop()
if game.winner == Winner.PLAYER_ONE:
ai1_victories += 1
elif game.winner == Winner.PLAYER_TWO:
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()
if game.winner == Winner.PLAYER_ONE:
ai2_victories += 1
elif game.winner == Winner.PLAYER_TWO:
ai1_victories += 1
return (ai1_victories, ai2_victories)
def main():
# Prepare the size for the game.
# Those values may be good if you want to play, they might not be so good
# to train your AI. Decreasing them will make the learning faster.
for (id1, ai1) in enumerate(ais):
for (id2, ai2) in enumerate(ais):
if id1 >= id2:
continue
print("Battling {} vs {}".format(ai1.name, ai2.name))
score = run_battle(ai1, ai2)
print(score)
if __name__ == '__main__':
main()