Archived
Private
Public Access
1
0
This repository has been archived on 2026-02-04. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
ProjectBackup/Unity/NeuralNetworkTest/Assets/Scripts/EvolutionController.cs
2022-11-12 13:10:03 +01:00

72 lines
2.4 KiB
C#

using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
using Random = UnityEngine.Random;
public class EvolutionController : MonoBehaviour {
public int generationTimeInSeconds;
public int populationSize;
public GameObject agentPrefab;
public Transform target;
public Text informationText;
public Slider timeSlider;
private int _currentGeneration;
private List<Agent> _agents;
private float _startTime;
private float _lastScore;
private void Start() {
_agents = new List<Agent>();
StartGeneration();
}
private void Update() {
if (_agents.Count == 0) return;
if (Time.time - _startTime > generationTimeInSeconds) {
_startTime = Time.time;
StartGeneration();
}
_agents.Sort((agent, agent1) => agent1.Network.CompareTo(agent.Network));
informationText.text = $"Generation: {_currentGeneration}\n" +
$"Time: {(Time.time - _startTime).ToString("F1")}\n" +
$"Population: {_agents.Count}\n" +
$"Time scale: {Time.timeScale}\n" +
$"Score: {_agents[0].Network.GetScore()}\n" +
$"Last score: {_lastScore}";
}
private void StartGeneration() {
for (int i = 0; i < transform.childCount; i++) {
Destroy(transform.GetChild(i).gameObject);
}
NeuralNetwork bestNetwork = null;
if (_currentGeneration > 0) {
_agents.Sort((agent, agent1) => agent1.Network.CompareTo(agent.Network));
bestNetwork = _agents[0].Network;
_lastScore = bestNetwork.GetScore();
}
target.position = new Vector2(Random.Range(-10, 10), Random.Range(-5, 5));
_agents.Clear();
for (int i = 0; i < populationSize; i++) {
GameObject agent = Instantiate(agentPrefab, Vector3.zero, Quaternion.identity);
agent.transform.SetParent(transform);
Agent agentController = agent.AddComponent<Agent>();
agentController.Initialize(target, bestNetwork);
_agents.Add(agentController);
}
_currentGeneration++;
}
public void ChangeTimeMultipler() {
Time.timeScale = timeSlider.value;
}
}