Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 8th, 2012  |  syntax: None  |  size: 11.13 KB  |  hits: 17  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. using UnityEngine;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5.  
  6. using Sfs2X;
  7. using Sfs2X.Core;
  8. using Sfs2X.Entities;
  9. using Sfs2X.Entities.Variables;
  10. using Sfs2X.Entities.Data;
  11. using Sfs2X.Requests;
  12. using Sfs2X.Logging;
  13.  
  14.  
  15. public class Lobby : MonoBehaviour {
  16.  
  17.         private SmartFox smartFox;
  18.         private string zone = "m113kph";
  19.     private string serverName = "129.21.29.6";
  20.         private int serverPort = 9933;
  21.         public string username = "";
  22.         private string loginErrorMessage = "";
  23.         private bool isLoggedIn;
  24.        
  25.         private string newMessage = "";
  26.         //private ArrayList messages = new ArrayList();
  27.                
  28.         public GUISkin gSkin;
  29.        
  30.         //keep track of room we're in
  31.         private Room currentActiveRoom;
  32.         public Room CurrentActiveRoom{ get {return currentActiveRoom;} }
  33.                                
  34.         private Vector2 roomScrollPosition, userScrollPosition, chatScrollPosition;
  35.         private int roomSelection = -1;   //For clicking on list box
  36.         private string[] roomNameStrings; //Names of rooms
  37.         private string[] roomFullStrings; //Names and descriptions
  38.         private int screenW;
  39.         private int screenH;
  40.  
  41.         //      Chat stuff
  42.         public Chat chat;
  43.        
  44.        
  45.         void Start()
  46.         {      
  47.                
  48.                 chat = GameObject.Find("Chat").GetComponent<Chat>();
  49.                 Security.PrefetchSocketPolicy(serverName, serverPort);
  50.                 bool debug = true;
  51.                 if (SmartFoxConnection.IsInitialized)
  52.                 {
  53.                         //If we've been here before, the connection has already been initialized.
  54.                         //and we don't want to re-create this scene, therefore destroy the new one
  55.                         smartFox = SmartFoxConnection.Connection;
  56.                         //Destroy(gameObject);
  57.                         chat.isVisible = true;
  58.                         username = smartFox.MySelf.Name;
  59.                         currentActiveRoom = smartFox.LastJoinedRoom;
  60.                         PrepareLobby();
  61.  
  62.                 }
  63.                 else
  64.                 {
  65.                         //If this is the first time we've been here, keep the Lobby around
  66.                         //even when we load another scene, this will remain with all its data
  67.                         smartFox = new SmartFox(debug);
  68.                         //DontDestroyOnLoad(gameObject);
  69.                        
  70.                         //Set up chat
  71.                         chat.game = false;
  72.                         chat.isVisible = false;
  73.                 }
  74.                
  75.                 smartFox.AddLogListener(LogLevel.INFO, OnDebugMessage);
  76.                 screenW = Screen.width;
  77.                 screenH = Screen.height;
  78.         }
  79.        
  80.         void OnEnable()
  81.         {
  82.                                
  83.                 chat = GameObject.Find("Chat").GetComponent<Chat>();
  84.         }
  85.        
  86.         private void AddEventListeners() {
  87.                
  88.                 smartFox.RemoveAllEventListeners();
  89.                
  90.                 smartFox.AddEventListener(SFSEvent.CONNECTION, OnConnection);
  91.                 smartFox.AddEventListener(SFSEvent.CONNECTION_LOST, OnConnectionLost);
  92.                 smartFox.AddEventListener(SFSEvent.LOGIN, OnLogin);
  93.                 smartFox.AddEventListener(SFSEvent.LOGIN_ERROR, OnLoginError);
  94.                 smartFox.AddEventListener(SFSEvent.LOGOUT, OnLogout);
  95.                 smartFox.AddEventListener(SFSEvent.ROOM_JOIN, OnJoinRoom);
  96.                 smartFox.AddEventListener(SFSEvent.ROOM_ADD, OnRoomAdded);
  97.                 smartFox.AddEventListener(SFSEvent.ROOM_CREATION_ERROR, OnRoomCreationError);
  98.                 smartFox.AddEventListener(SFSEvent.USER_ENTER_ROOM, OnUserEnterRoom);
  99.                 smartFox.AddEventListener(SFSEvent.USER_EXIT_ROOM, OnUserLeaveRoom);
  100.                 smartFox.AddEventListener(SFSEvent.USER_COUNT_CHANGE, OnUserCountChange);
  101.         }
  102.        
  103.         void FixedUpdate() {
  104.                 //this is necessary to have any smartfox action!
  105.                 smartFox.ProcessEvents();
  106.         }
  107.        
  108.         private void UnregisterSFSSceneCallbacks() {
  109.                 smartFox.RemoveAllEventListeners();
  110.         }
  111.        
  112.         public void OnConnection(BaseEvent evt) {
  113.                 bool success = (bool)evt.Params["success"];
  114.                 string error = (string)evt.Params["errorMessage"];
  115.                
  116.                 Debug.Log("On Connection callback got: " + success + " (error? : <" + error + ">)");
  117.  
  118.                 if (success) {
  119.                         SmartFoxConnection.Connection = smartFox;
  120.  
  121.                         Debug.Log("Sending login request");
  122.                         smartFox.Send(new LoginRequest(username, "", zone));
  123.  
  124.                 }
  125.         }
  126.  
  127.         public void OnConnectionLost(BaseEvent evt) {
  128.                 Debug.Log("OnConnectionLost");
  129.                 isLoggedIn = false;
  130.                 chat.isVisible = false;
  131.                 UnregisterSFSSceneCallbacks();
  132.                 currentActiveRoom = null;
  133.                 roomSelection = -1;    
  134.                 //Application.LoadLevel("The Lobby");
  135.         }
  136.  
  137.         // Various SFS callbacks
  138.         public void OnLogin(BaseEvent evt) {
  139.                 try {
  140.                         if (evt.Params.ContainsKey("success") && !(bool)evt.Params["success"]) {
  141.                                 loginErrorMessage = (string)evt.Params["errorMessage"];
  142.                                 Debug.Log("Login error: "+loginErrorMessage);
  143.                         }
  144.                         else {
  145.                                 Debug.Log("Logged in successfully");
  146.                                 PrepareLobby();
  147.                                 chat.isVisible = true;
  148.                                 chat.restart();
  149.  
  150.                         }
  151.                 }
  152.                 catch (Exception ex) {
  153.                         Debug.Log("Exception handling login request: "+ex.Message+" "+ex.StackTrace);
  154.                 }
  155.         }
  156.  
  157.         public void OnLoginError(BaseEvent evt) {
  158.                 Debug.Log("Login error: "+(string)evt.Params["errorMessage"]);
  159.         }
  160.        
  161.         void OnLogout(BaseEvent evt) {
  162.                 chat.isVisible = false;
  163.                 Debug.Log("OnLogout");
  164.                 isLoggedIn = false;
  165.                 currentActiveRoom = null;
  166.                 smartFox.Disconnect();
  167.         }
  168.        
  169.         public void OnDebugMessage(BaseEvent evt) {
  170.                 string message = (string)evt.Params["message"];
  171.                 Debug.Log("[SFS DEBUG] " + message);
  172.         }
  173.        
  174.        
  175.         public void OnRoomAdded(BaseEvent evt)
  176.         {
  177.                 Room room = (Room)evt.Params["room"];
  178.                 SetupRoomList();
  179.                 Debug.Log("Room added: "+room.Name);
  180.         }
  181.         public void OnRoomCreationError(BaseEvent evt)
  182.         {
  183.                 Debug.Log("Error creating room");
  184.         }
  185.        
  186.         public void OnJoinRoom(BaseEvent evt)
  187.         {
  188.                 Room room = (Room)evt.Params["room"];
  189.                 currentActiveRoom = room;
  190.                 Debug.Log("joined "+room.Name);
  191.                 if(room.Name=="The Lobby" )     {
  192.                         chat.isVisible = true;
  193.                         //Application.LoadLevel(room.Name);
  194.                         }
  195.                 else {
  196.                         chat.isVisible = false;
  197.                         Application.LoadLevel("GameRoomLobby");
  198.                         smartFox.Send(new SpectatorToPlayerRequest());
  199.                 }
  200.         }
  201.        
  202.         public void OnUserEnterRoom(BaseEvent evt) {
  203.                 User user = (User)evt.Params["user"];
  204.                 //      messages.Add( user.Name + " has entered the room.");
  205.                 chat.receiveMessage(user.Name + " has entered the room.");
  206.         }
  207.  
  208.         private void OnUserLeaveRoom(BaseEvent evt) {
  209.                 User user = (User)evt.Params["user"];
  210.                 if(user.Name!=username){
  211.                         //      messages.Add( user.Name + " has left the room.");
  212.                         chat.receiveMessage(user.Name + " has left the room.");
  213.                 }      
  214.         }
  215.  
  216.         public void OnUserCountChange(BaseEvent evt) {
  217.                 Room room = (Room)evt.Params["room"];
  218.                 if (room.IsGame ) {
  219.                         SetupRoomList();
  220.                 }
  221.         }
  222.        
  223.        
  224.         //PrepareLobby is called from OnLogin, the callback for login
  225.         //so we can be assured that login was successful
  226.         private void PrepareLobby() {
  227.                 Debug.Log("Setting up the lobby");
  228.                 SetupRoomList();
  229.                 isLoggedIn = true;
  230.         }
  231.        
  232.        
  233.         void OnGUI() {
  234.                 if (smartFox == null) return;
  235.                 screenW = Screen.width;
  236.                 GUI.skin = gSkin;
  237.                
  238.                
  239.                 print(isLoggedIn);
  240.                 // Login
  241.                 if (!isLoggedIn) {
  242.                         DrawLoginGUI();
  243.                 }
  244.                
  245.                 else if (currentActiveRoom != null)
  246.                 {
  247.                         // ****** Show full interface only in the Lobby ******* //
  248.                         if(currentActiveRoom.Name == "The Lobby")
  249.                         {
  250.                                 DrawLobbyGUI();
  251.                                 DrawRoomsGUI();
  252.                         }
  253.                 }
  254.                
  255.         }
  256.        
  257.        
  258.         private void DrawLoginGUI(){
  259.                 GUI.Label(new Rect(2, -2, 680, 70), "");
  260.  
  261.                 int positionX = screenW / 2 - 100;
  262.                 int positionY = screenH / 2 - 100;
  263.                 GUI.Label(new Rect(positionX, positionY, 100, 100), "Username: ");
  264.                 username = GUI.TextField(new Rect(positionX + 100, positionY, 200, 20), username, 25);
  265.        
  266.                 //GUI.Label(new Rect(10, 180, 100, 100), "Server: ");
  267.                 //serverName = GUI.TextField(new Rect(100, 180, 200, 20), serverName, 25);
  268.  
  269.                 //GUI.Label(new Rect(10, 210, 100, 100), "Port: ");
  270.                 //serverPort = int.Parse(GUI.TextField(new Rect(100, 210, 200, 20), serverPort.ToString(), 4));
  271.  
  272.                 GUI.Label(new Rect(10, 240, 100, 100), loginErrorMessage);
  273.  
  274.                 if (GUI.Button(new Rect(positionX + 100, positionY + 90, 100, 24), "Login")  ||
  275.             (Event.current.type == EventType.keyDown && Event.current.character == '\n'))
  276.                 {
  277.                         if(smartFox.IsConnected)
  278.                         {
  279.                                 smartFox.Disconnect();
  280.                                 smartFox.RemoveAllEventListeners();
  281.                         }
  282.                         AddEventListeners();
  283.                         smartFox.Connect(serverName, serverPort);
  284.                 }      
  285.         }
  286.                        
  287.         private void DrawLobbyGUI(){
  288.                 GUI.Label(new Rect(2, -2, 680, 70), "");
  289.                 DrawUsersGUI();
  290.                
  291.                 // Logout button
  292.                 if(GUI.Button (new Rect (screenW - 115, 20, 85, 24), "Logout")) {
  293.                         smartFox.Send( new LogoutRequest() );
  294.                         isLoggedIn = false;
  295.                         chat.isVisible = false;
  296.                         //chat.receiveMessage("logout");
  297.                 }
  298.         }
  299.                
  300.                
  301.         private void DrawUsersGUI(){
  302.                 GUI.Box (new Rect (screenW - 200, 80, 180, 170), "Users");
  303.                 GUILayout.BeginArea (new Rect (screenW - 190, 110, 150, 160));
  304.                         userScrollPosition = GUILayout.BeginScrollView (userScrollPosition, GUILayout.Width (150), GUILayout.Height (150));
  305.                         GUILayout.BeginVertical ();
  306.                        
  307.                                 List<User> userList = currentActiveRoom.UserList;
  308.                                 foreach (User user in userList) {
  309.                                         GUILayout.Label (user.Name);
  310.                                 }
  311.                         GUILayout.EndVertical ();
  312.                         GUILayout.EndScrollView ();
  313.                 GUILayout.EndArea ();
  314.         }
  315.        
  316.         private void DrawRoomsGUI(){
  317.                 roomSelection = -1;
  318.                 GUI.Box (new Rect (screenW - 200, 260, 180, 130), "Room List");
  319.                 GUILayout.BeginArea (new Rect (screenW - 190, 290, 180, 150));
  320.                         if (smartFox.RoomList.Count >= 1) {            
  321.                                 roomScrollPosition = GUILayout.BeginScrollView (roomScrollPosition, GUILayout.Width (180), GUILayout.Height (130));
  322.                                         roomSelection = GUILayout.SelectionGrid (roomSelection, roomFullStrings, 1,"RoomList");
  323.                                        
  324.                                         //works... some duplicate code... but it works
  325.                                         if (roomSelection >= 0 && roomNameStrings[roomSelection] != currentActiveRoom.Name) {
  326.                                                 if(smartFox.GetRoomByName(roomNameStrings[roomSelection]).ContainsVariable("isplaying") == false)
  327.                                                 {
  328.                                                                 smartFox.Send(new JoinRoomRequest(roomNameStrings[roomSelection]));
  329.                                                 }else
  330.                                                 {
  331.                                                         if(smartFox.GetRoomByName(roomNameStrings[roomSelection]).GetVariable("isplaying").GetBoolValue() == false)
  332.                                                         {
  333.                                                                 smartFox.Send(new JoinRoomRequest(roomNameStrings[roomSelection]));
  334.  
  335.                                                         }
  336.                                                 }
  337.                                         }
  338.                                 GUILayout.EndScrollView ();
  339.                                
  340.                         } else {
  341.                                 GUILayout.Label ("No rooms available to join");
  342.                         }
  343.                        
  344.                         // Game Room button
  345.                         if (currentActiveRoom.Name == "The Lobby"){
  346.                                 if (GUI.Button (new Rect (80, 110, 85, 24), "Make Game")) {            
  347.                                         // ****** Create new room ******* //
  348.                                         Debug.Log("new room "+username + "'s Room");
  349.                                        
  350.                                         //let smartfox take care of error if duplicate name
  351.                                         RoomSettings settings = new RoomSettings(username + "'s Room");
  352.                                         // how many players allowed
  353.                                         settings.MaxUsers = 12;
  354.                                         settings.IsGame = true;
  355.                                        
  356.                                         //store indices into color arrays for setting user colors, delete as used
  357.                                         SFSArray nums = new SFSArray();
  358.                                         for(int i=0; i<5;i++){
  359.                                                 nums.AddInt(i);
  360.                                         }
  361.                                         SFSRoomVariable colorNums = new SFSRoomVariable("colorNums", nums);
  362.                                         settings.Variables.Add(colorNums);
  363.                                         settings.MaxVariables = 20;//short.MaxValue;
  364.                                         smartFox.Send(new CreateRoomRequest(settings,false));
  365.                                 }
  366.                         }
  367.                 GUILayout.EndArea();
  368.         }
  369.        
  370.        
  371.         private void SetupRoomList () {
  372.                 List<string> rooms = new List<string> ();
  373.                 List<string> roomsFull = new List<string> ();
  374.                
  375.                 List<Room> allRooms = smartFox.RoomManager.GetRoomList();
  376.                
  377.                 foreach (Room room in allRooms) {
  378.                         rooms.Add(room.Name);
  379.                         roomsFull.Add(room.Name + " (" + room.UserCount + "/" + room.MaxUsers + ")");
  380.                 }
  381.                
  382.                 roomNameStrings = rooms.ToArray();
  383.                 roomFullStrings = roomsFull.ToArray();
  384.                
  385.                 if (smartFox.LastJoinedRoom==null) {
  386.                         smartFox.Send(new JoinRoomRequest("The Lobby"));
  387.                 }
  388.         }
  389. }