using System; using System.IO; using UnityEngine; using Newtonsoft.Json; using static GameHandler; using static LevelSpawner; using static PlayerScript; using static PlayersHandler; namespace Assets.Scripts { public class DataBearer : SingletonMB { #region PROPERTIES public bool DataSaved { get; private set; } public Attempt CurrentAttempt { get; private set; } public SessionData Session { get { if (_session == null) { _session = GetSettings(); } return _session; } private set { _session = value; } } private SessionData _session = null; public GameState GameState { get; set; } = new(); public Players Players { get { return Session.Players; } } public Rules Rules { get { return Session.Rules; } } #endregion #region VARIABLES private GameHandler _gameHandler; private ScoreHandler _scoreHandler; private PlayersHandler _playerHandler; private LevelSpawner _levelSpawner; #endregion #region EVENTS public void RegisterAttempt_OnAttemptEnded(object sender, AttemptEventArgs eventArgs) { Session.Attempts.Add(CurrentAttempt); CurrentAttempt = null; } // public void RegisterPlayer_OnPlayerInstanciated(object sender, PlayerEventArgs args) { var player = args.player; var newPlayer = new RegisteredPlayer() { Name = player.Name, Id = player.Id, Human = player.IsHuman }; if(!Session.RegisteredPlayers.Exists(rp => rp.Name == newPlayer.Name)) { Session.RegisteredPlayers.Add(newPlayer); } player.OnBonusTouched += RecordBonus_OnBonusTouched; player.OnObstacleTouched += RecordObstacle_OnObstacleTouched; } // public void CreateAttemptRecord_OnAttemptStarted(object sender, AttemptEventArgs args) { CurrentAttempt = args.attempt; foreach(var player in Session.RegisteredPlayers) { PlayerAttempt playerAttempt = new PlayerAttempt() { PlayerName = player.Name }; CurrentAttempt.PlayersAttempts.Add(player.Name, playerAttempt); } } // public void RecordAttemptObstacle_OnPrefabSpawned(object sender, PrefabSpawnedEventArgs args) { LevelPrefab obstacle = new() { PrefabName = args.pattern.name, //todo : prefab name has "(clone)" at the end PrefabNumber = CurrentAttempt.Level.Count + 1, TickTimeWhenTouched = _gameHandler.TickAttemptDuration }; CurrentAttempt.Level.Add(obstacle); } // public void RecordObstacle_OnObstacleTouched(object sender, PrefabTouchedEventArgs args) { var prefab = args.objectTouched; TouchedGameObject touchedGameObject = new() { FullObjectName = prefab.name, //todo : prefab name is laser... It should be full pattern name ObjectTypeName = SortingLayer.IDToName(prefab.layer), // todo : GameSpeed = _gameHandler.MapSpeed, PrefabName = prefab.name, TickTimeWhenTouched = _gameHandler.TickAttemptDuration }; CurrentAttempt.PlayersAttempts[args.playerName].ObstaclesTouched.Add(touchedGameObject); RecordPlayerScore(args.playerId, args.playerName); } // public void RecordBonus_OnBonusTouched(object sender, PrefabTouchedEventArgs args) { var prefab = args.objectTouched; TouchedGameObject touchedGameObject = new() { FullObjectName = prefab.name, ObjectTypeName = SortingLayer.IDToName(prefab.layer), GameSpeed = _gameHandler.MapSpeed, PrefabName = prefab.name, TickTimeWhenTouched = _gameHandler.TickAttemptDuration }; CurrentAttempt.PlayersAttempts[args.playerName].BonusTouched.Add(touchedGameObject); RecordPlayerScore(args.playerId, args.playerName); } // #endregion #region ENDPOINTS public void ResetSession() { _session = null; } public void SaveData() { string directoryPath = Path.Combine(Application.persistentDataPath, "SessionsData"); if (!Directory.Exists(directoryPath))// Crée le répertoire s'il n'existe pas déjà { Directory.CreateDirectory(directoryPath); } var existingFiles = Directory.GetFiles(directoryPath, "*.json"); int sessionNumber = existingFiles.Length + 1; Session.SessionNumber = sessionNumber; string jsonData = JsonConvert.SerializeObject(Session); string fileName = $"Session_{sessionNumber}.json"; string filePath = Path.Combine(directoryPath, fileName); File.WriteAllText(filePath, jsonData); DataSaved = true; Debug.Log($"Session saved to {filePath}"); } public void RecordSessionTime(float time) { Session.SessionTime = time; } public void RecordSessionDate(DateTime date) { Session.Date = date; } /// /// Record all players scores /// public void RecordPlayersScore() { Session.RegisteredPlayers.ForEach(p => { RecordPlayerScore(p.Id, p.Name); }); } /// /// Find and record a player score /// public void RecordPlayerScore(int playerId, string playerName) { int score = (int) _scoreHandler.GetPlayerScore(playerId); var tickTime = _gameHandler.TickAttemptDuration; GenericVector ScoreByTime = new() { X = tickTime, Y = score }; CurrentAttempt.PlayersAttempts[playerName].PlayerScoresOverTicksTime.Add(ScoreByTime); } /// /// Record a player final score /// public void RecordPlayerFinalScore(int score, string playerName) { CurrentAttempt.PlayersAttempts[playerName].FinalScore = score; } /// /// Record the distance parcoured by the player /// public void RecordPlayerDistance(string playerName) { CurrentAttempt.PlayersAttempts[playerName].Distance = (int)_gameHandler.TotalDistance; } public void RecordPlayerAttemptDuration(string playerName) { CurrentAttempt.PlayersAttempts[playerName].AttemptDurationSeconds = _gameHandler.TimeAttemptDuration; CurrentAttempt.PlayersAttempts[playerName].AttemptDurationTicks = _gameHandler.TickAttemptDuration; } #endregion #region METHODS private SessionData GetSettings() { SessionData session = new(); session.Players.Human = bool.Parse(PlayerPrefs.GetString(Settings.HumanPlayerSelected)); session.Players.OmnicientBot = bool.Parse(PlayerPrefs.GetString(Settings.OmnicientBotSelected)); session.Players.ObserverBot = bool.Parse(PlayerPrefs.GetString(Settings.ObserverBotSelected)); session.Players.IteratorBot = bool.Parse(PlayerPrefs.GetString(Settings.IteratorBotSelected)); session.Rules.ChangeSeedEachTry = bool.Parse(PlayerPrefs.GetString(Settings.ChangeSeedSetting)); session.Rules.UsesDefaultSeed = bool.Parse(PlayerPrefs.GetString(Settings.UseDefaultSeedSetting)); session.Rules.Lasers = bool.Parse(PlayerPrefs.GetString(Settings.LaserSettingToggle)); session.Rules.Missiles = bool.Parse(PlayerPrefs.GetString(Settings.MissileSettingToggle)); session.Rules.BonusCoins = bool.Parse(PlayerPrefs.GetString(Settings.CoinSettingToggle)); session.Rules.MalusCoins = bool.Parse(PlayerPrefs.GetString(Settings.BadCoinSettingToggle)); session.Rules.ScoreOnDistance = bool.Parse(PlayerPrefs.GetString(Settings.SurviveScoreSettingToggle)); session.Rules.RushMode = bool.Parse(PlayerPrefs.GetString(Settings.RushModeSettingToggle)); session.Rules.MaxDistance = PlayerPrefs.GetFloat(Settings.MaxDistanceSettingValue); session.Rules.MaxAttempts = PlayerPrefs.GetInt(Settings.MaxTrySettingValue); session.Rules.MaxSessionTime = PlayerPrefs.GetInt(Settings.MaxTimeSettingValue); session.Rules.MaxSpeed = PlayerPrefs.GetFloat(Settings.MaxSpeedSettingValue); session.Rules.StartSpeed = PlayerPrefs.GetFloat(Settings.StartSpeedSettingValue); session.Rules.DifficultyMultiplier = PlayerPrefs.GetFloat(Settings.DifficultyMultiplierSettingValue); return session; } #endregion #region LIFECYCLE protected override void Awake() { DataSaved = false; Session = GetSettings(); base.Awake(); _gameHandler = GameHandler.Instance; _scoreHandler = ScoreHandler.Instance; _playerHandler = PlayersHandler.Instance; _levelSpawner = LevelSpawner.Instance; _gameHandler.OnAttemptEnded += RegisterAttempt_OnAttemptEnded; _gameHandler.OnAttemptStarted += CreateAttemptRecord_OnAttemptStarted; _playerHandler.OnPlayerInstanciated += RegisterPlayer_OnPlayerInstanciated; _levelSpawner.OnPrefabSpawned += RecordAttemptObstacle_OnPrefabSpawned; } #endregion } }