public void LoadNetwork(object sender, EventArgs e) { rootGrid.Children.Clear(); rootGrid.Children.Add(Score); rootGrid.Children.Add(Info); rootGrid.Children.Add(saveNetButton); // Create a string to read into int numWeights = (INPUTS + 1) * HIDDEN + (HIDDEN + 1) * OUTPUTS; string[] lines = new string[numWeights + 1]; //Initialize networks for (int i = 0; i < ann.Length; i++) { ann[i] = new ANN(INPUTS, HIDDEN, OUTPUTS); } //Read file if (System.IO.File.Exists(netPath)) { lines = System.IO.File.ReadAllLines(netPath); } gen = Convert.ToInt32(lines[2]); for (int i = 0; i < ann.Length; i++) { int ii = 3; for (int j = 1; j < 3; j++) { for (int k = 0; k < ann[i].neuronLayers[j].neuronNum; k++) { for (int l = 0; l < ann[i].neuronLayers[j].neurons[k].inputNum + 1; l++) { ann[i].neuronLayers[j].neurons[k].weights[l] = Convert.ToDouble(lines[ii]); ii++; } } } } GA.Mutate(ann); //Start a game game = new Game(rootGrid, random); timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromMilliseconds(SPEED2); timer.Tick += delegate { Update(); game.UpdateDisplay(); UpdateDisplay(); }; timer.Start(); KeyDown += AdjustSpeed; }
void Update() { for (int y = 0; y < WIDTH; y++) { for (int x = 0; x < WIDTH; x++) { prevBoard[x, y] = game.board[x, y]; } } //Check each direction to see if it is a legal move int prevScore = game.score; double[] outputs = new double[4]; for (int i = 0; i < 4; i++) { //Move in a direction game.Update(i, true); //Check if legal bool legal = false; for (int y = 0; y < WIDTH; y++) { for (int x = 0; x < WIDTH; x++) { if (prevBoard[x, y] != game.board[x, y]) { legal = true; break; } } if (legal) { break; } } //If legal, feed to network if (legal) { outputs[i] = ComputeNetwork(ann[c]); } else { outputs[i] = 0; } //Revert game state for next check game.score = prevScore; game.board = prevBoard; } //Update game with highest output int highest = 0; for (int i = 1; i < 4; i++) { if (outputs[i] > outputs[highest]) { highest = i; } } game.Update(highest, false); if (game.end) { ann[c].fitness = game.score; if (game.score > maxFitness) { maxFitness = game.score; } c++; game = null; rootGrid.Children.Clear(); rootGrid.Children.Add(Info); rootGrid.Children.Add(Score); rootGrid.Children.Add(saveNetButton); game = new Game(rootGrid, random); } if (c >= POPULATION) { c = 0; gen++; //Total fitness totalFitness = 0; for (int i = 0; i < POPULATION; i++) { totalFitness += ann[i].fitness; } avgFitness = totalFitness / POPULATION; finalMaxFitness = maxFitness; maxFitness = 0; Console.Write("gen: " + gen.ToString() + ", avg: " + avgFitness + "\n"); if (gen % 100 == 0) { SaveNetwork(); } GA.Compute(ann); } }