package player.gamer.statemachine.sadna;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;


/**
 * Run tournament to find the best weights vector out of all of weights vectors from the final learning run. 
 * The tournament go over all of the weights vector of the first player from the final run, choose randomly weights vector for the second player, 
 * let them play 100 games and if one of them is good enough (player won more then 30 games then the other player) - save them.
 * All last learning run vectors are saved under the names: "final run\weights1_1000.txt", "final run\weights1_2000.txt", ..., "final run\weights1_200000.txt"
 * and - "final run\weights2_1000.txt", "final run\weights2_2000.txt", ..., "final run\weights2_200000.txt"
 */
public class Tournament {

	private static Random rand = new Random();
	
	public static void main(String[] args) throws IOException {

		List<String> weights1FileNames = new ArrayList<String>();
		List<String> weights2FileNames = new ArrayList<String>();

		try
		{
			// go over all of the weights vector of the first player
			for (int i = 100000; i <= 200000; i++) {
				
				String player1FileName = "final\\weights1_" + i*100 +".txt";
				TrainingPlayer player1 = new TrainingPlayer(Utils.readWeights(player1FileName));
				
				// go over all of the weights vector of the first player
				int j = (rand.nextInt(200000/1000))*1000;
				String player2FileName = "final\\weights2_" + j +".txt";
				TrainingPlayer player2 = new TrainingPlayer(Utils.readWeights(player2FileName));
				
				// play 100 games and if one of players is good enough - save them.
				Score score = play100Games(player1, player2);
				if (score.won1 - score.won2 > 30) {
					weights1FileNames.add(player1FileName);
				} else if (score.won2 - score.won1 > 30)  {
					weights2FileNames.add(player2FileName);
				}
			}
		} finally {
			// save tournament results
			Utils.writeFile("final\\best_of_weights_1.txt", weights1FileNames.toString());
			Utils.writeFile("final\\best_of_weights_2.txt", weights2FileNames.toString());
		}
	}
	
	/**
	 * Play 100 games
	 * @return The final score of the games
	 */
	private static Score play100Games(TrainingPlayer player1, TrainingPlayer player2) {
		Score score = new Score();

		for (int i = 0; i < 100; i++) {

			player1 = new TrainingPlayer(player1.getWeights(), 5); 
			player2 = new TrainingPlayer(player2.getWeights(), 5); 

			// play one game
			int result = GameTrainer.playGame(player1, player2);
			if (result == 1) {
				score.won1++;
			} else if (result == 2) {
				score.won2++;
			} else {
				score.tie++;
			}
		}
		
		return score;
	}

	public static class Score {
		public int won1 = 0;
		public int won2 = 0;
		public int tie = 0;
	}
}
