sounds and screens with improved matchmaker

This commit is contained in:
2026-04-05 00:08:52 +05:30
parent ef89a7320a
commit 352693c860
38 changed files with 6044 additions and 2270 deletions
+24 -4
View File
@@ -1,3 +1,4 @@
using System;
using System.Collections;
using System.Collections.Generic;
using Mirror;
@@ -10,19 +11,37 @@ public class CupidConnector : MonoBehaviour
{
#if UNITY_SERVER
//Server code
string[] args = System.Environment.GetCommandLineArgs();
string[] args = Environment.GetCommandLineArgs();
int matchId = 0;
string dedicatedSecret = "38516e39d3406225b7c3015a66e5d25c54e9b2024c0755212122bdcea3e3a328";
string internalApiBase = null;
for (int i = 0; i < args.Length; i++)
{
if (args[i].Contains("-port"))
if (args[i].Contains("-port") && i + 1 < args.Length)
{
Cupid.RoomPort = int.Parse(args[i+1]);
Cupid.RoomPort = int.Parse(args[i + 1]);
Logger.SetFileName(Cupid.RoomPort.ToString());
}
}
if (i + 1 < args.Length)
{
if (string.Equals(args[i], "-matchId", StringComparison.OrdinalIgnoreCase)
|| string.Equals(args[i], "-matchid", StringComparison.OrdinalIgnoreCase))
int.TryParse(args[i + 1], out matchId);
else if (string.Equals(args[i], "-dedicatedSecret", StringComparison.OrdinalIgnoreCase))
dedicatedSecret = args[i + 1];
else if (string.Equals(args[i], "-internalApiBase", StringComparison.OrdinalIgnoreCase))
internalApiBase = args[i + 1];
}
}
GameManager.ConfigureDedicatedMatchReporting(matchId);
if(Cupid.RoomPort < 0){
Logger.Log("Invalid port, Did you pass the -port arguement?");
return;
}
if(matchId <=0){
Logger.Log("Invalid match id, Did you pass the -matchId arguement?");
return;
}
transport.Port = (ushort)Cupid.RoomPort;
Logger.Log($"Starting server at port {Cupid.RoomPort}");
NetworkManager.singleton.StartServer();
@@ -47,6 +66,7 @@ public class CupidConnector : MonoBehaviour
}else{
if(NetworkServer.connections.Count <= 0){
Logger.Log("Closing port " + Cupid.RoomPort + " due to no players");
GameManager.ReportDedicatedMatchRoomClosed();
Application.Quit();
}
}
+72 -24
View File
@@ -12,36 +12,66 @@ public static class Cupid
private static int port;
public static int Port => port;
private static string password;
private static string bearerToken;
public static string BearerToken => bearerToken;
private static CupidSettings settings = null;
public static CupidSettings Settings => settings;
public static bool isInitialized => settings!=null;
public static bool isInitialized => settings != null;
public static int RoomPort =-1;
public static int RoomPort = -1;
public static async Task Init(string _serverAddress, int _port, string _password){
serverAddress= _serverAddress;
public static async Task Init(string _serverAddress, int _port, string _bearerToken)
{
serverAddress = _serverAddress;
port = _port;
password = _password;
bearerToken = _bearerToken ?? "";
using (UnityWebRequest www = UnityWebRequest.Get(CupidURI + "/settings?password="+password))
if (string.IsNullOrEmpty(bearerToken))
{
Logger.Log("Cupid: no bearer token; configure auth before matchmaking.");
settings = null;
return;
}
using (UnityWebRequest www = UnityWebRequest.Get(CupidURI + "/settings"))
{
www.SetRequestHeader("Authorization", "Bearer " + bearerToken);
var operation = www.SendWebRequest();
while (!operation.isDone)
{
await Task.Yield();
}
try{
settings = JsonUtility.FromJson<CupidSettings>(www.downloadHandler.text);
if(settings==null){throw new NullReferenceException();}
try
{
if (www.result != UnityWebRequest.Result.Success)
{
Logger.Log("Cupid settings request failed: " + www.error);
Logger.Log(www.downloadHandler != null ? www.downloadHandler.text : "");
settings = null;
return;
}
string body = www.downloadHandler != null ? www.downloadHandler.text : "";
if (string.IsNullOrWhiteSpace(body))
{
settings = null;
return;
}
settings = JsonUtility.FromJson<CupidSettings>(body);
if (settings == null) { throw new NullReferenceException(); }
Logger.Log("Cupid init success");
}catch(Exception e){
}
catch (Exception e)
{
Logger.Log("Error retreiving settings from server " + e.Message);
Logger.Log(www.downloadHandler.text);
Logger.Log(www.downloadHandler != null ? www.downloadHandler.text : "");
settings = null;
}
}
}
@@ -59,13 +89,25 @@ public static class Cupid
}
}
public static CupidRoom? ParseRoom(string data){
CupidRoom? room = null;
try{
room = JsonUtility.FromJson<CupidRoom>(data);
}catch{}
return room;
/// <summary>Matchmaker GET / body: <c>"0"</c> while waiting; otherwise a JSON room object.</summary>
public static CupidRoom? ParseRoom(string data)
{
if (string.IsNullOrWhiteSpace(data))
return null;
string t = data.Trim();
if (t == "0")
return null;
try
{
CupidRoom room = JsonUtility.FromJson<CupidRoom>(t);
if (room.Port <= 0)
return null;
return room;
}
catch
{
return null;
}
}
}
@@ -78,14 +120,20 @@ public class CupidSettings
}
[System.Serializable]
public struct CupidRoom{
public struct CupidRoom
{
public CupidQueueEntry[] Players;
public string GameName;
public int Port;
public uint InitTime;
public long InitTime;
public int match_id;
public string your_team;
}
[System.Serializable]
public struct CupidQueueEntry{
string Name;
uint LastSeen;
public struct CupidQueueEntry
{
public string Name;
public long LastSeen;
public int UserId;
}
+98 -52
View File
@@ -1,22 +1,24 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
public class CupidLobby : MonoBehaviour
{
public const string GAME_NAME = "soccar";
public const bool saveUsername = false;
private static string m_username = "";
[SerializeField]private GameObject MatchmakingUI;
[SerializeField]private string GameScene;
[Header("Server info")]
[Header("Server info (matchmaker port should match server settings.json)")]
[SerializeField]private string serverAddress = "xx.xx.xxx.xx";
[SerializeField]private int cupidPort = 1601;
[SerializeField]private string password = "xyz@123";
[SerializeField]private int cupidPort = 2612;
[Tooltip("Used when LoginManager is absent or has no token (e.g. Cupid sample scene).")]
[SerializeField]private string bearerTokenFallback = "";
public static string Username
{
@@ -47,11 +49,17 @@ public class CupidLobby : MonoBehaviour
void Start()
{
Cupid.Init(serverAddress, cupidPort, password);
string token = !string.IsNullOrEmpty(LoginManager.AuthToken)
? LoginManager.AuthToken
: bearerTokenFallback;
if (LoginManager.instance != null && LoginManager.CurrentUser != null && !string.IsNullOrEmpty(LoginManager.CurrentUser.username))
m_username = LoginManager.CurrentUser.username;
Cupid.Init(serverAddress, cupidPort, token);
}
bool matchmaking = false;
public void Matchmake()
{
LoginManager.ClearMatchYourTeam();
Logger.Log("Starting matchmake as " + Username);
StartCoroutine(matchmake());
}
@@ -59,63 +67,101 @@ public class CupidLobby : MonoBehaviour
IEnumerator matchmake()
{
matchmaking = true;
if (string.IsNullOrEmpty(Cupid.BearerToken))
{
Logger.Log("Matchmake aborted: no bearer token");
matchmaking = false;
RefreshMatchmakingPanel();
yield break;
}
while (matchmaking)
{
RefreshMatchmakingPanel();
WWW req = new WWW(Cupid.CupidURI + "/?password=" + password + "&&username=" + Username + $"&&game_name={GAME_NAME}");
yield return req;
// Debug.Log(req.text);
CupidRoom? room = Cupid.ParseRoom(req.text);
if(room == null){
Logger.Log("No room : " + req.text);
}else{
CupidRoom _room = (CupidRoom)room;
Logger.Log("Got into a room");
Logger.Log(req.text);
Logger.Log("Setting cupid to load game scene");
Cupid.RoomPort = _room.Port;
matchmaking=false;
Logger.Log("Loading game scene");
SceneManager.LoadScene(GameScene);
using (UnityWebRequest req = UnityWebRequest.Get(Cupid.CupidURI + "/"))
{
req.downloadHandler = new DownloadHandlerBuffer();
req.SetRequestHeader("Authorization", "Bearer " + Cupid.BearerToken);
yield return req.SendWebRequest();
string text = req.downloadHandler != null ? req.downloadHandler.text : "";
if (req.result != UnityWebRequest.Result.Success)
{
Logger.Log("Matchmaker poll failed: " + req.error + " body: " + text);
yield return new WaitForSeconds(1);
continue;
}
CupidRoom? room = Cupid.ParseRoom(text);
if (room == null)
{
if (text != null && text.Trim() != "0")
Logger.Log("Still waiting: " + text);
}
else
{
CupidRoom _room = (CupidRoom)room;
Logger.Log("Got into a room");
Logger.Log(text);
MatchmadeResponse matchmadeResponse = JsonUtility.FromJson<MatchmadeResponse>(text);
if(matchmadeResponse.Players.Length < 2){
Debug.Log("Waiting for the other player to show up");
yield return new WaitForSeconds(1);
continue;
}
Team myTeam = matchmadeResponse.your_team == "red" ? Team.Red : Team.Blue;
MatchmadePlayer myPlayer = matchmadeResponse.Players.First(p => p.UserId == LoginManager.CurrentUser.id);
MatchmadePlayer opponentPlayer = matchmadeResponse.Players.First(p => p.UserId != LoginManager.CurrentUser.id);
if(myTeam==Team.Red){
GameManager.RedPlayer = myPlayer;
GameManager.BluePlayer = opponentPlayer;
}else{
GameManager.BluePlayer = myPlayer;
GameManager.RedPlayer = opponentPlayer;
}
LevelLoadManager.instance.SetupMatchMade(myTeam, myPlayer.Name, opponentPlayer.Name, $"L10 {myPlayer.l10_wins} -{myPlayer.l10_losses}", $"L10 {opponentPlayer.l10_wins} -{opponentPlayer.l10_losses}");
GameManager.ConfigureDedicatedMatchReporting(matchmadeResponse.match_id);
Logger.Log("Setting cupid to load game scene");
Cupid.RoomPort = _room.Port;
LoginManager.SetMatchYourTeam(_room.your_team);
matchmaking = false;
Logger.Log("Loading game scene");
LevelLoadManager.LoadLevel(GameScene);
yield break;
}
}
// string[] data = req.text.Split(',');
// if(data.Length ==2){
// Logger.Log(req.text);
// if(data[0] == "1"){
// //Game started
// Logger.Log("Setting cupid room to " + data[1]);
// Cupid.RoomPort = int.Parse(data[1]);
// Logger.Log("Loading scene " + GameScene);
// SceneManager.LoadScene(GameScene);
// matchmaking=false;
// break;
// }else{
// //Game not started gotta continue
// }
// int gamePort = -1;
// try{
// gamePort = int.Parse(data[1]);
// }catch(Exception e){
// Logger.Log("Couldn't parse game port: " + req.text);
// }
// }
yield return new WaitForSeconds(1);
}
}
IEnumerator CancelMatchmake(){
WWW www = new WWW(Cupid.CupidURI + "/cancel?password=" + password + "&&username=" + Username);
yield return www;
if(www.text == "1"){
Logger.Log("Cancelled matchmaking success");
}else{
Logger.Log("Matchmaking cancellation said " + www.text);
IEnumerator CancelMatchmake()
{
if (string.IsNullOrEmpty(Cupid.BearerToken))
{
Logger.Log("Cancel skipped: no bearer token");
yield break;
}
using (UnityWebRequest www = UnityWebRequest.Get(Cupid.CupidURI + "/cancel"))
{
www.downloadHandler = new DownloadHandlerBuffer();
www.SetRequestHeader("Authorization", "Bearer " + Cupid.BearerToken);
yield return www.SendWebRequest();
string text = www.downloadHandler != null ? www.downloadHandler.text : "";
if (www.result != UnityWebRequest.Result.Success)
{
Logger.Log("Cancel request failed: " + www.error + " body: " + text);
yield break;
}
if (text.Trim() == "1")
Logger.Log("Cancelled matchmaking success");
else
Logger.Log("Matchmaking cancellation said " + text);
}
}