rematch complete

This commit is contained in:
2026-05-04 23:57:56 +05:30
parent 82287d74fb
commit 184d4fbc04
8 changed files with 1489 additions and 1166 deletions
+133 -1
View File
@@ -33,6 +33,109 @@ public class GameManager : NetworkBehaviour
Logger.Log($"Configured dedicated match reporting for match id {matchId} with secret {DedicatedMatchSecret} and internal api base {DedicatedInternalApiBase}");
}
/// <summary>Outcome of <see cref="RequestDedicatedRematch"/> (POST <c>/internal/rematch</c>).</summary>
public readonly struct DedicatedRematchResult
{
public readonly bool Success;
public readonly long HttpStatusCode;
public readonly MatchmadeResponse Response;
public readonly string ErrorMessage;
public DedicatedRematchResult(bool success, long httpStatusCode, MatchmadeResponse response, string errorMessage)
{
Success = success;
HttpStatusCode = httpStatusCode;
Response = response;
ErrorMessage = errorMessage ?? "";
}
}
/// <summary>
/// Dedicated server only: POST <c>/internal/rematch</c> with <c>X-Dedicated-Server-Secret</c>.
/// Blocks until the request finishes (same pattern as <see cref="ReportDedicatedMatchRoomClosed"/>).
/// On HTTP 200, returns the same JSON envelope as a successful matchmaker GET room fill: <see cref="MatchmadeResponse"/>.
/// </summary>
/// <param name="userRedId"><c>users.id</c> for red.</param>
/// <param name="userBlueId"><c>users.id</c> for blue; must differ from red.</param>
/// <param name="entryFee">RC stake per player (non-negative).</param>
/// <param name="secret">Overrides <see cref="DedicatedMatchSecret"/> when non-empty.</param>
/// <param name="internalApiBaseUrl">Overrides <see cref="DedicatedInternalApiBase"/> when non-empty.</param>
public static DedicatedRematchResult RequestDedicatedRematch(int userRedId, int userBlueId, int entryFee, string secret = null, string internalApiBaseUrl = null)
{
string s = string.IsNullOrEmpty(secret) ? DedicatedMatchSecret : secret;
string baseUrl = string.IsNullOrEmpty(internalApiBaseUrl) ? DedicatedInternalApiBase : internalApiBaseUrl.TrimEnd('/');
if (string.IsNullOrEmpty(s))
return new DedicatedRematchResult(false, 0, null, "Missing dedicated server secret");
if (string.IsNullOrEmpty(baseUrl))
return new DedicatedRematchResult(false, 0, null, "Missing internal API base URL");
string json = JsonUtility.ToJson(new DedicatedRematchRequestBody
{
user_red_id = userRedId,
user_blue_id = userBlueId,
entry_fee = entryFee
});
using (var req = DedicatedMatschInternalApi.BuildRematchRequest(baseUrl, s, json))
{
var op = req.SendWebRequest();
while (!op.isDone)
System.Threading.Thread.Sleep(16);
string text = req.downloadHandler != null ? req.downloadHandler.text : "";
long code = req.responseCode;
if (req.result != UnityWebRequest.Result.Success &&
req.result != UnityWebRequest.Result.ProtocolError)
{
string netErr = string.IsNullOrEmpty(req.error) ? "Network error" : req.error;
Logger.Log("Dedicated rematch POST failed (transport): " + netErr + " " + req.url);
return new DedicatedRematchResult(false, code, null, netErr);
}
if (code == 200)
{
try
{
var env = JsonUtility.FromJson<MatchmadeResponse>(text);
if (env != null && env.ok)
return new DedicatedRematchResult(true, code, env, "");
string apiErr = TryParseRematchErrorMessage(text);
Logger.Log("Dedicated rematch POST 200 but ok=false or parse issue: " + text);
return new DedicatedRematchResult(false, code, env, string.IsNullOrEmpty(apiErr) ? "Unexpected response" : apiErr);
}
catch (Exception e)
{
Logger.Log("Dedicated rematch POST: could not parse success body: " + e.Message + " body=" + text);
return new DedicatedRematchResult(false, code, null, e.Message);
}
}
string err = TryParseRematchErrorMessage(text);
if (string.IsNullOrEmpty(err))
err = string.IsNullOrEmpty(text) ? "HTTP " + code : text;
Logger.Log("Dedicated rematch POST failed: " + code + " " + err);
return new DedicatedRematchResult(false, code, null, err);
}
}
static string TryParseRematchErrorMessage(string json)
{
if (string.IsNullOrEmpty(json))
return "";
try
{
var err = JsonUtility.FromJson<DedicatedRematchErrorEnvelope>(json);
if (err != null && !string.IsNullOrEmpty(err.error))
return err.error;
}
catch
{
/* ignore */
}
return "";
}
/// <summary>Sets match <c>status</c> to <c>-1</c> (room closed). Safe to call from shutdown paths; runs synchronously so it completes before <c>Application.Quit</c>.</summary>
public static void ReportDedicatedMatchRoomClosed()
{
@@ -704,7 +807,7 @@ public class GameManager : NetworkBehaviour
}
void StopClient(){
public void StopClient(){
try{
NetworkManager.singleton.StopClient();
}catch(Exception e){
@@ -833,6 +936,20 @@ static class DedicatedMatschInternalApi
return BuildPatchJson(url, secret, jsonBody);
}
public static UnityWebRequest BuildRematchRequest(string baseUrl, string secret, string jsonBody)
{
string url = baseUrl.TrimEnd('/') + "/internal/rematch";
byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonBody);
var req = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST)
{
uploadHandler = new UploadHandlerRaw(bodyRaw),
downloadHandler = new DownloadHandlerBuffer()
};
req.SetRequestHeader("Content-Type", "application/json");
req.SetRequestHeader("X-Dedicated-Server-Secret", secret);
return req;
}
static UnityWebRequest BuildPatchJson(string url, string secret, string jsonBody)
{
byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonBody);
@@ -906,3 +1023,18 @@ class DedicatedWinnerPatchResponse
public int winner_id;
public DedicatedWinnerPatchEconomy economy;
}
[Serializable]
class DedicatedRematchRequestBody
{
public int user_red_id;
public int user_blue_id;
public int entry_fee;
}
[Serializable]
class DedicatedRematchErrorEnvelope
{
public bool ok;
public string error;
}
+30 -3
View File
@@ -33,7 +33,7 @@ public class GameOverCanvas : MonoBehaviour
[Header("Game Over Data")]
public Button btnRematch;
public Button btnLeave;
public GameObject rematchWarningLoser;
public TMP_Text rematchWarningLoser;
public TMP_Text txtRewardRC;
public TMP_Text txtRewardCC;
public TMP_Text countdownTxt;
@@ -79,6 +79,21 @@ public class GameOverCanvas : MonoBehaviour
btnLeave.onClick.AddListener(OnBtnLeaveGameClicked);
betSlider.onValueChanged.AddListener(OnBetSliderValueChanged);
btnConfirmBet.onClick.AddListener(OnBetAccepted);
btnCancelBet.onClick.AddListener(OnBetCancelled);
}
void OnBetAccepted(){
NetPlayer.localPlayer.AcceptRematch((int)betSlider.value);
rematchPanel.interactable=false;
}
void OnBetCancelled(){
NetPlayer.localPlayer.AcceptRematch(0);
rematchPanel.interactable=false;
rematchPanel.blocksRaycasts=false;
rematchPanel.DOFade(0,0.3f).SetEase(Ease.InOutBack);
}
void OnBetSliderValueChanged(float value){
@@ -95,6 +110,8 @@ public class GameOverCanvas : MonoBehaviour
if(winningTeam == myTeam){
//Only i can initiate the rematch, so here we go
ShowRematchPanel();
}else{
rematchWarningLoser.text = "Waiting for opponent to accept";
}
}
@@ -232,7 +249,11 @@ public class GameOverCanvas : MonoBehaviour
}
btnRematch.interactable = winningTeam != myTeam;
rematchWarningLoser.SetActive(winningTeam == myTeam);
if(winningTeam == myTeam){
rematchWarningLoser.text = "Only the loser can request a rematch";
}else{
rematchWarningLoser.text = "";
}
StartCoroutine(CoroutineShow());
@@ -330,8 +351,14 @@ public class GameOverCanvas : MonoBehaviour
public void OnRematchCancelled(){
SetRematchPendingState(false);
btnRematch.interactable=false;
btnLeave.interactable=true;
rematchWarningLoser.text = "Rematch declined.";
StartCoroutine(CoroutineHideRematchPanel());
countdownCoroutine = StartCoroutine(CoroutineCountdown());
}
IEnumerator CoroutineHideRematchPanel(){
+127 -18
View File
@@ -1,9 +1,13 @@
using UnityEngine;
using Mirror;
using UnityEngine.EventSystems;
using System.Collections;
public class NetPlayer : NetworkBehaviour
{
[SyncVar]
public int userId;
[SyncVar]
public Team myTeam;
// set the team to red if there are no other players, if not set blue
@@ -17,16 +21,37 @@ public class NetPlayer : NetworkBehaviour
//Without cupid, set the team to red
bool cloneWorkspace = LoginManager.EditorWorkspaceLooksLikeClone();
SetMyTeam(cloneWorkspace ? Team.Red : Team.Blue);
SetMyData(cloneWorkspace ? 0: 1 );
}else{
SetMyTeam(GameManager.MyTeam);
SetMyData(GameManager.MyTeam == Team.Red ? GameManager.RedPlayer.UserId : GameManager.BluePlayer.UserId);
}
#else
SetMyTeam(GameManager.MyTeam);
SetMyData(GameManager.MyTeam == Team.Red ? GameManager.RedPlayer.UserId : GameManager.BluePlayer.UserId);
#endif
TeamSpecificEffects.instance.SetTeamSpecificEffects(myTeam);
}
void SetMyData(int uid){
if(isServer){
setMyData(uid);
}else{
CmdSetMyData(uid);
setMyData(uid);
}
}
void setMyData(int uid){
userId= uid;
}
[Command]
void CmdSetMyData(int uid){
userId=uid;
}
void SetMyTeam(Team team){
if(isServer){
setMyTeam(team);
@@ -47,10 +72,18 @@ public class NetPlayer : NetworkBehaviour
setMyTeam(team);
Logger.Log($"Client {netId} set team to {team}");
if(team == Team.Red){
RedPlayer = this;
}else{
BluePlayer = this;
}
}
public static NetPlayer localPlayer;
public static NetPlayer RedPlayer;
public static NetPlayer BluePlayer;
public static Vector2 curPosition;
public Vector2 startPosition;
public float curPuckPullForce;
@@ -248,35 +281,111 @@ public class NetPlayer : NetworkBehaviour
}
public void AcceptRematch(float betRc){
public void AcceptRematch( int betRcCoins){
if(isServer){
OnRematchAccepted(betRc);
RpcAcceptRematch(betRc);
OnRematchAcceptedServer(betRcCoins);
}else{
CmdAcceptRematch(betRc);
CmdAcceptRematch(betRcCoins);
}
}
[Command]
void CmdAcceptRematch(float betRc){
OnRematchAccepted(betRc);
RpcAcceptRematch(betRc);
void CmdAcceptRematch(int betRcCoins){
OnRematchAcceptedServer(betRcCoins);
}
[ClientRpc]
void RpcAcceptRematch(float betRc){
OnRematchAccepted(betRc);
}
void OnRematchAcceptedServer(int betRcCoins ){
if(!isServer){ return; }
void OnRematchAccepted(float betRc){
//Implement here
if(betRc == 0){
//Cancel signal
GameOverCanvas.instance.OnRematchCancelled();
if(betRcCoins <= 0){
OnRematchCancelledServer();
return;
}
GameManager.DedicatedRematchResult resp = GameManager.RequestDedicatedRematch(RedPlayer.userId, BluePlayer.userId, betRcCoins);
if(resp.Success && resp.Response != null){
string matchmadeResponseString = JsonUtility.ToJson(resp.Response);
RpcRematchConfirmed(matchmadeResponseString);
Logger.Log("Rematch was confirmed, closing in 5 secs. new room :");
Logger.Log(matchmadeResponseString);
StartCoroutine(CoroutineOnRematchConfirmedServer());
}
}
IEnumerator CoroutineOnRematchConfirmedServer(){
yield return new WaitForSeconds(5f);
Logger.Log("Exiting for rematch.");
GameManager.ReportDedicatedMatchRoomClosed();
Application.Quit();
}
[ClientRpc]
void RpcRematchConfirmed(string matchmadeResponseString){
if (string.IsNullOrEmpty(matchmadeResponseString))
return;
MatchmadeResponse env = JsonUtility.FromJson<MatchmadeResponse>(matchmadeResponseString);
if (env == null || !env.ok)
return;
Team? teamHint = LoginManager.MatchYourTeam;
if (!teamHint.HasValue)
teamHint = GameManager.MyTeam;
int userId = localPlayer != null ? localPlayer.userId : (LoginManager.CurrentUser != null ? LoginManager.CurrentUser.id : 0);
MatchmadeTeamPayload branch = MatchmadeResponse.SelectTeamPayload(env, userId, teamHint);
if (branch == null || !MatchmadeResponse.TryResolveMyAndOpponent(env, branch, userId, out MatchmadePlayer myPlayer, out MatchmadePlayer opponentPlayer))
{
Debug.LogWarning("RpcRematchConfirmed: could not resolve roster for rematch UI");
return;
}
string yt = (branch.your_team ?? "").Trim().ToLowerInvariant();
Team myTeam = yt == "blue" ? Team.Blue : Team.Red;
if (myTeam == Team.Red)
{
GameManager.RedPlayer = myPlayer;
GameManager.BluePlayer = opponentPlayer;
}
else
{
GameManager.BluePlayer = myPlayer;
GameManager.RedPlayer = opponentPlayer;
}
GameManager.MyTeam = myTeam;
int rcPrizeCoins = env.rc_prize > 0 ? env.rc_prize : branch.rc_prize;
GameManager.MatchRcPrizeCoins = rcPrizeCoins;
if (LevelLoadManager.instance != null)
LevelLoadManager.instance.SetupMatchMade(myTeam, myPlayer, opponentPlayer, CoinHelper.FormatString(rcPrizeCoins) + " RC");
GameManager.ConfigureDedicatedMatchReporting(branch.match_id);
Cupid.RoomPort = branch.Port;
LoginManager.SetMatchYourTeam(branch.your_team);
GameManager.instance.StopClient();
LevelLoadManager.LoadLevel("Game");
}
void OnRematchCancelledServer(){
if(!isServer){ return; }
RpcCancelRematch();
if(!isServerOnly){
CancelRematch();
}
}
[ClientRpc]
void RpcCancelRematch(){
CancelRematch();
}
void CancelRematch(){
GameOverCanvas.instance.OnRematchCancelled();
}
}
@@ -85,6 +85,12 @@ public class LevelLoadManager : MonoBehaviour
}
Team myTeam = Team.Red;
public void SetupRematch(int rc_prize, int port, int gameId){
txtRcPrize.text = CoinHelper.FormatString(rc_prize) + " RC";
}
public void SetupMatchMade(Team myTeam_, string opponentName, string myName, string myL10, string opponentL10, string rcPrize){
myTeam = myTeam_;
matchmadeUI.SetActive(true);