// ----------------------------------------------------------------------------
//
// PhotonNetwork Framework for Unity - Copyright (C) 2016 Exit Games GmbH
//
//
// Manager for Turn Based games, using PUN
//
// developer@exitgames.com
// ----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using ExitGames.Client.Photon;
using Photon;
using UnityEngine;
using ExitGames = ExitGames.Client.Photon.Hashtable;
///
/// Pun turnBased Game manager.
/// Provides an Interface (IPunTurnManagerCallbacks) for the typical turn flow and logic, between players
/// Provides Extensions for PhotonPlayer, Room and RoomInfo to feature dedicated api for TurnBased Needs
///
public class PunTurnManager : PunBehaviour
{
///
/// Wraps accessing the "turn" custom properties of a room.
///
/// The turn index
public int Turn
{
get { return PhotonNetwork.room.GetTurn(); }
private set {
_isOverCallProcessed = false;
PhotonNetwork.room.SetTurn(value, true);
}
}
///
/// The duration of the turn in seconds.
///
public float TurnDuration = 20f;
///
/// Gets the elapsed time in the current turn in seconds
///
/// The elapsed time in the turn.
public float ElapsedTimeInTurn
{
get { return ((float)(PhotonNetwork.ServerTimestamp - PhotonNetwork.room.GetTurnStart()))/1000.0f; }
}
///
/// Gets the remaining seconds for the current turn. Ranges from 0 to TurnDuration
///
/// The remaining seconds fo the current turn
public float RemainingSecondsInTurn
{
get { return Mathf.Max(0f,this.TurnDuration - this.ElapsedTimeInTurn); }
}
///
/// Gets a value indicating whether the turn is completed by all.
///
/// true if this turn is completed by all; otherwise, false.
public bool IsCompletedByAll
{
get { return PhotonNetwork.room != null && Turn > 0 && this.finishedPlayers.Count == PhotonNetwork.room.PlayerCount; }
}
///
/// Gets a value indicating whether the current turn is finished by me.
///
/// true if the current turn is finished by me; otherwise, false.
public bool IsFinishedByMe
{
get { return this.finishedPlayers.Contains(PhotonNetwork.player); }
}
///
/// Gets a value indicating whether the current turn is over. That is the ElapsedTimeinTurn is greater or equal to the TurnDuration
///
/// true if the current turn is over; otherwise, false.
public bool IsOver
{
get { return this.RemainingSecondsInTurn <= 0f; }
}
///
/// The turn manager listener. Set this to your own script instance to catch Callbacks
///
public IPunTurnManagerCallbacks TurnManagerListener;
///
/// The finished players.
///
private readonly HashSet finishedPlayers = new HashSet();
///
/// The turn manager event offset event message byte. Used internaly for defining data in Room Custom Properties
///
public const byte TurnManagerEventOffset = 0;
///
/// The Move event message byte. Used internaly for saving data in Room Custom Properties
///
public const byte EvMove = 1 + TurnManagerEventOffset;
///
/// The Final Move event message byte. Used internaly for saving data in Room Custom Properties
///
public const byte EvFinalMove = 2 + TurnManagerEventOffset;
// keep track of message calls
private bool _isOverCallProcessed = false;
#region MonoBehaviour CallBack
///
/// Register for Event Call from PhotonNetwork.
///
void Start()
{
PhotonNetwork.OnEventCall = OnEvent;
}
void Update()
{
if (Turn > 0 && this.IsOver && !_isOverCallProcessed)
{
_isOverCallProcessed = true;
this.TurnManagerListener.OnTurnTimeEnds(this.Turn);
}
}
#endregion
///
/// Tells the TurnManager to begins a new turn.
///
public void BeginTurn()
{
Turn = this.Turn + 1; // note: this will set a property in the room, which is available to the other players.
}
///
/// Call to send an action. Optionally finish the turn, too.
/// The move object can be anything. Try to optimize though and only send the strict minimum set of information to define the turn move.
///
///
///
public void SendMove(object move, bool finished)
{
if (IsFinishedByMe)
{
UnityEngine.Debug.LogWarning("Can't SendMove. Turn is finished by this player.");
return;
}
// along with the actual move, we have to send which turn this move belongs to
Hashtable moveHt = new Hashtable();
moveHt.Add("turn", Turn);
moveHt.Add("move", move);
byte evCode = (finished) ? EvFinalMove : EvMove;
PhotonNetwork.RaiseEvent(evCode, moveHt, true, new RaiseEventOptions() { CachingOption = EventCaching.AddToRoomCache });
if (finished)
{
PhotonNetwork.player.SetFinishedTurn(Turn);
}
// the server won't send the event back to the origin (by default). to get the event, call it locally
// (note: the order of events might be mixed up as we do this locally)
OnEvent(evCode, moveHt, PhotonNetwork.player.ID);
}
///
/// Gets if the player finished the current turn.
///
/// true, if player finished the current turn, false otherwise.
/// The Player to check for
public bool GetPlayerFinishedTurn(PhotonPlayer player)
{
if (player != null && this.finishedPlayers != null && this.finishedPlayers.Contains(player))
{
return true;
}
return false;
}
#region Callbacks
///
/// Called by PhotonNetwork.OnEventCall registration
///
/// Event code.
/// Content.
/// Sender identifier.
public void OnEvent(byte eventCode, object content, int senderId)
{
PhotonPlayer sender = PhotonPlayer.Find(senderId);
switch (eventCode)
{
case EvMove:
{
Hashtable evTable = content as Hashtable;
int turn = (int)evTable["turn"];
object move = evTable["move"];
this.TurnManagerListener.OnPlayerMove(sender, turn, move);
break;
}
case EvFinalMove:
{
Hashtable evTable = content as Hashtable;
int turn = (int)evTable["turn"];
object move = evTable["move"];
if (turn == this.Turn)
{
this.finishedPlayers.Add(sender);
this.TurnManagerListener.OnPlayerFinished(sender, turn, move);
}
if (IsCompletedByAll)
{
this.TurnManagerListener.OnTurnCompleted(this.Turn);
}
break;
}
}
}
///
/// Called by PhotonNetwork
///
/// Properties that changed.
public override void OnPhotonCustomRoomPropertiesChanged(Hashtable propertiesThatChanged)
{
// Debug.Log("OnPhotonCustomRoomPropertiesChanged: "+propertiesThatChanged.ToStringFull());
if (propertiesThatChanged.ContainsKey("Turn"))
{
_isOverCallProcessed = false;
this.finishedPlayers.Clear();
this.TurnManagerListener.OnTurnBegins(this.Turn);
}
}
#endregion
}
public interface IPunTurnManagerCallbacks
{
///
/// Called the turn begins event.
///
/// Turn Index
void OnTurnBegins(int turn);
///
/// Called when a turn is completed (finished by all players)
///
/// Turn Index
void OnTurnCompleted(int turn);
///
/// Called when a player moved (but did not finish the turn)
///
/// Player reference
/// Turn Index
/// Move Object data
void OnPlayerMove(PhotonPlayer player, int turn, object move);
///
/// When a player finishes a turn (includes the action/move of that player)
///
/// Player reference
/// Turn index
/// Move Object data
void OnPlayerFinished(PhotonPlayer player, int turn, object move);
///
/// Called when a turn completes due to a time constraint (timeout for a turn)
///
/// Turn index
void OnTurnTimeEnds(int turn);
}
public static class TurnExtensions
{
///
/// currently ongoing turn number
///
public static readonly string TurnPropKey = "Turn";
///
/// start (server) time for currently ongoing turn (used to calculate end)
///
public static readonly string TurnStartPropKey = "TStart";
///
/// Finished Turn of Actor (followed by number)
///
public static readonly string FinishedTurnPropKey = "FToA";
///
/// Sets the turn.
///
/// Room reference
/// Turn index
/// If set to true set start time.
public static void SetTurn(this Room room, int turn, bool setStartTime = false)
{
if (room == null || room.CustomProperties == null)
{
return;
}
Hashtable turnProps = new Hashtable();
turnProps[TurnPropKey] = turn;
if (setStartTime)
{
turnProps[TurnStartPropKey] = PhotonNetwork.ServerTimestamp;
}
room.SetCustomProperties(turnProps);
}
///
/// Gets the current turn from a RoomInfo
///
/// The turn index
/// RoomInfo reference
public static int GetTurn(this RoomInfo room)
{
if (room == null || room.CustomProperties == null || !room.CustomProperties.ContainsKey(TurnPropKey))
{
return 0;
}
return (int)room.CustomProperties[TurnPropKey];
}
///
/// Returns the start time when the turn began. This can be used to calculate how long it's going on.
///
/// The turn start.
/// Room.
public static int GetTurnStart(this RoomInfo room)
{
if (room == null || room.CustomProperties == null || !room.CustomProperties.ContainsKey(TurnStartPropKey))
{
return 0;
}
return (int)room.CustomProperties[TurnStartPropKey];
}
///
/// gets the player's finished turn (from the ROOM properties)
///
/// The finished turn index
/// Player reference
public static int GetFinishedTurn(this PhotonPlayer player)
{
Room room = PhotonNetwork.room;
if (room == null || room.CustomProperties == null || !room.CustomProperties.ContainsKey(TurnPropKey))
{
return 0;
}
string propKey = FinishedTurnPropKey + player.ID;
return (int)room.CustomProperties[propKey];
}
///
/// Sets the player's finished turn (in the ROOM properties)
///
/// Player Reference
/// Turn Index
public static void SetFinishedTurn(this PhotonPlayer player, int turn)
{
Room room = PhotonNetwork.room;
if (room == null || room.CustomProperties == null)
{
return;
}
string propKey = FinishedTurnPropKey + player.ID;
Hashtable finishedTurnProp = new Hashtable();
finishedTurnProp[propKey] = turn;
room.SetCustomProperties(finishedTurnProp);
}
}