Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace MyApp;
- use Ratchet\MessageComponentInterface;
- use Ratchet\ConnectionInterface;
- use Mysqli;
- require_once("../../../var/www/html/Resources/PHP/Libraries/DatabaseLibrary.php");
- require_once("../../../var/www/html/Resources/PHP/Libraries/Utilities.php");
- require_once("../../../var/www/html/Resources/PHP/Libraries/UserSession.php");
- require_once("../../../var/www/dev2.animeandmangaclub.net/Resources/PHP/Libraries/unoGameUtil.php");
- class unoServer implements MessageComponentInterface {
- protected $clients;
- private static $serverDBConnection;
- private static $unoCards = array(
- 1=>array("color"=>"red", "type"=>"number", "text"=>"0"),
- 2=>array("color"=>"red", "type"=>"number", "text"=>"1"),
- 3=>array("color"=>"red", "type"=>"number", "text"=>"2"),
- 4=>array("color"=>"red", "type"=>"number", "text"=>"3"),
- 5=>array("color"=>"red", "type"=>"number", "text"=>"4"),
- 6=>array("color"=>"red", "type"=>"number", "text"=>"5"),
- 7=>array("color"=>"red", "type"=>"number", "text"=>"6"),
- 8=>array("color"=>"red", "type"=>"number", "text"=>"7"),
- 9=>array("color"=>"red", "type"=>"number", "text"=>"8"),
- 10=>array("color"=>"red", "type"=>"number", "text"=>"9"),
- 11=>array("color"=>"yellow", "type"=>"number", "text"=>"0"),
- 12=>array("color"=>"yellow", "type"=>"number", "text"=>"1"),
- 13=>array("color"=>"yellow", "type"=>"number", "text"=>"2"),
- 14=>array("color"=>"yellow", "type"=>"number", "text"=>"3"),
- 15=>array("color"=>"yellow", "type"=>"number", "text"=>"4"),
- 16=>array("color"=>"yellow", "type"=>"number", "text"=>"5"),
- 17=>array("color"=>"yellow", "type"=>"number", "text"=>"6"),
- 18=>array("color"=>"yellow", "type"=>"number", "text"=>"7"),
- 19=>array("color"=>"yellow", "type"=>"number", "text"=>"8"),
- 20=>array("color"=>"yellow", "type"=>"number", "text"=>"9"),
- 21=>array("color"=>"green", "type"=>"number", "text"=>"0"),
- 22=>array("color"=>"green", "type"=>"number", "text"=>"1"),
- 23=>array("color"=>"green", "type"=>"number", "text"=>"2"),
- 24=>array("color"=>"green", "type"=>"number", "text"=>"3"),
- 25=>array("color"=>"green", "type"=>"number", "text"=>"4"),
- 26=>array("color"=>"green", "type"=>"number", "text"=>"5"),
- 27=>array("color"=>"green", "type"=>"number", "text"=>"6"),
- 28=>array("color"=>"green", "type"=>"number", "text"=>"7"),
- 29=>array("color"=>"green", "type"=>"number", "text"=>"8"),
- 30=>array("color"=>"green", "type"=>"number", "text"=>"9"),
- 31=>array("color"=>"blue", "type"=>"number", "text"=>"0"),
- 32=>array("color"=>"blue", "type"=>"number", "text"=>"1"),
- 33=>array("color"=>"blue", "type"=>"number", "text"=>"2"),
- 34=>array("color"=>"blue", "type"=>"number", "text"=>"3"),
- 35=>array("color"=>"blue", "type"=>"number", "text"=>"4"),
- 36=>array("color"=>"blue", "type"=>"number", "text"=>"5"),
- 37=>array("color"=>"blue", "type"=>"number", "text"=>"6"),
- 38=>array("color"=>"blue", "type"=>"number", "text"=>"7"),
- 39=>array("color"=>"blue", "type"=>"number", "text"=>"8"),
- 40=>array("color"=>"blue", "type"=>"number", "text"=>"9"),
- // Special cards
- 41=>array("color"=>"red", "type"=>"action", "text"=>"skip"),
- 42=>array("color"=>"red", "type"=>"action", "text"=>"reverse"),
- 43=>array("color"=>"red", "type"=>"action", "text"=>"draw2"),
- 44=>array("color"=>"yellow", "type"=>"action", "text"=>"skip"),
- 45=>array("color"=>"yellow", "type"=>"action", "text"=>"reverse"),
- 46=>array("color"=>"yellow", "type"=>"action", "text"=>"draw2"),
- 47=>array("color"=>"green", "type"=>"action", "text"=>"skip"),
- 48=>array("color"=>"green", "type"=>"action", "text"=>"reverse"),
- 49=>array("color"=>"green", "type"=>"action", "text"=>"draw2"),
- 50=>array("color"=>"blue", "type"=>"action", "text"=>"skip"),
- 51=>array("color"=>"blue", "type"=>"action", "text"=>"reverse"),
- 52=>array("color"=>"blue", "type"=>"action", "text"=>"draw2"),
- 53=>array("color"=>"wild", "type"=>"wild", "text"=>"wild"),
- 54=>array("color"=>"wild", "type"=>"wild", "text"=>"draw4"),
- );
- private static $openGames = array();
- /*
- Array design
- {
- [gameID] = {
- [hasPassword] = bool;
- [roomPassword] = "";
- [mostRecentCardID] = integer; -> card ID that is face up in the center
- [userIDTurn] = integer; -> userID whose turn it is
- [registeredPlayerIDs] = {
- [userID] = {
- [cardsInHand] = {}; -> list of cardIDs in this userID's hand
- }
- }
- }
- }
- */
- public static $resourceIDLog = array(); // stores resourceIds as indices and UserIDs as their value
- public static $connectedUsers = array(); // Stores who is connected by their ID. Also stores how many instances they have connected (tabs or other windows).
- // This array is set up like this
- /*
- {
- [userID] = {
- "resourceIDs"=>{},
- "userObject"=>User userObject
- }
- }
- */
- public function __construct() {
- $this->clients = new \SplObjectStorage;
- self::$serverDBConnection = NewMySQLi();
- }
- private function verifyDBConnection(){
- if (!self::$serverDBConnection->ping()){ // mysqlnd doesn't allow ping() to automatically reconnect the connection.
- self::$serverDBConnection = NewMySQLi();
- }
- }
- public function onOpen(ConnectionInterface $conn){
- $this->clients->attach($conn);
- }
- private function pushDataToClients($data, $ignoreThisClient = false){ // $ignoreThisClient should be a ConnectionInterface object to not send data to
- // $data should be a string
- foreach($this->clients as $client){
- if ($client !== $ignoreThisClient){
- $client->send($data);
- }
- }
- }
- private function pushDataToClientsByResourceIDs($data, $resourceIDs){ // send array of ids
- // $data should be a string
- foreach($this->clients as $client){
- if (array_search($client->resourceId, $resourceIDs) !== false){
- $client->send($data);
- }
- }
- }
- private function pushDataToUserID($data, $userID){
- // $data should be a string
- $userID = (int)$userID;
- if (isset(self::$connectedUsers[$userID])){
- // We've verified the user is connected
- $resourceIDs = self::$connectedUsers[$userID]['resourceIDs'];
- foreach($this->clients as $client){
- if (array_search($client->resourceId, $resourceIDs) !== false){
- // 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.
- $client->send($data);
- }
- }
- }
- }
- private function attachClient($userObject, $resourceID){
- // First, we see if they already have a tab/window of the chat open
- $userID = $userObject->Get("id");
- self::$resourceIDLog[$resourceID] = $userID;
- if (!isset(self::$connectedUsers[$userID])){
- // Add their info to the table
- self::$connectedUsers[$userID] = array(
- "resourceIDs" => array($resourceID),
- "userObject"=>$userObject,
- "joinTime"=>time()
- );
- return true; // Means we need to tell existing connections to add a new user
- }else{
- // They already exist, so just add to their resource IDs
- array_push(
- self::$connectedUsers[$userID]['resourceIDs'],
- $resourceID
- );
- return false; // Do not tell existing clients about this user. They're already aware
- }
- return 0; // Should never happen
- }
- public function doesGamServerCacheExist($gameID){
- $gameID = (int)$gameID;
- if (isset( self::$openGames[$gameID] )){
- return true;
- }else{
- return false;
- }
- }
- public function updateRegisteredPlayers(\unoGame $game){
- $gameID = (int)$game::$gameRow['id'];
- $hostID = (int)$game::$gameRow['hostUserID'];
- $players = array(
- $hostID,
- (int)$game::$gameRow['player2'],
- (int)$game::$gameRow['player3'],
- (int)$game::$gameRow['player4'],
- );
- foreach($players as $index=>$userID){
- if ($userID !== 0){
- self::$openGames[$gameID]['registeredPlayerIDs'][$userID] = array(
- "cardsInHand"=>array()
- );
- }
- }
- }
- public function dealCards($gameID){
- $gameID = (int)$gameID;
- $gameCache = self::$openGames[$gameID];
- $players = $gameCache['registeredPlayerIDs'];
- foreach($players as $userID => $pData){
- self::$openGames[$gameID]['registeredPlayerIDs'][$userID]['cardsInHand'] = array_rand(self::$unoCards, 8);
- }
- print("Dealt cards \n");
- }
- public function createServerCacheOfGame(\unoGame $game){
- $gameID = (int)$game::$gameRow['id'];
- $hasPassword = (bool)$game::$gameRow['passwordProtected'];
- $password = (string)$game::$gameRow['roomPassword'];
- $hostID = (int)$game::$gameRow['hostUserID'];
- $gameArray = array(
- "hasPassword"=>$hasPassword,
- "roomPassword"=>$password,
- "userIDTurn"=>$hostID,
- "currentFieldCardID"=>array_rand(self::$unoCards, 1),
- "registeredPlayerIDs"=>array()
- );
- self::$openGames[$gameID] = $gameArray;
- }
- public function sendDataToPlayers($gameID, $data){
- $gameID = (int)$gameID;
- $gameCache = self::$openGames[$gameID];
- $players = $gameCache['registeredPlayerIDs'];
- $playersJSON = json_encode($players);
- $playerResourceIDs = array();
- foreach($players as $userID => $pData){
- if (isset(self::$connectedUsers[$userID])){
- $resources = self::$connectedUsers[$userID]['resourceIDs'];
- $playerResourceIDs = array_merge($playerResourceIDs, $resources);
- }
- }
- $this->pushDataToClientsByResourceIDs($data, $playerResourceIDs);
- }
- public function getInitialData($gameID){
- $gameID = (int)$gameID;
- $gameCache = self::$openGames[$gameID];
- $thisGame = new \unoGame($gameID);
- $players = $gameCache['registeredPlayerIDs'];
- $playerData = array();
- foreach($players as $userID => $pData){
- $cardsInHand = $pData['cardsInHand'];
- print_r($cardsInHand);
- $user = new \User((int)$userID, true); // self::$connectedUsers[$userID]['userObject']; -> They might not be on the server, this breaks shit.
- array_push($playerData, array(
- "id"=>$user->get("id"),
- "username"=>$user->get("name"),
- "hand"=>$cardsInHand
- ));
- }
- $data = array(
- "action"=>"initialData",
- "gameStarted"=>(bool)((int)$thisGame::$gameRow['gameBegan']),
- "currentFieldCardID" => $gameCache['currentFieldCardID'],
- "userIDTurn" => $gameCache['userIDTurn'],
- "userData"=>$playerData,
- );
- return $data;
- }
- public function onMessage(ConnectionInterface $from, $json) {
- $ip = $from->remoteAddress;
- $rObj = json_decode($json, true); // rObj = Received Object
- $util = new \Util();
- if (is_array($rObj)){
- $requestedAction = (string)$rObj['action'];
- $loginToken = (string)$rObj['userToken'];
- $gameID = (int)$rObj['gameID'];
- $thisUser = new \User($loginToken, true);
- $thisGame = new \unoGame($gameID);
- if ($thisUser->doesExist()){
- if ($requestedAction === "attachClient"){
- // Be sure the server has a gameID array ready. If not, make one (so long as the game actually exists)
- $this->attachClient($thisUser, $from->resourceId);
- if ($thisGame->gameExists === true){
- print("Game $gameID exists. \n");
- if ($this->doesGamServerCacheExist($gameID) === false){
- print("No server cache of game exists. Creating game.\n");
- $this->createServerCacheOfGame($thisGame);
- }
- $this->updateRegisteredPlayers($thisGame);
- $this->pushDataToUserID(
- json_encode($this->getInitialData($gameID)),
- $thisUser->get("id")
- );
- }else{
- print("Game $gameID does not exist. \n");
- }
- }elseif($requestedAction === "dealCards"){
- if ($thisGame->gameExists === true){
- if ($this->doesGamServerCacheExist($gameID) !== false){
- print("Attempting to deal cards. \n");
- $hasAlreadyDealt = $thisGame::$gameRow['gameBegan'];
- if ( (int)$hasAlreadyDealt === 0){
- if ( $thisGame->isUserHost($thisUser->get("id"))){
- $thisGame->update("gameBegan", "i", 1);
- $this->dealCards($gameID);
- $this->sendDataToPlayers(
- $gameID,
- json_encode($this->getInitialData($gameID))
- );
- }else{
- print("User attempting to deal is not the host. \n");
- }
- }else{
- print("Cards already dealt. \n");
- }
- }
- }
- }
- }
- }
- }
- public function onClose(ConnectionInterface $conn) {
- $this->clients->detach($conn);
- $resourceID = $conn->resourceId;
- $Util = new \Util();
- // Funny thing, I used to do this by searching the entire array of connectedUsers for the matching resourceId
- // But then I just made an array that matched each resourceId to a UserID
- if (!isset(self::$resourceIDLog[$resourceID])){
- return;
- }
- $userID = self::$resourceIDLog[$resourceID];
- if (!isset(self::$connectedUsers[$userID])){
- return;
- }
- $connectedUser = self::$connectedUsers[$userID];
- $indexID = array_search($resourceID,$connectedUser['resourceIDs']);
- unset($connectedUser['resourceIDs'][$indexID]);
- print("Disconnected $userID \n");
- // re-index the stored array and fill in any gaps
- self::$connectedUsers[$userID]['resourceIDs'] = array_values($connectedUser['resourceIDs']);
- // Do they still have any tabs still open?
- if (count($connectedUser['resourceIDs']) === 0){
- // They're gone
- // Inform other clients to remove them and remove them from the connected users
- unset(self::$connectedUsers[$userID]);
- $packet = array(
- "serverRequest"=>"disconnectUser",
- "userID"=>$userID
- );
- $this->pushDataToClients( json_encode($packet) );
- }else{
- // They are still in the chat
- }
- }
- public function onError(ConnectionInterface $conn, \Exception $e) {
- $conn->close();
- }
- public function onServerCommunication($dataString){
- $dataArray = json_decode($Data, true);
- if (is_array($dataArray)){
- $authenticationCode = $dataArray['IdentityCode'];
- if ($authenticationCode === "AaMCServer"){
- // verified this is being sent from the server
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement