- using UnityEngine;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using Sfs2X;
- using Sfs2X.Core;
- using Sfs2X.Entities;
- using Sfs2X.Entities.Variables;
- using Sfs2X.Entities.Data;
- using Sfs2X.Requests;
- using Sfs2X.Logging;
- public class Lobby : MonoBehaviour {
- private SmartFox smartFox;
- private string zone = "m113kph";
- private string serverName = "129.21.29.6";
- private int serverPort = 9933;
- public string username = "";
- private string loginErrorMessage = "";
- private bool isLoggedIn;
- private string newMessage = "";
- //private ArrayList messages = new ArrayList();
- public GUISkin gSkin;
- //keep track of room we're in
- private Room currentActiveRoom;
- public Room CurrentActiveRoom{ get {return currentActiveRoom;} }
- private Vector2 roomScrollPosition, userScrollPosition, chatScrollPosition;
- private int roomSelection = -1; //For clicking on list box
- private string[] roomNameStrings; //Names of rooms
- private string[] roomFullStrings; //Names and descriptions
- private int screenW;
- private int screenH;
- // Chat stuff
- public Chat chat;
- void Start()
- {
- chat = GameObject.Find("Chat").GetComponent<Chat>();
- Security.PrefetchSocketPolicy(serverName, serverPort);
- bool debug = true;
- if (SmartFoxConnection.IsInitialized)
- {
- //If we've been here before, the connection has already been initialized.
- //and we don't want to re-create this scene, therefore destroy the new one
- smartFox = SmartFoxConnection.Connection;
- //Destroy(gameObject);
- chat.isVisible = true;
- username = smartFox.MySelf.Name;
- currentActiveRoom = smartFox.LastJoinedRoom;
- PrepareLobby();
- }
- else
- {
- //If this is the first time we've been here, keep the Lobby around
- //even when we load another scene, this will remain with all its data
- smartFox = new SmartFox(debug);
- //DontDestroyOnLoad(gameObject);
- //Set up chat
- chat.game = false;
- chat.isVisible = false;
- }
- smartFox.AddLogListener(LogLevel.INFO, OnDebugMessage);
- screenW = Screen.width;
- screenH = Screen.height;
- }
- void OnEnable()
- {
- chat = GameObject.Find("Chat").GetComponent<Chat>();
- }
- private void AddEventListeners() {
- smartFox.RemoveAllEventListeners();
- smartFox.AddEventListener(SFSEvent.CONNECTION, OnConnection);
- smartFox.AddEventListener(SFSEvent.CONNECTION_LOST, OnConnectionLost);
- smartFox.AddEventListener(SFSEvent.LOGIN, OnLogin);
- smartFox.AddEventListener(SFSEvent.LOGIN_ERROR, OnLoginError);
- smartFox.AddEventListener(SFSEvent.LOGOUT, OnLogout);
- smartFox.AddEventListener(SFSEvent.ROOM_JOIN, OnJoinRoom);
- smartFox.AddEventListener(SFSEvent.ROOM_ADD, OnRoomAdded);
- smartFox.AddEventListener(SFSEvent.ROOM_CREATION_ERROR, OnRoomCreationError);
- smartFox.AddEventListener(SFSEvent.USER_ENTER_ROOM, OnUserEnterRoom);
- smartFox.AddEventListener(SFSEvent.USER_EXIT_ROOM, OnUserLeaveRoom);
- smartFox.AddEventListener(SFSEvent.USER_COUNT_CHANGE, OnUserCountChange);
- }
- void FixedUpdate() {
- //this is necessary to have any smartfox action!
- smartFox.ProcessEvents();
- }
- private void UnregisterSFSSceneCallbacks() {
- smartFox.RemoveAllEventListeners();
- }
- public void OnConnection(BaseEvent evt) {
- bool success = (bool)evt.Params["success"];
- string error = (string)evt.Params["errorMessage"];
- Debug.Log("On Connection callback got: " + success + " (error? : <" + error + ">)");
- if (success) {
- SmartFoxConnection.Connection = smartFox;
- Debug.Log("Sending login request");
- smartFox.Send(new LoginRequest(username, "", zone));
- }
- }
- public void OnConnectionLost(BaseEvent evt) {
- Debug.Log("OnConnectionLost");
- isLoggedIn = false;
- chat.isVisible = false;
- UnregisterSFSSceneCallbacks();
- currentActiveRoom = null;
- roomSelection = -1;
- //Application.LoadLevel("The Lobby");
- }
- // Various SFS callbacks
- public void OnLogin(BaseEvent evt) {
- try {
- if (evt.Params.ContainsKey("success") && !(bool)evt.Params["success"]) {
- loginErrorMessage = (string)evt.Params["errorMessage"];
- Debug.Log("Login error: "+loginErrorMessage);
- }
- else {
- Debug.Log("Logged in successfully");
- PrepareLobby();
- chat.isVisible = true;
- chat.restart();
- }
- }
- catch (Exception ex) {
- Debug.Log("Exception handling login request: "+ex.Message+" "+ex.StackTrace);
- }
- }
- public void OnLoginError(BaseEvent evt) {
- Debug.Log("Login error: "+(string)evt.Params["errorMessage"]);
- }
- void OnLogout(BaseEvent evt) {
- chat.isVisible = false;
- Debug.Log("OnLogout");
- isLoggedIn = false;
- currentActiveRoom = null;
- smartFox.Disconnect();
- }
- public void OnDebugMessage(BaseEvent evt) {
- string message = (string)evt.Params["message"];
- Debug.Log("[SFS DEBUG] " + message);
- }
- public void OnRoomAdded(BaseEvent evt)
- {
- Room room = (Room)evt.Params["room"];
- SetupRoomList();
- Debug.Log("Room added: "+room.Name);
- }
- public void OnRoomCreationError(BaseEvent evt)
- {
- Debug.Log("Error creating room");
- }
- public void OnJoinRoom(BaseEvent evt)
- {
- Room room = (Room)evt.Params["room"];
- currentActiveRoom = room;
- Debug.Log("joined "+room.Name);
- if(room.Name=="The Lobby" ) {
- chat.isVisible = true;
- //Application.LoadLevel(room.Name);
- }
- else {
- chat.isVisible = false;
- Application.LoadLevel("GameRoomLobby");
- smartFox.Send(new SpectatorToPlayerRequest());
- }
- }
- public void OnUserEnterRoom(BaseEvent evt) {
- User user = (User)evt.Params["user"];
- // messages.Add( user.Name + " has entered the room.");
- chat.receiveMessage(user.Name + " has entered the room.");
- }
- private void OnUserLeaveRoom(BaseEvent evt) {
- User user = (User)evt.Params["user"];
- if(user.Name!=username){
- // messages.Add( user.Name + " has left the room.");
- chat.receiveMessage(user.Name + " has left the room.");
- }
- }
- public void OnUserCountChange(BaseEvent evt) {
- Room room = (Room)evt.Params["room"];
- if (room.IsGame ) {
- SetupRoomList();
- }
- }
- //PrepareLobby is called from OnLogin, the callback for login
- //so we can be assured that login was successful
- private void PrepareLobby() {
- Debug.Log("Setting up the lobby");
- SetupRoomList();
- isLoggedIn = true;
- }
- void OnGUI() {
- if (smartFox == null) return;
- screenW = Screen.width;
- GUI.skin = gSkin;
- print(isLoggedIn);
- // Login
- if (!isLoggedIn) {
- DrawLoginGUI();
- }
- else if (currentActiveRoom != null)
- {
- // ****** Show full interface only in the Lobby ******* //
- if(currentActiveRoom.Name == "The Lobby")
- {
- DrawLobbyGUI();
- DrawRoomsGUI();
- }
- }
- }
- private void DrawLoginGUI(){
- GUI.Label(new Rect(2, -2, 680, 70), "");
- int positionX = screenW / 2 - 100;
- int positionY = screenH / 2 - 100;
- GUI.Label(new Rect(positionX, positionY, 100, 100), "Username: ");
- username = GUI.TextField(new Rect(positionX + 100, positionY, 200, 20), username, 25);
- //GUI.Label(new Rect(10, 180, 100, 100), "Server: ");
- //serverName = GUI.TextField(new Rect(100, 180, 200, 20), serverName, 25);
- //GUI.Label(new Rect(10, 210, 100, 100), "Port: ");
- //serverPort = int.Parse(GUI.TextField(new Rect(100, 210, 200, 20), serverPort.ToString(), 4));
- GUI.Label(new Rect(10, 240, 100, 100), loginErrorMessage);
- if (GUI.Button(new Rect(positionX + 100, positionY + 90, 100, 24), "Login") ||
- (Event.current.type == EventType.keyDown && Event.current.character == '\n'))
- {
- if(smartFox.IsConnected)
- {
- smartFox.Disconnect();
- smartFox.RemoveAllEventListeners();
- }
- AddEventListeners();
- smartFox.Connect(serverName, serverPort);
- }
- }
- private void DrawLobbyGUI(){
- GUI.Label(new Rect(2, -2, 680, 70), "");
- DrawUsersGUI();
- // Logout button
- if(GUI.Button (new Rect (screenW - 115, 20, 85, 24), "Logout")) {
- smartFox.Send( new LogoutRequest() );
- isLoggedIn = false;
- chat.isVisible = false;
- //chat.receiveMessage("logout");
- }
- }
- private void DrawUsersGUI(){
- GUI.Box (new Rect (screenW - 200, 80, 180, 170), "Users");
- GUILayout.BeginArea (new Rect (screenW - 190, 110, 150, 160));
- userScrollPosition = GUILayout.BeginScrollView (userScrollPosition, GUILayout.Width (150), GUILayout.Height (150));
- GUILayout.BeginVertical ();
- List<User> userList = currentActiveRoom.UserList;
- foreach (User user in userList) {
- GUILayout.Label (user.Name);
- }
- GUILayout.EndVertical ();
- GUILayout.EndScrollView ();
- GUILayout.EndArea ();
- }
- private void DrawRoomsGUI(){
- roomSelection = -1;
- GUI.Box (new Rect (screenW - 200, 260, 180, 130), "Room List");
- GUILayout.BeginArea (new Rect (screenW - 190, 290, 180, 150));
- if (smartFox.RoomList.Count >= 1) {
- roomScrollPosition = GUILayout.BeginScrollView (roomScrollPosition, GUILayout.Width (180), GUILayout.Height (130));
- roomSelection = GUILayout.SelectionGrid (roomSelection, roomFullStrings, 1,"RoomList");
- //works... some duplicate code... but it works
- if (roomSelection >= 0 && roomNameStrings[roomSelection] != currentActiveRoom.Name) {
- if(smartFox.GetRoomByName(roomNameStrings[roomSelection]).ContainsVariable("isplaying") == false)
- {
- smartFox.Send(new JoinRoomRequest(roomNameStrings[roomSelection]));
- }else
- {
- if(smartFox.GetRoomByName(roomNameStrings[roomSelection]).GetVariable("isplaying").GetBoolValue() == false)
- {
- smartFox.Send(new JoinRoomRequest(roomNameStrings[roomSelection]));
- }
- }
- }
- GUILayout.EndScrollView ();
- } else {
- GUILayout.Label ("No rooms available to join");
- }
- // Game Room button
- if (currentActiveRoom.Name == "The Lobby"){
- if (GUI.Button (new Rect (80, 110, 85, 24), "Make Game")) {
- // ****** Create new room ******* //
- Debug.Log("new room "+username + "'s Room");
- //let smartfox take care of error if duplicate name
- RoomSettings settings = new RoomSettings(username + "'s Room");
- // how many players allowed
- settings.MaxUsers = 12;
- settings.IsGame = true;
- //store indices into color arrays for setting user colors, delete as used
- SFSArray nums = new SFSArray();
- for(int i=0; i<5;i++){
- nums.AddInt(i);
- }
- SFSRoomVariable colorNums = new SFSRoomVariable("colorNums", nums);
- settings.Variables.Add(colorNums);
- settings.MaxVariables = 20;//short.MaxValue;
- smartFox.Send(new CreateRoomRequest(settings,false));
- }
- }
- GUILayout.EndArea();
- }
- private void SetupRoomList () {
- List<string> rooms = new List<string> ();
- List<string> roomsFull = new List<string> ();
- List<Room> allRooms = smartFox.RoomManager.GetRoomList();
- foreach (Room room in allRooms) {
- rooms.Add(room.Name);
- roomsFull.Add(room.Name + " (" + room.UserCount + "/" + room.MaxUsers + ")");
- }
- roomNameStrings = rooms.ToArray();
- roomFullStrings = roomsFull.ToArray();
- if (smartFox.LastJoinedRoom==null) {
- smartFox.Send(new JoinRoomRequest("The Lobby"));
- }
- }
- }