Advertisement
Guest User

Untitled

a guest
Sep 9th, 2016
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 14.30 KB | None | 0 0
  1. <?php
  2. namespace MyApp;
  3. use Ratchet\MessageComponentInterface;
  4. use Ratchet\ConnectionInterface;
  5. use Mysqli;
  6.  
  7. require_once("../../../var/www/html/Resources/PHP/Libraries/DatabaseLibrary.php");
  8. require_once("../../../var/www/html/Resources/PHP/Libraries/Utilities.php");
  9. require_once("../../../var/www/html/Resources/PHP/Libraries/UserSession.php");
  10. require_once("../../../var/www/dev2.animeandmangaclub.net/Resources/PHP/Libraries/unoGameUtil.php");
  11.  
  12.  
  13. class unoServer implements MessageComponentInterface {
  14.     protected $clients;
  15.     private static $serverDBConnection;
  16.     private static $unoCards = array(
  17.         1=>array("color"=>"red", "type"=>"number", "text"=>"0"),
  18.         2=>array("color"=>"red", "type"=>"number", "text"=>"1"),
  19.         3=>array("color"=>"red", "type"=>"number", "text"=>"2"),
  20.         4=>array("color"=>"red", "type"=>"number", "text"=>"3"),
  21.         5=>array("color"=>"red", "type"=>"number", "text"=>"4"),
  22.         6=>array("color"=>"red", "type"=>"number", "text"=>"5"),
  23.         7=>array("color"=>"red", "type"=>"number", "text"=>"6"),
  24.         8=>array("color"=>"red", "type"=>"number", "text"=>"7"),
  25.         9=>array("color"=>"red", "type"=>"number", "text"=>"8"),
  26.         10=>array("color"=>"red", "type"=>"number", "text"=>"9"),
  27.         11=>array("color"=>"yellow", "type"=>"number", "text"=>"0"),
  28.         12=>array("color"=>"yellow", "type"=>"number", "text"=>"1"),
  29.         13=>array("color"=>"yellow", "type"=>"number", "text"=>"2"),
  30.         14=>array("color"=>"yellow", "type"=>"number", "text"=>"3"),
  31.         15=>array("color"=>"yellow", "type"=>"number", "text"=>"4"),
  32.         16=>array("color"=>"yellow", "type"=>"number", "text"=>"5"),
  33.         17=>array("color"=>"yellow", "type"=>"number", "text"=>"6"),
  34.         18=>array("color"=>"yellow", "type"=>"number", "text"=>"7"),
  35.         19=>array("color"=>"yellow", "type"=>"number", "text"=>"8"),
  36.         20=>array("color"=>"yellow", "type"=>"number", "text"=>"9"),
  37.         21=>array("color"=>"green", "type"=>"number", "text"=>"0"),
  38.         22=>array("color"=>"green", "type"=>"number", "text"=>"1"),
  39.         23=>array("color"=>"green", "type"=>"number", "text"=>"2"),
  40.         24=>array("color"=>"green", "type"=>"number", "text"=>"3"),
  41.         25=>array("color"=>"green", "type"=>"number", "text"=>"4"),
  42.         26=>array("color"=>"green", "type"=>"number", "text"=>"5"),
  43.         27=>array("color"=>"green", "type"=>"number", "text"=>"6"),
  44.         28=>array("color"=>"green", "type"=>"number", "text"=>"7"),
  45.         29=>array("color"=>"green", "type"=>"number", "text"=>"8"),
  46.         30=>array("color"=>"green", "type"=>"number", "text"=>"9"),
  47.         31=>array("color"=>"blue", "type"=>"number", "text"=>"0"),
  48.         32=>array("color"=>"blue", "type"=>"number", "text"=>"1"),
  49.         33=>array("color"=>"blue", "type"=>"number", "text"=>"2"),
  50.         34=>array("color"=>"blue", "type"=>"number", "text"=>"3"),
  51.         35=>array("color"=>"blue", "type"=>"number", "text"=>"4"),
  52.         36=>array("color"=>"blue", "type"=>"number", "text"=>"5"),
  53.         37=>array("color"=>"blue", "type"=>"number", "text"=>"6"),
  54.         38=>array("color"=>"blue", "type"=>"number", "text"=>"7"),
  55.         39=>array("color"=>"blue", "type"=>"number", "text"=>"8"),
  56.         40=>array("color"=>"blue", "type"=>"number", "text"=>"9"),
  57.        
  58.         // Special cards
  59.         41=>array("color"=>"red", "type"=>"action", "text"=>"skip"),
  60.         42=>array("color"=>"red", "type"=>"action", "text"=>"reverse"),
  61.         43=>array("color"=>"red", "type"=>"action", "text"=>"draw2"),
  62.        
  63.         44=>array("color"=>"yellow", "type"=>"action", "text"=>"skip"),
  64.         45=>array("color"=>"yellow", "type"=>"action", "text"=>"reverse"),
  65.         46=>array("color"=>"yellow", "type"=>"action", "text"=>"draw2"),
  66.        
  67.         47=>array("color"=>"green", "type"=>"action", "text"=>"skip"),
  68.         48=>array("color"=>"green", "type"=>"action", "text"=>"reverse"),
  69.         49=>array("color"=>"green", "type"=>"action", "text"=>"draw2"),
  70.        
  71.         50=>array("color"=>"blue", "type"=>"action", "text"=>"skip"),
  72.         51=>array("color"=>"blue", "type"=>"action", "text"=>"reverse"),
  73.         52=>array("color"=>"blue", "type"=>"action", "text"=>"draw2"),
  74.        
  75.         53=>array("color"=>"wild", "type"=>"wild", "text"=>"wild"),
  76.         54=>array("color"=>"wild", "type"=>"wild", "text"=>"draw4"),
  77.  
  78.     );
  79.     private static $openGames = array();
  80.     /*
  81.         Array design
  82.         {
  83.             [gameID] = {
  84.                 [hasPassword] = bool;
  85.                 [roomPassword] = "";
  86.                 [mostRecentCardID] = integer; -> card ID that is face up in the center
  87.                 [userIDTurn] = integer; -> userID whose turn it is
  88.                 [registeredPlayerIDs] = {
  89.                     [userID] = {
  90.                         [cardsInHand] = {}; -> list of cardIDs in this userID's hand
  91.                     }
  92.                 }
  93.                
  94.             }
  95.         }
  96.     */
  97.     public static $resourceIDLog = array(); // stores resourceIds as indices and UserIDs as their value
  98.     public static $connectedUsers = array(); // Stores who is connected by their ID. Also stores how many instances they have connected (tabs or other windows).
  99.     // This array is set up like this
  100.     /*
  101.         {
  102.             [userID] = {
  103.                 "resourceIDs"=>{},
  104.                 "userObject"=>User userObject
  105.             }
  106.         }
  107.     */
  108.  
  109.     public function __construct() {
  110.         $this->clients = new \SplObjectStorage;
  111.         self::$serverDBConnection = NewMySQLi();
  112.     }
  113.    
  114.     private function verifyDBConnection(){
  115.         if (!self::$serverDBConnection->ping()){ // mysqlnd doesn't allow ping() to automatically reconnect the connection.
  116.             self::$serverDBConnection = NewMySQLi();
  117.         }
  118.     }
  119.  
  120.     public function onOpen(ConnectionInterface $conn){
  121.         $this->clients->attach($conn);
  122.     }
  123.    
  124.     private function pushDataToClients($data, $ignoreThisClient = false){ // $ignoreThisClient should be a ConnectionInterface object to not send data to
  125.         // $data should be a string
  126.         foreach($this->clients as $client){
  127.             if ($client !== $ignoreThisClient){
  128.                 $client->send($data);
  129.             }
  130.         }
  131.     }
  132.    
  133.     private function pushDataToClientsByResourceIDs($data, $resourceIDs){ // send array of ids
  134.         // $data should be a string
  135.         foreach($this->clients as $client){
  136.             if (array_search($client->resourceId, $resourceIDs) !== false){
  137.                 $client->send($data);
  138.             }
  139.         }
  140.     }
  141.    
  142.     private function pushDataToUserID($data, $userID){
  143.         // $data should be a string
  144.         $userID = (int)$userID;
  145.         if (isset(self::$connectedUsers[$userID])){
  146.             // We've verified the user is connected
  147.             $resourceIDs = self::$connectedUsers[$userID]['resourceIDs'];
  148.             foreach($this->clients as $client){
  149.                 if (array_search($client->resourceId, $resourceIDs) !== false){
  150.                     // We've verified that the current iterated client's resource ID is in the array of connections the userID we want to send to has.
  151.                     $client->send($data);
  152.                 }
  153.             }
  154.         }
  155.     }
  156.    
  157.     private function attachClient($userObject, $resourceID){
  158.         // First, we see if they already have a tab/window of the chat open
  159.         $userID = $userObject->Get("id");
  160.         self::$resourceIDLog[$resourceID] = $userID;
  161.        
  162.         if (!isset(self::$connectedUsers[$userID])){
  163.             // Add their info to the table
  164.             self::$connectedUsers[$userID] = array(
  165.                 "resourceIDs" => array($resourceID),
  166.                 "userObject"=>$userObject,
  167.                 "joinTime"=>time()
  168.             );
  169.            
  170.             return true; // Means we need to tell existing connections to add a new user
  171.         }else{
  172.             // They already exist, so just add to their resource IDs
  173.             array_push(
  174.                 self::$connectedUsers[$userID]['resourceIDs'],
  175.                 $resourceID
  176.             );
  177.            
  178.             return false; // Do not tell existing clients about this user. They're already aware
  179.         }
  180.        
  181.         return 0; // Should never happen
  182.     }
  183.    
  184.     public function doesGamServerCacheExist($gameID){
  185.         $gameID = (int)$gameID;
  186.         if (isset( self::$openGames[$gameID] )){
  187.             return true;
  188.         }else{
  189.             return false;
  190.         }
  191.     }
  192.    
  193.     public function updateRegisteredPlayers(\unoGame $game){
  194.         $gameID = (int)$game::$gameRow['id'];
  195.         $hostID = (int)$game::$gameRow['hostUserID'];
  196.         $players = array(
  197.             $hostID,
  198.             (int)$game::$gameRow['player2'],
  199.             (int)$game::$gameRow['player3'],
  200.             (int)$game::$gameRow['player4'],
  201.         );
  202.         foreach($players as $index=>$userID){
  203.             if ($userID !== 0){
  204.                 self::$openGames[$gameID]['registeredPlayerIDs'][$userID] = array(
  205.                     "cardsInHand"=>array()
  206.                 );
  207.             }
  208.         }
  209.     }
  210.    
  211.     public function dealCards($gameID){
  212.         $gameID = (int)$gameID;
  213.         $gameCache = self::$openGames[$gameID];
  214.         $players = $gameCache['registeredPlayerIDs'];
  215.        
  216.         foreach($players as $userID => $pData){
  217.             self::$openGames[$gameID]['registeredPlayerIDs'][$userID]['cardsInHand'] = array_rand(self::$unoCards, 8);
  218.         }
  219.        
  220.         print("Dealt cards \n");
  221.     }
  222.    
  223.     public function createServerCacheOfGame(\unoGame $game){
  224.         $gameID = (int)$game::$gameRow['id'];
  225.         $hasPassword = (bool)$game::$gameRow['passwordProtected'];
  226.         $password = (string)$game::$gameRow['roomPassword'];
  227.         $hostID = (int)$game::$gameRow['hostUserID'];
  228.         $gameArray = array(
  229.             "hasPassword"=>$hasPassword,
  230.             "roomPassword"=>$password,
  231.             "userIDTurn"=>$hostID,
  232.             "currentFieldCardID"=>array_rand(self::$unoCards, 1),
  233.             "registeredPlayerIDs"=>array()
  234.         );
  235.         self::$openGames[$gameID] = $gameArray;
  236.     }
  237.    
  238.     public function sendDataToPlayers($gameID, $data){
  239.         $gameID = (int)$gameID;
  240.         $gameCache = self::$openGames[$gameID];
  241.         $players = $gameCache['registeredPlayerIDs'];
  242.         $playersJSON = json_encode($players);
  243.         $playerResourceIDs = array();
  244.        
  245.         foreach($players as $userID => $pData){
  246.             if (isset(self::$connectedUsers[$userID])){
  247.                 $resources = self::$connectedUsers[$userID]['resourceIDs'];
  248.                 $playerResourceIDs = array_merge($playerResourceIDs, $resources);
  249.             }
  250.         }
  251.        
  252.         $this->pushDataToClientsByResourceIDs($data, $playerResourceIDs);
  253.     }
  254.    
  255.     public function getInitialData($gameID){
  256.         $gameID = (int)$gameID;
  257.         $gameCache = self::$openGames[$gameID];
  258.         $thisGame = new \unoGame($gameID);
  259.         $players = $gameCache['registeredPlayerIDs'];
  260.         $playerData = array();
  261.        
  262.         foreach($players as $userID => $pData){
  263.             $cardsInHand = $pData['cardsInHand'];
  264.             print_r($cardsInHand);
  265.             $user = new \User((int)$userID, true); // self::$connectedUsers[$userID]['userObject']; -> They might not be on the server, this breaks shit.
  266.             array_push($playerData, array(
  267.                 "id"=>$user->get("id"),
  268.                 "username"=>$user->get("name"),
  269.                 "hand"=>$cardsInHand
  270.             ));
  271.         }
  272.         $data = array(
  273.             "action"=>"initialData",
  274.             "gameStarted"=>(bool)((int)$thisGame::$gameRow['gameBegan']),
  275.             "currentFieldCardID" => $gameCache['currentFieldCardID'],
  276.             "userIDTurn" => $gameCache['userIDTurn'],
  277.             "userData"=>$playerData,
  278.         );
  279.        
  280.         return $data;
  281.     }
  282.  
  283.     public function onMessage(ConnectionInterface $from, $json) {
  284.        
  285.         $ip = $from->remoteAddress;
  286.         $rObj = json_decode($json, true); // rObj = Received Object
  287.         $util = new \Util();
  288.        
  289.         if (is_array($rObj)){
  290.            
  291.             $requestedAction = (string)$rObj['action'];
  292.             $loginToken = (string)$rObj['userToken'];
  293.             $gameID = (int)$rObj['gameID'];
  294.             $thisUser = new \User($loginToken, true);
  295.             $thisGame = new \unoGame($gameID);
  296.            
  297.             if ($thisUser->doesExist()){
  298.                 if ($requestedAction === "attachClient"){
  299.                     // Be sure the server has a gameID array ready. If not, make one (so long as the game actually exists)
  300.                     $this->attachClient($thisUser, $from->resourceId);
  301.                    
  302.                     if ($thisGame->gameExists === true){
  303.                         print("Game $gameID exists. \n");
  304.                        
  305.                         if ($this->doesGamServerCacheExist($gameID) === false){
  306.                             print("No server cache of game exists. Creating game.\n");
  307.                             $this->createServerCacheOfGame($thisGame);
  308.                         }
  309.                         $this->updateRegisteredPlayers($thisGame);
  310.                         $this->pushDataToUserID(
  311.                             json_encode($this->getInitialData($gameID)),
  312.                             $thisUser->get("id")
  313.                         );
  314.                     }else{
  315.                         print("Game $gameID does not exist. \n");
  316.                     }
  317.                 }elseif($requestedAction === "dealCards"){
  318.                     if ($thisGame->gameExists === true){
  319.                         if ($this->doesGamServerCacheExist($gameID) !== false){
  320.                             print("Attempting to deal cards. \n");
  321.                             $hasAlreadyDealt = $thisGame::$gameRow['gameBegan'];
  322.                             if ( (int)$hasAlreadyDealt === 0){
  323.                                 if ( $thisGame->isUserHost($thisUser->get("id"))){
  324.                                     $thisGame->update("gameBegan", "i", 1);
  325.                                     $this->dealCards($gameID);
  326.                                     $this->sendDataToPlayers(
  327.                                         $gameID,
  328.                                         json_encode($this->getInitialData($gameID))
  329.                                     );
  330.                                 }else{
  331.                                     print("User attempting to deal is not the host. \n");
  332.                                 }
  333.                             }else{
  334.                                 print("Cards already dealt. \n");
  335.                             }
  336.                         }
  337.                     }
  338.                 }
  339.             }
  340.         }
  341.     }
  342.  
  343.     public function onClose(ConnectionInterface $conn) {
  344.         $this->clients->detach($conn);
  345.         $resourceID = $conn->resourceId;
  346.         $Util = new \Util();
  347.        
  348.         // Funny thing, I used to do this by searching the entire array of connectedUsers for the matching resourceId
  349.         // But then I just made an array that matched each resourceId to a UserID
  350.        
  351.         if (!isset(self::$resourceIDLog[$resourceID])){
  352.             return;
  353.         }
  354.        
  355.         $userID = self::$resourceIDLog[$resourceID];
  356.        
  357.         if (!isset(self::$connectedUsers[$userID])){
  358.             return;
  359.         }
  360.        
  361.         $connectedUser = self::$connectedUsers[$userID];
  362.         $indexID = array_search($resourceID,$connectedUser['resourceIDs']);
  363.         unset($connectedUser['resourceIDs'][$indexID]);
  364.         print("Disconnected $userID \n");
  365.        
  366.         // re-index the stored array and fill in any gaps
  367.         self::$connectedUsers[$userID]['resourceIDs'] = array_values($connectedUser['resourceIDs']);
  368.        
  369.         // Do they still have any tabs still open?
  370.         if (count($connectedUser['resourceIDs']) === 0){
  371.             // They're gone
  372.             // Inform other clients to remove them and remove them from the connected users
  373.             unset(self::$connectedUsers[$userID]);
  374.            
  375.             $packet = array(
  376.                 "serverRequest"=>"disconnectUser",
  377.                 "userID"=>$userID
  378.             );
  379.             $this->pushDataToClients( json_encode($packet) );
  380.         }else{
  381.             // They are still in the chat
  382.         }
  383.     }
  384.  
  385.     public function onError(ConnectionInterface $conn, \Exception $e) {
  386.         $conn->close();
  387.     }
  388.    
  389.     public function onServerCommunication($dataString){
  390.         $dataArray = json_decode($Data, true);
  391.         if (is_array($dataArray)){
  392.             $authenticationCode = $dataArray['IdentityCode'];
  393.             if ($authenticationCode === "AaMCServer"){
  394.                 // verified this is being sent from the server
  395.                
  396.             }
  397.         }
  398.     }
  399. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement