SebastianLawe

Untitled

Sep 20th, 2015
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 14.96 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using System;
  4. using XInputDotNetPure;
  5. using Assets.Scripts;
  6. using UnityEngine.UI;
  7. using System.Diagnostics;
  8. using System.Threading;
  9. using Photon;
  10.  
  11. public class ServerManager : PunBehaviour {
  12.     string _ip = "";
  13.     public bool _server;
  14.     public bool _teamMatch = false;
  15.     public bool _canRespawn = true;
  16.     public int _playerCount;
  17.     public int _playerCountX;
  18.     public int _playerCountY;
  19.     public int _playerSpacing;
  20.     public bool isOffline;
  21.     TeamManager teamManager;
  22.     private bool _connect = false;
  23.     private bool _playerCreated;
  24.     private int _lastYAllocation;
  25.     private int _lastXAllocation;
  26.     private bool _aiPlayersSpawned;
  27.     public int localPlayers;
  28.     GameObject newestPlayer;
  29.     Vector3 lastSpawned = new Vector3(0, 1, 0);
  30.     private bool roomCreated;
  31.     private bool isMatchMaking;
  32.     private bool isCustomGame;
  33.     GameType gameType;
  34.     private bool customGameReadyToConfigure;
  35.     private byte maxPlayers;
  36.     public Text roomName;
  37.     public Dropdown customGameType;
  38.     public Dropdown matchMakingGameType;
  39.     public Dropdown playersDropDown;
  40.     public Toggle offlineToggle;
  41.     public GameObject[] menus;
  42.     public int playersRequiredToStartMatch;
  43.     private Stopwatch levelTimer;
  44.     private bool sentLevelLoadRequest;
  45.     private int retryAttempts;
  46.     public bool paused;
  47.  
  48.     public bool levelLoaded { get; private set; }
  49.     public bool isDud;
  50.  
  51.     public event EventHandler matchStarted;
  52.     // Use this for initialization
  53.     void Start() {
  54.         if (!isDud) {
  55.             levelTimer = new Stopwatch();
  56.             PhotonNetwork.automaticallySyncScene = true;
  57.             PhotonNetwork.sendRate = 30;
  58.             PhotonNetwork.sendRateOnSerialize = 30;
  59.             DontDestroyOnLoad(gameObject);
  60.             teamManager = GetComponent<TeamManager>();
  61.             if (ControllerConfig.HasMouseKeyboardConfigured) {
  62.                 _playerCount++;
  63.             }
  64.             for (int i = 0; i < 4 - ControllerConfig.Offset; ++i) {
  65.                 PlayerIndex testPlayerIndex = (PlayerIndex)i;
  66.                 GamePadState testState = GamePad.GetState(testPlayerIndex);
  67.                 if (testState.IsConnected) {
  68.                     _playerCount++;
  69.                 }
  70.             }
  71.             Application.LoadLevel(UnityEngine.Random.Range(1, 3));
  72.         }
  73.     }
  74.     public void SetGameType() {
  75.         if (isMatchMaking) {
  76.             gameType = (GameType)matchMakingGameType.value;
  77.         }
  78.         if (isCustomGame) {
  79.             gameType = (GameType)customGameType.value;
  80.         }
  81.         teamManager.gameType = gameType;
  82.     }
  83.  
  84.     public void GoBack() {
  85.         isCustomGame = false;
  86.         isMatchMaking = false;
  87.         menus[0].SetActive(true);
  88.         menus[1].SetActive(false);
  89.         menus[2].SetActive(false);
  90.         menus[3].SetActive(false);
  91.         menus[4].SetActive(false);
  92.     }
  93.  
  94.     public void GoMatchmaking() {
  95.         isMatchMaking = true;
  96.         menus[0].SetActive(false);
  97.         menus[1].SetActive(true);
  98.         menus[2].SetActive(false);
  99.         menus[3].SetActive(false);
  100.         menus[4].SetActive(false);
  101.     }
  102.  
  103.     public void GoCustomGames() {
  104.         isCustomGame = true;
  105.         menus[0].SetActive(false);
  106.         menus[1].SetActive(false);
  107.         menus[2].SetActive(true);
  108.         menus[3].SetActive(false);
  109.         menus[4].SetActive(false);
  110.     }
  111.  
  112.     public void DisableMenus() {
  113.         menus[0].SetActive(false);
  114.         menus[1].SetActive(false);
  115.         menus[2].SetActive(false);
  116.         menus[3].SetActive(false);
  117.         menus[4].SetActive(false);
  118.         paused = false;
  119.     }
  120.  
  121.     public void GoControllerSettings() {
  122.         menus[0].SetActive(false);
  123.         menus[1].SetActive(false);
  124.         menus[2].SetActive(false);
  125.         menus[3].SetActive(false);
  126.         menus[4].SetActive(true);
  127.     }
  128.  
  129.     public void StartMatchmaking() {
  130.         PhotonNetwork.offlineMode = false;
  131.         PhotonNetwork.ConnectUsingSettings("v4.2");
  132.         DisableMenus();
  133.     }
  134.  
  135.     public void StartCustomGame() {
  136.         PhotonNetwork.offlineMode = offlineToggle.isOn;
  137.         if (!PhotonNetwork.offlineMode) {
  138.             PhotonNetwork.ConnectUsingSettings("v4.2");
  139.         } else {
  140.             CreateCustomMatch();
  141.         }
  142.         isCustomGame = true;
  143.         DisableMenus();
  144.     }
  145.     public void StartLocalGame() {
  146.         PhotonNetwork.offlineMode = true;
  147.         isCustomGame = true;
  148.         DisableMenus();
  149.     }
  150.     public void CreateCustomMatch() {
  151.         RoomOptions option = new RoomOptions();
  152.         TypedLobby lobby = new TypedLobby();
  153.         option.maxPlayers = (byte)((playersDropDown.value + 1) * 4);
  154.         option.customRoomProperties = new ExitGames.Client.Photon.Hashtable();
  155.         option.customRoomProperties.Add("GT", (int)gameType);
  156.         PhotonNetwork.LeaveRoom();
  157.         PhotonNetwork.JoinOrCreateRoom(roomName.ToString(), option, lobby);
  158.         DisableMenus();
  159.     }
  160.  
  161.  
  162.     void OnConnectedToMaster() {
  163.         if (isMatchMaking) {
  164.             UnityEngine.Debug.Log("Connected to matchmaking.");
  165.             UnityEngine.Debug.Log(string.Format("Attemting to join game with game type {0}. Attempt {1}", gameType.ToString(), retryAttempts));
  166.             ExitGames.Client.Photon.Hashtable expectedCustomRoomProperties = new ExitGames.Client.Photon.Hashtable() { { "GT", (int)gameType } };
  167.             PhotonNetwork.JoinRandomRoom(expectedCustomRoomProperties, 16);
  168.         }
  169.         if (isCustomGame) {
  170.             CreateCustomMatch();
  171.         }
  172.     }
  173.  
  174.     public void DisplayPause() {
  175.         paused = true;
  176.         menus[0].SetActive(false);
  177.         menus[1].SetActive(false);
  178.         menus[2].SetActive(false);
  179.         menus[3].SetActive(true);
  180.         Cursor.visible = true;
  181.     }
  182.  
  183.     public void HidePause() {
  184.         paused = false;
  185.         DisableMenus();
  186.         Cursor.visible = false;
  187.     }
  188.  
  189.     public void Disconnect() {
  190.         paused = false;
  191.         PhotonNetwork.Disconnect();
  192.         GoBack();
  193.         foreach (PlayerController player in FindObjectsOfType<PlayerController>()) {
  194.             Destroy(player.gameObject);
  195.         }
  196.         _playerCreated = false;
  197.         _server = false;
  198.         teamManager.hasAssignedColors = false;
  199.         teamManager.hasEnumeratedTeamItems = false;
  200.         levelLoaded = false;
  201.         Application.LoadLevel(0);
  202.         Destroy(gameObject);
  203.     }
  204.  
  205.     void OnPhotonRandomJoinFailed() {
  206.         if (isMatchMaking) {
  207.             if (retryAttempts++ < 30) {
  208.                 OnConnectedToMaster();
  209.             } else {
  210.                 RoomOptions options = new RoomOptions();
  211.                 TypedLobby lobby = new TypedLobby();
  212.                 options.isOpen = true;
  213.                 options.isVisible = true;
  214.                 options.maxPlayers = 16;
  215.                 options.customRoomProperties = new ExitGames.Client.Photon.Hashtable();
  216.                 options.customRoomPropertiesForLobby = new string[2] { "GT", gameType.ToString() };
  217.                 options.customRoomProperties.Add("GT", (int)gameType);
  218.                 PhotonNetwork.CreateRoom(null, options, lobby);
  219.                 UnityEngine.Debug.Log("No rooms found. Creating a new one.");
  220.             }
  221.         }
  222.     }
  223.  
  224.     // Update is called once per frame
  225.     void Update() {
  226.         if (!isDud) {
  227.             if (PhotonNetwork.playerList.Length >= playersRequiredToStartMatch) {
  228.                 if (matchStarted != null) {
  229.                     matchStarted(this, EventArgs.Empty);
  230.                 }
  231.             }
  232.             if (PhotonNetwork.connectionStateDetailed == PeerState.Joined) {
  233.                 _server = PhotonNetwork.isMasterClient;
  234.                 if (_server || PhotonNetwork.offlineMode) {
  235.                     if (!sentLevelLoadRequest) {
  236.                         levelLoaded = false;
  237.                         if (gameType == GameType.CTF) {
  238.                             PhotonNetwork.LoadLevel(1);
  239.                         }
  240.                         if (gameType == GameType.Territores) {
  241.                             PhotonNetwork.LoadLevel(2);
  242.                         }
  243.                         if (gameType == GameType.Elimination) {
  244.                             PhotonNetwork.LoadLevel(3);
  245.                         }
  246.                         sentLevelLoadRequest = true;
  247.                     }
  248.                 }
  249.                 if (levelTimer == null) {
  250.                     levelTimer = new Stopwatch();
  251.                 }
  252.                 if (!levelTimer.IsRunning && !levelLoaded) {
  253.                     levelTimer.Start();
  254.                 }
  255.                 if (levelTimer.ElapsedMilliseconds >= 5000) {
  256.                     //UnityEngine.Debug.Log("Level Loaded.");
  257.                     levelLoaded = true;
  258.                     if (teamManager.hasAssignedColors) {
  259.                         levelTimer.Reset();
  260.                         if (!_playerCreated) {
  261.                             Spawn[] spawns = FindObjectsOfType<Spawn>();
  262.                             for (int i = 0; i < _playerCount; i++) {
  263.                                 SpawnPlayer(spawns[UnityEngine.Random.Range(0, spawns.Length - 1)].transform.position);
  264.                             }
  265.                             _playerCreated = true;
  266.                         }
  267.                     }
  268.                 }
  269.             }
  270.         }
  271. #if !UNITY_EDITOR
  272.         //Screen.lockCursor = true;
  273. #endif
  274.         #region Old Code
  275.         //if (!isOffline) {
  276.         //    if (isMatchMaking) {
  277.         //        if (PhotonNetwork.connectionStateDetailed == PeerState.ConnectedToMaster) {
  278.         //            if (!_server) {
  279.         //                PhotonNetwork.JoinRandomRoom();
  280.         //                _connect = true;
  281.         //            } else {
  282.         //                PhotonNetwork.CreateRoom(Guid.NewGuid().ToString());
  283.         //                PhotonNetwork.LoadLevel(UnityEngine.Random.Range(1, 2));
  284.         //            }
  285.         //        }
  286.         //        if (PhotonNetwork.connectionStateDetailed == PeerState.Joined) {
  287.         //            if (_server) {
  288.         //                _connect = true;
  289.         //                //SpawnPlayer(_teamMatch ? "Team A" : DateTime.Now.Ticks.ToString());
  290.         //            }
  291.         //            if (PhotonNetwork.playerList.Length >= 2) {
  292.         //                if (_connect) {
  293.         //                    if (!_playerCreated) {
  294.         //                        if (teamManager.hasAssignedColors) {
  295.         //                            for (int i = 0; i < _playerCount; i++) {
  296.         //                                SpawnPlayer(_teamMatch ? "Team A" : DateTime.Now.Ticks.ToString());
  297.         //                            }
  298.         //                            _connect = false;
  299.         //                            _playerCreated = true;
  300.         //                        }
  301.         //                    }
  302.         //                }
  303.         //            } else if (_server && !_playerCreated) {
  304.         //                //if (teamManager.hasAssignedColors) {
  305.         //                //    for (int i = 0; i < _playerCount; i++) {
  306.         //                //        SpawnPlayer(_teamMatch ? "Team A" : DateTime.Now.Ticks.ToString());
  307.         //                //    }
  308.         //                //    _connect = false;
  309.         //                //    _playerCreated = true;
  310.         //                //}
  311.         //            }
  312.         //        }
  313.         //    } else {
  314.         //        if (!_playerCreated) {
  315.         //            if (!roomCreated) {
  316.         //                PhotonNetwork.CreateRoom(Guid.NewGuid().ToString());
  317.         //                Application.LoadLevel(UnityEngine.Random.Range(1, 2));
  318.         //                roomCreated = true;
  319.         //            }
  320.         //            if (teamManager.hasAssignedColors) {
  321.         //                //SpawnPlayer();
  322.         //                for (int i = 0; i < _playerCount; i++) {
  323.         //                    SpawnPlayer(_teamMatch ? "Team A" : DateTime.Now.Ticks.ToString());
  324.         //                }
  325.         //                _playerCreated = true;
  326.         //            }
  327.         //        }
  328.         //    }
  329.         //}
  330.         #endregion Old Code
  331.     }
  332.  
  333.     private void SpawnAI() {
  334.         //MasterServer.RegisterHost("Test", "Test", "");
  335.         if (!_aiPlayersSpawned) {
  336.             for (int x = 0; x < _playerCount; x++) {
  337.                 string team = x % 2 == 0 ? "Team A" : "Team B";
  338.                 SpawnAI(_teamMatch ? team : DateTime.Now.Ticks.ToString());
  339.                 _aiPlayersSpawned = true;
  340.             }
  341.         }
  342.     }
  343.  
  344.     public void SpawnPlayer(Vector3 location) {
  345.         newestPlayer = PhotonNetwork.Instantiate("RobotA", location, Quaternion.identity, 0) as GameObject;
  346.         newestPlayer.GetComponent<PlayerController>().localPlayerNumber = localPlayers++;
  347.         teamManager.CmdRegisterPlayer(newestPlayer.GetComponent<PlayerController>().photonView.viewID);
  348.         newestPlayer.GetComponent<PlayerController>().serverPrepDone = true;
  349.         // photonView.RPC("ModifyPlayer", PhotonTargets.All, false, false);
  350.     }
  351.  
  352.     public void SpawnAI(Vector3 location, string faction) {
  353.         newestPlayer = PhotonNetwork.Instantiate("RobotA", location, Quaternion.identity, 0) as GameObject;
  354.         // photonView.RPC("ModifyPlayer", PhotonTargets.All, true, !_teamMatch);
  355.     }
  356.  
  357.     public void SpawnPlayer() {
  358.         if (_lastXAllocation >= _playerCountX) {
  359.             _lastXAllocation = 0;
  360.         }
  361.         if (_lastXAllocation < _playerCountX) {
  362.             if (_lastYAllocation >= _playerCountY) {
  363.                 _lastYAllocation = 0;
  364.                 _lastXAllocation++;
  365.             }
  366.             if (_lastYAllocation < _playerCountY) {
  367.                 SpawnPlayer(new Vector3(_lastXAllocation * _playerSpacing, 1, _lastYAllocation++ * _playerSpacing));
  368.             }
  369.         }
  370.     }
  371.  
  372.     public void SpawnAI(string faction) {
  373.         if (_lastXAllocation >= _playerCountX) {
  374.             _lastXAllocation = 0;
  375.         }
  376.         if (_lastXAllocation < _playerCountX) {
  377.             if (_lastXAllocation < _playerCountX) {
  378.                 if (_lastYAllocation >= _playerCountY) {
  379.                     _lastYAllocation = 0;
  380.                     _lastXAllocation++;
  381.                 }
  382.                 if (_lastYAllocation < _playerCountY) {
  383.                     SpawnAI(new Vector3(_lastXAllocation * _playerSpacing, 1, _lastYAllocation++ * _playerSpacing), faction);
  384.                 }
  385.             }
  386.         }
  387.     }
  388.     [PunRPC]
  389.     public void ModifyPlayer(Color faction, bool isAI, bool isFreeForAll) {
  390.         if (newestPlayer != null) {
  391.             PlayerController controller = newestPlayer.GetComponent<PlayerController>();
  392.             if (controller != null) {
  393.                 controller.GetComponent<FactionManager>().color = faction;
  394.                 //controller._useAI = isAI;
  395.                 //controller._freeForAll = isFreeForAll;
  396.             }
  397.         }
  398.     }
  399. }
Advertisement
Add Comment
Please, Sign In to add comment