Snaparazzi/Assets/Scripts/GameManager.cs

452 lines
12 KiB
C#
Raw Normal View History

2024-01-27 15:25:53 +00:00
using System;
2024-01-27 12:19:56 +00:00
using System.Collections.Generic;
2024-01-27 22:50:57 +00:00
using System.Linq;
2024-01-27 15:32:12 +00:00
using Firebase.Database;
using Firebase.Extensions;
2024-01-27 21:26:23 +00:00
using Newtonsoft.Json;
2024-01-28 00:55:35 +00:00
using Newtonsoft.Json.Linq;
2024-01-27 12:46:54 +00:00
using TMPro;
2024-01-27 12:19:56 +00:00
using UnityEngine;
2024-01-27 12:46:54 +00:00
/// <summary>
/// This is the game state manager on the phone side
/// </summary>
2024-01-27 12:19:56 +00:00
public class GameManager : MonoBehaviour
{
2024-01-27 20:07:49 +00:00
private List<Player> players = new();
2024-01-27 19:01:45 +00:00
public Player currentPlayer = null;
2024-01-27 15:25:53 +00:00
[Header("Other component")]
2024-01-27 12:46:54 +00:00
public float explanationTime = 4f;
private float currentExplanationTime = 0;
2024-01-27 18:54:06 +00:00
[Header("Home Connection Component")]
2024-01-27 15:25:53 +00:00
public TMP_InputField roomCodeField;
2024-01-27 12:46:54 +00:00
public TextMeshProUGUI roomError;
2024-01-27 15:25:53 +00:00
public TMP_InputField playerNameField;
2024-01-27 12:46:54 +00:00
public TextMeshProUGUI nameError;
2024-01-27 15:25:53 +00:00
public UnityEngine.UI.Button submitNewPlayer;
[Header("WaitingRoom Component")]
public TextMeshProUGUI listPlayersUI;
public GameObject submitStartGame;
2024-01-27 23:59:12 +00:00
[Header("Explanation Component")]
public TextMeshProUGUI counter;
2024-01-27 15:25:53 +00:00
[Header("Pages")]
public GameObject HomeConnection;
public GameObject WaitingRoom;
public GameObject BeforeStart;
public GameObject TakePicture;
public GameObject VotePicture;
public GameObject WaitingOtherPlayers;
public GameObject EndGame;
2024-01-27 15:32:12 +00:00
private DatabaseReference realtimeDB;
2024-01-27 18:58:02 +00:00
public Room myRoom;
2024-01-27 16:54:37 +00:00
private DatabaseReference myOnlineRoom;
2024-01-27 23:59:12 +00:00
private DateTime endOfExplanationDate = DateTime.MinValue;
2024-01-27 15:32:12 +00:00
private void Awake()
{
FirebaseInitializer.Instance.onFirebaseReady += Initialize;
}
2024-01-27 12:46:54 +00:00
private void Start()
{
currentExplanationTime = explanationTime;
2024-01-27 15:25:53 +00:00
HomeConnection.SetActive(true);
2024-01-28 00:55:35 +00:00
WaitingRoom.SetActive(false);
BeforeStart.SetActive(false);
TakePicture.SetActive(false);
VotePicture.SetActive(false);
WaitingOtherPlayers.SetActive(false);
EndGame.SetActive(false);
2024-01-27 17:18:03 +00:00
submitNewPlayer.interactable = false;
2024-01-27 12:46:54 +00:00
}
2024-01-27 23:21:38 +00:00
2024-01-27 21:26:23 +00:00
private void OnApplicationQuit()
{
2024-01-27 22:50:57 +00:00
myOnlineRoom.Child("players").Child(currentPlayer.id).RemoveValueAsync().ContinueWithOnMainThread(task =>
{
Debug.Log($"delete player {currentPlayer.name}");
2024-01-27 23:21:38 +00:00
if (myOnlineRoom != null)
2024-01-27 23:06:41 +00:00
{
myOnlineRoom.ValueChanged -= OnRoomUpdate;
}
2024-01-27 22:50:57 +00:00
});
2024-01-27 21:26:23 +00:00
}
2024-01-27 12:46:54 +00:00
2024-01-27 23:59:12 +00:00
private void Update()
{
2024-01-28 01:40:12 +00:00
if (myRoom.currentState == (int)GameState.Explanation && endOfExplanationDate != DateTime.MinValue)
2024-01-27 23:59:12 +00:00
{
TimeSpan duration = endOfExplanationDate - DateTime.Now;
counter.text = ((int)duration.TotalSeconds).ToString("D1");
if (duration.TotalMilliseconds <= 0)
{
Debug.Log("It's time to make proposition !");
2024-01-28 00:55:35 +00:00
endOfExplanationDate = DateTime.MinValue;
2024-01-27 23:59:12 +00:00
}
}
}
2024-01-27 12:46:54 +00:00
2024-01-27 15:32:12 +00:00
private void Initialize()
{
FirebaseInitializer.Instance.onFirebaseReady -= Initialize;
realtimeDB = FirebaseDatabase.DefaultInstance.RootReference;
Debug.Log("Realtime DB initialized");
2024-01-27 17:18:03 +00:00
submitNewPlayer.interactable = true;
2024-01-27 15:32:12 +00:00
}
2024-01-27 12:46:54 +00:00
/// <summary>
/// Send your name and game room to the server
/// </summary>
2024-01-27 15:32:12 +00:00
public void PlayerValidateNameAndServerRoom(string _name, string _code)
2024-01-27 12:46:54 +00:00
{
2024-01-27 18:57:11 +00:00
nameError.gameObject.SetActive(false);
roomError.gameObject.SetActive(false);
2024-01-27 20:07:49 +00:00
2024-01-27 16:54:37 +00:00
if (string.IsNullOrEmpty(_name))
{
Debug.LogError("Player name is empty", this);
2024-01-27 18:57:11 +00:00
nameError.text = "You have to put a valid name";
nameError.gameObject.SetActive(true);
2024-01-27 16:54:37 +00:00
return;
}
if (string.IsNullOrEmpty(_code))
{
Debug.LogError("Room code is empty", this);
2024-01-27 18:57:11 +00:00
roomError.text = "You have to put a room code";
roomError.gameObject.SetActive(true);
2024-01-27 16:54:37 +00:00
return;
}
2024-01-27 20:07:49 +00:00
2024-01-27 17:50:04 +00:00
currentPlayer = new Player(_name);
2024-01-27 16:54:37 +00:00
2024-01-27 12:46:54 +00:00
//check if the room exists, if not display an error message
2024-01-27 16:54:37 +00:00
CheckIfRoomExists(_code, room =>
2024-01-27 15:32:12 +00:00
{
2024-01-27 16:54:37 +00:00
if (room == null)
2024-01-27 15:32:12 +00:00
{
2024-01-27 16:54:37 +00:00
Debug.LogError("The room doesn't exists");
roomError.text = "Error: the room doesn't exists";
roomError.gameObject.SetActive(true);
2024-01-27 15:32:12 +00:00
}
2024-01-27 16:54:37 +00:00
else
2024-01-27 15:32:12 +00:00
{
2024-01-27 17:50:04 +00:00
myOnlineRoom = realtimeDB.Child("rooms").Child(_code);
2024-01-27 23:59:12 +00:00
//subscribe to it
myOnlineRoom.ValueChanged += OnRoomUpdate;
2024-01-27 16:54:37 +00:00
//if room exists, join it
JoinRoom(() =>
2024-01-27 15:32:12 +00:00
{
2024-01-27 22:50:57 +00:00
myRoom.currentState = (int)GameState.WaitingForOtherPlayersToJoin;
2024-01-27 17:50:04 +00:00
players.Add(currentPlayer);
WaitingRoom.SetActive(true);
HomeConnection.SetActive(false);
2024-01-27 16:54:37 +00:00
});
2024-01-27 15:32:12 +00:00
}
});
2024-01-27 12:19:56 +00:00
}
2024-01-27 16:54:37 +00:00
private void CheckIfRoomExists(string _roomCode, Action<Room> callback_Room)
{
realtimeDB.Child("rooms").Child(_roomCode).GetValueAsync().ContinueWithOnMainThread(task =>
2024-01-27 15:32:12 +00:00
{
if (task.IsFaulted)
{
Debug.LogException(task.Exception);
}
else if (task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
if (snapshot == null)
{
2024-01-27 16:54:37 +00:00
callback_Room?.Invoke(null);
2024-01-27 15:32:12 +00:00
}
else
{
2024-01-27 16:54:37 +00:00
callback_Room?.Invoke(JsonUtility.FromJson<Room>(snapshot.GetRawJsonValue()));
2024-01-27 15:32:12 +00:00
}
}
});
2024-01-27 15:25:53 +00:00
2024-01-27 16:54:37 +00:00
}
2024-01-27 15:25:53 +00:00
2024-01-27 16:54:37 +00:00
/// <summary>
/// Add this player to the room
/// </summary>
private void JoinRoom(Action callback_OnRoomJoined)
{
string JSON = JsonUtility.ToJson(currentPlayer);
2024-01-27 17:50:04 +00:00
Debug.Log(JSON);
try
2024-01-27 16:54:37 +00:00
{
2024-01-27 17:50:04 +00:00
myOnlineRoom.Child("players").Child(currentPlayer.id).SetRawJsonValueAsync(JSON).ContinueWithOnMainThread(task =>
2024-01-27 16:54:37 +00:00
{
2024-01-27 17:50:04 +00:00
if (task.IsFaulted)
{
Debug.LogException(task.Exception);
}
else
{
Debug.Log($"{currentPlayer.name} has been added to the room", this);
callback_OnRoomJoined?.Invoke();
}
});
}
catch (Exception ex)
{
Debug.LogException(ex);
}
2024-01-27 12:19:56 +00:00
}
2024-01-27 12:46:54 +00:00
/// <summary>
/// Call this only by the first player
/// </summary>
public void StartGame()
2024-01-27 12:19:56 +00:00
{
2024-01-27 20:07:49 +00:00
// send Start Game
2024-01-28 01:40:12 +00:00
myRoom.SetPlayersAreReady(1);
2024-01-27 21:26:23 +00:00
string JSON = JsonUtility.ToJson(myRoom);
Debug.Log(JSON);
try
{
2024-01-28 01:40:12 +00:00
SendCurrentState(GameState.Explanation, () =>
2024-01-27 21:26:23 +00:00
{
2024-01-27 22:50:57 +00:00
Debug.Log($"start the game", this);
myRoom.currentState = (int)GameState.Explanation;
WaitingRoom.SetActive(false);
BeforeStart.SetActive(true);
2024-01-27 21:26:23 +00:00
});
}
catch (Exception ex)
{
Debug.LogException(ex);
}
2024-01-27 12:19:56 +00:00
}
2024-01-27 12:46:54 +00:00
/// <summary>
/// Dislay on the screen the current prompt ask to you and another player
/// Also show all the camera stuff
/// </summary>
/// <param name="_prompt">The prompt to display</param>
public void MakeAProposition(Prompt _prompt)
{
2024-01-27 22:50:57 +00:00
//currentState = GameState.MakeProposition;
2024-01-27 12:46:54 +00:00
}
/// <summary>
/// Create a proposition from the picture taken and send it to server.
/// Then go to next proposition (if any) or the page "WaitingForOtherPlayers"
/// </summary>
public void SubmitProposition()
{
Proposition temp = new Proposition();
}
/// <summary>
/// Display the voting page
/// </summary>
public void StartToVote()
{
}
/// <summary>
/// Choose one result and send it to the server
/// Then go to the next vote (if any) or to the page "WaitingForOtherPlayers"
/// </summary>
public void Vote()
{
}
/// <summary>
/// Display the UI of the end screen
/// </summary>
public void DisplayEndScreen()
{
}
/// <summary>
/// Automatically called when something change in your room
/// </summary>
2024-01-27 18:57:11 +00:00
private void OnRoomUpdate(object sender, ValueChangedEventArgs e)
2024-01-27 12:46:54 +00:00
{
2024-01-28 00:55:35 +00:00
Debug.Log("begin OnRoomUpdate");
2024-01-27 18:57:11 +00:00
try
{
2024-01-28 00:55:35 +00:00
if (e?.Snapshot?.GetRawJsonValue() != null)
2024-01-27 23:59:12 +00:00
{
2024-01-28 00:55:35 +00:00
string JSON = e.Snapshot.GetRawJsonValue();
2024-01-27 23:59:12 +00:00
myRoom = JsonConvert.DeserializeObject<Room>(e.Snapshot.GetRawJsonValue());
2024-01-28 01:40:12 +00:00
2024-01-27 23:59:12 +00:00
}
2024-01-27 18:57:11 +00:00
}
catch (Exception ex)
{
Debug.LogException(ex);
}
2024-01-27 23:21:38 +00:00
if (myRoom == null)
{
2024-01-28 00:55:35 +00:00
Debug.Log("myroom is null");
2024-01-27 22:50:57 +00:00
return;
}
switch (myRoom.currentState)
2024-01-27 15:25:53 +00:00
{
2024-01-28 01:52:40 +00:00
case (int)GameState.EnteringName:
{
if (EndGame.activeInHierarchy)
{
EndGame.SetActive(false);
HomeConnection.SetActive(true);
}
break;
}
2024-01-27 22:50:57 +00:00
case (int)GameState.WaitingForOtherPlayersToJoin:
2024-01-27 15:25:53 +00:00
{
2024-01-28 11:14:09 +00:00
2024-01-28 02:05:29 +00:00
CheckIfIAmTheFirst(myRoom.GetPlayerList());
UpdateDisplayedListUser(myRoom.GetPlayerList());
2024-01-28 11:14:09 +00:00
2024-01-27 22:50:57 +00:00
break;
}
case (int)GameState.Explanation:
{
2024-01-28 01:52:40 +00:00
if (EndGame.activeInHierarchy)
{
EndGame.SetActive(false);
}
2024-01-27 23:59:12 +00:00
WaitingRoom.SetActive(false);
BeforeStart.SetActive(true);
2024-01-28 02:05:29 +00:00
endOfExplanationDate = DateTime.Now.AddSeconds(4);
2024-01-27 23:59:12 +00:00
2024-01-27 22:50:57 +00:00
break;
}
case (int)GameState.MakeProposition:
{
if (BeforeStart.activeInHierarchy)
{
BeforeStart.SetActive(false);
TakePicture.SetActive(true);
}
2024-01-27 15:25:53 +00:00
break;
}
}
}
2024-01-27 12:46:54 +00:00
2024-01-27 15:25:53 +00:00
2024-01-27 21:26:23 +00:00
private void UpdateDisplayedListUser(List<Player> players)
2024-01-27 15:25:53 +00:00
{
listPlayersUI.text = string.Empty;
for (int i = 0; i < players.Count; i++)
{
listPlayersUI.text += "\n" + players[i].name;
}
2024-01-27 12:46:54 +00:00
}
2024-01-27 23:06:23 +00:00
2024-01-27 21:26:23 +00:00
private void CheckIfIAmTheFirst(List<Player> players)
{
2024-01-27 22:50:57 +00:00
bool isFirst = false;
2024-01-27 21:26:23 +00:00
if (players.Count > 1)
{
2024-01-28 00:15:05 +00:00
List<Player> sortedList = players.OrderBy(x => x.creationDate).ToList();
2024-01-27 22:50:57 +00:00
2024-01-28 00:15:05 +00:00
if (sortedList[0].id == currentPlayer.id)
2024-01-27 22:50:57 +00:00
{
isFirst = true;
2024-01-27 23:21:38 +00:00
}
2024-01-27 21:26:23 +00:00
}
2024-01-27 22:50:57 +00:00
if (isFirst)
2024-01-27 21:26:23 +00:00
{
2024-01-27 22:50:57 +00:00
submitStartGame.SetActive(true);
2024-01-27 21:26:23 +00:00
}
}
2024-01-28 01:40:12 +00:00
public void SendCurrentState(GameState state, Action callback_oncCurrentStateSent)
2024-01-27 22:50:57 +00:00
{
myOnlineRoom.Child("currentState").SetValueAsync((int)state).ContinueWithOnMainThread(task =>
{
if (task.IsFaulted)
{
Debug.LogException(task.Exception);
}
else
{
callback_oncCurrentStateSent?.Invoke();
}
}); ;
2024-01-27 12:46:54 +00:00
2024-01-27 22:50:57 +00:00
}
2024-01-27 16:56:03 +00:00
public void OnClickSubmitSignIn()
{
string playerName = playerNameField.text;
string roomCode = roomCodeField.text;
PlayerValidateNameAndServerRoom(playerName, roomCode);
}
2024-01-28 01:52:40 +00:00
public void onClickSamePlayers()
{
myRoom.currentState = (int)GameState.Explanation;
myRoom.questions = null;
2024-01-28 11:14:09 +00:00
myRoom.currentQuestionId = string.Empty;
2024-01-28 01:52:40 +00:00
string json = JsonUtility.ToJson(myRoom);
myOnlineRoom.SetRawJsonValueAsync(json).ContinueWithOnMainThread(task =>
{
if (task.IsFaulted)
{
Debug.LogException(task.Exception);
}
});
}
public void onClickNewPlayers()
{
myRoom.currentState = (int)GameState.EnteringName;
2024-01-28 11:14:09 +00:00
myRoom.currentQuestionId = string.Empty;
2024-01-28 01:52:40 +00:00
myRoom.questions = null;
myRoom.players = null;
string json = JsonUtility.ToJson(myRoom);
myOnlineRoom.SetRawJsonValueAsync(json).ContinueWithOnMainThread(task =>
{
if (task.IsFaulted)
{
Debug.LogException(task.Exception);
}
});
}
2024-01-27 12:19:56 +00:00
}
public enum GameState
{
2024-01-27 21:24:50 +00:00
EnteringName = 0,
WaitingForOtherPlayersToJoin = 1,
Explanation = 2,
MakeProposition = 3,
PropositionsSent = 4,
2024-01-27 21:33:42 +00:00
MakeVote = 5,
VoteSent = 6,
2024-01-27 23:06:23 +00:00
Score = 7
2024-01-27 12:19:56 +00:00
}