Exemplo n.º 1
0
        protected void Application_Start(object sender, EventArgs e)
        {
            //App_Start Configuration
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // Inform the game loop about its environment
            GameLoop.Instance.MachineName = System.Environment.MachineName.ToLower();
            GameLoop.Instance.VirtualPath = HostingEnvironment.ApplicationVirtualPath;
            GameLoop.Instance.SetEngine();

            // Get latest codes from the WebService
            var dms = new DescilMturkService(new PersistedRepository());
            dms.GetCodes();

            try
            {
                using (var db = new PersistedRepository()) { db.Log.AddEvent("ApplicationStart"); }
            }
            catch
            {
                //Swallow this
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Lets clients pull a client view object on init
        /// </summary>
        /// <returns>ClientView object</returns>
        public ClientView Init()
        {
            using (var db = new PersistedRepository())
            {
                // Diagnostics
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                // Get the grid the player sits on
                var grid = db.Grid.GetByConnectionId(Context.ConnectionId);
                if(grid != null)
                {
                    var initData = new ClientView
                    {
                        Round = 0,
                        OwnType = 0,
                        Move = false,
                        TypeChange = false,
                        Timeout = false,
                        LastPayoff = 0,
                        TotalPayoff = 0,
                        BlueCount = 0,
                        YellowCount = 0,
                        WhiteCount = 0,
                        OwnShare = "",
                        OtherShare = "",
                        CountDown = grid.IntroTimer
                    };
                    return initData;
                }
            }
            return null;
        }
Exemplo n.º 3
0
 public DescilMturkService(PersistedRepository repo, string serviceUrl, string serviceKey, string projectCode)
 {
     _db = repo;
     _serviceUrl = serviceUrl;
     _serviceKey = serviceKey;
     _projectCode = projectCode;
 }
Exemplo n.º 4
0
 /// <summary>
 /// Save page request time
 /// </summary>
 private void SavePageLog()
 {
     using (var db = new PersistedRepository())
     {
         db.Log.AddPageLog("default");
     }
 }
Exemplo n.º 5
0
 //CTOR
 public DescilMturkService(PersistedRepository repo)
 {
     _db = repo;
     var config = new Configuration();
     _serviceUrl = config.AppSettings("DescilServiceUrl");
     _serviceKey = config.AppSettings("DescilServiceKey");
     _projectCode = config.AppSettings("DescilProjectCode");
 }
Exemplo n.º 6
0
 /// <summary>
 /// Simply broadcast a message to all clients
 /// </summary>
 /// <param name="message">The message</param>
 public void Send(string message)
 {
     using (var db = new PersistedRepository())
     {
         var playerCode = db.Player.GetShortAccessCode(Context.ConnectionId);
         Clients.Group("admin").chatMessage(playerCode + " says: " + message);
         Clients.Group("playerview-" + playerCode).chatMessage(playerCode + " says: " + message);
     }
 }
Exemplo n.º 7
0
 /// <summary>
 /// Add entry to questions
 /// </summary>
 private void AddResponse(string accessCode)
 {
     using (var db = new PersistedRepository())
     {
         var question = db.Questionnaires.FirstOrDefault(q => q.AccessCode.Equals(LblAccessCode.Text));
         if (question == null)
         {
             db.Add(new Questionnaire { AccessCode = accessCode });
             db.Save();
         }
     }
 }
Exemplo n.º 8
0
 protected void Application_Error(object sender, EventArgs e)
 {
     try
     {
         // Get the exception object.
         Exception exc = Server.GetLastError();
         using (var db = new PersistedRepository()) { db.Log.AddEvent(exc.ToString() + " " + exc.InnerException.ToString() ); }
     }
     catch
     {
         //Swallow this
     }
 }
Exemplo n.º 9
0
 /// <summary>
 /// Save events / exceptions on this page
 /// </summary>
 private void SaveExceptions(string message, string method)
 {
     using (var db = new PersistedRepository())
     {
         var evlog = new EventLog
         {
             EventLogTime = DateTime.Now,
             Message = message,
             PlayerId = 0,
             AccessCode = LblAccessCode.Text,
             Page = "default",
             PageStep = 0,
             Method = method
         };
         db.Add(evlog);
     }
 }
Exemplo n.º 10
0
        /// <summary>
        /// Save hub message and sends it to admin
        /// </summary>
        /// <param name="gridId">GridId</param>
        /// <param name="accessCode">Access Code</param>
        /// <param name="message">The message</param>
        /// <returns></returns>
        private async Task HubMessageAsync(int gridId, string accessCode, string message, string method, long runtime, int verbosity)
        {
            using (var db = new PersistedRepository())
            {
                // Add to message log
                var messageLog = new MessageLog(gridId, accessCode, message, method, runtime);
                db.Add(messageLog);
                db.Save();
            }

            if(_segregLoop.Engine.Verbosity >= verbosity)
            {
                // Send to admin
                await AdminMessageAsync(message);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Fires when a client establishes a hub connection
        /// </summary>
        public override Task OnConnected()
        {
            using (var db = new PersistedRepository())
            {

                // Diagnostics
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                // User definition
                var connectionId = Context.ConnectionId;
                var isAdmin = false;
                var isAuthorized = false;

                // Collect client info
                var myContext = Context.Request.GetHttpContext();
                string ip = myContext.Request.ServerVariables["REMOTE_ADDR"];
                string browser = myContext.Request.Browser.Browser + " " + myContext.Request.Browser.Version;

                // Check for access code in cookie
                string accessCode = "";
                foreach (var c in myContext.Request.Cookies.AllKeys)
                {
                    if (c.Equals("SegRegCode")) accessCode = myContext.Request.Cookies["SegRegCode"].Value;
                }

                // Check for access code in querystring
                var qsAccessCode = Context.QueryString["a"];
                if(!string.IsNullOrEmpty(qsAccessCode))
                {
                    // Override if present
                    accessCode = qsAccessCode;
                }

                // Authorize: Check if AccessCode is present and valid, otherwise throw
                if (!string.IsNullOrEmpty(accessCode))
                {
                    isAuthorized = db.Code.IsAuthorized(accessCode);
                    if (!isAuthorized)
                    {
                        HubMessage(0, accessCode, accessCode.Substring(0, 8) + " access denied.", "OnConnected", stopwatch.ElapsedMilliseconds, 1);
                        //throw new Exception("Access denied");
                    }
                }
                else
                {
                    HubMessage(0, "", "Access denied.", "OnConnected", stopwatch.ElapsedMilliseconds, 2);
                    //throw new Exception("Access denied");
                }

                // Check query string for page url and add to groups
                var transport = Context.QueryString["transport"];
                var page = Context.QueryString["page"];
                if (!string.IsNullOrEmpty(page))
                {
                    // Add to groups
                    page = AddToPageGroup(connectionId, page);
                    // Test for admin
                    if (page.IndexOf("admin") >= 0) isAdmin = true;
                    if (page.IndexOf("gridview") >= 0) isAdmin = true;
                    if (page.IndexOf("playerview") >= 0) isAdmin = true;
                }

                // .Net clients
                //var clientType = Context.QueryString["segregclient"];
                //if (!string.IsNullOrEmpty(clientType))
                //{
                //    page = AddToPageGroup(connectionId, "admin");
                //    isAdmin = true;
                //    AdminMessage(connectionId.Substring(0, 8) + " connected as client.");
                //}

                //Add or update player
                var player = db.Player.GetByAccessCode(accessCode);
                if (player == null)
                {
                    // Add a new player to the database
                    db.Player.Add(accessCode, connectionId, true, isAdmin, ip, browser, transport);
                }
                else
                {
                    // Set connected if player is found
                    db.Player.SetConnectionStatus(accessCode, connectionId, true, isAdmin, ip, browser, transport);

                    // Check if he is/was in a specific room/game
                    // If the players grid is non static but he tries to connect to lobby waiting room
                    // We redirect him to the game room.
                    if (!player.Grid.IsStatic & page.IndexOf("game") < 0)
                    {
                        string url = db.Grid.GetUrl(_segregLoop.Engine, player.GridId);
                        url += "?a=" + accessCode;
                        Clients.Caller.navigate(url);
                    }
                }
            
                // AutoStart the game engine on admin entrance
                if (page == "admin") _segregLoop.AutoStart();
                //if (page == "lobby") _segregLoop.AutoStart();

                // Report back
                HubMessage(0, accessCode, accessCode.Substring(0, 8) + " connected", "OnConnected", stopwatch.ElapsedMilliseconds, 2);
                return base.OnConnected();
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Start grids
        /// </summary>
        private async Task StartGrids()
        {
            using (var db = new PersistedRepository())
            {
                //Diagnostics
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                // Set random number generator
                db.Random = _rng;

                // Loop over all grids that are setup and ready
                foreach (var g in db.Grids.Where(x => x.GridState == 3))
                {
                    // Add AI bots
                    db.Game.AddBots(g.GridId);

                    // Check number of players
                    var playerCount = db.Players.Count(p => p.GridId == g.GridId);
                    if (g.TotalPlayerCount != playerCount)
                    {
                        await GridMessageAsync(g, " *** Grid Excpetion: wrong number of players: " + playerCount.ToString(), "StartGrids", stopwatch.ElapsedMilliseconds, 1);
                        db.Grid.SetState(g.GridId, 9);
                        return;
                    }

                    // Assign Player Types
                    db.Game.AssignPlayerTypes(g.GridId);

                    // Move players into cells
                    db.Game.AssignPlayerToCells(g.GridId);

                    // Reset player flags
                    db.Game.ResetRealPlayerFlags(g.GridId);
                    
                    // Tell the grid startup is completed
                    db.Grid.SetState(g.GridId, 4);

                    // Report back
                    await GridMessageAsync(g, "started grid", "StartGrids", stopwatch.ElapsedMilliseconds, 1);
                }
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="target"></param>
        /// <param name="statusType"></param>
        public async Task SetPlayerStatus(string accessCode, string statusType)
        {
            using (var db = new PersistedRepository())
            {
                // Diagnostics
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                string message = "";
                var player = db.Players.FirstOrDefault(p => p.AccessCode.Substring(0, 8) == accessCode.Trim());
                if (player != null)
                {
                    switch(statusType)
                    {
                        case "zombie":
                            db.Player.SetZombie(player.AccessCode);
                            message = "Player " + accessCode + " marked as zombie.";
                            break;
                        case "exit":
                            await GridMove(player.AccessCode.Substring(0, 8), "3", "");
                            message = "Player " + accessCode + " moved to the exit.";
                            break;
                        case "swap":
                            db.Grid.SwapPlayer(player);
                            await GridMove(player.AccessCode.Substring(0, 8), "3", "");
                            message = "Player " + accessCode + " swapped and moved to the exit.";
                            break;
                    }
                }
                else
                {
                    message = "Player has not been found.";
                }

                Clients.Caller.chatMessage("PlayerCode:" + accessCode);

                // Report back
                Clients.Caller.chatMessage(message);
                await HubMessageAsync(0, "admin", "HubSetPlayerStatus: " + message, "SetPlayerStatus", stopwatch.ElapsedMilliseconds, 1);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Player requests a type change for the next round
        /// </summary>
        /// <param name="request">Change type if true, false otherwise</param>
        /// <param name="timeout">True if player didn't reach a decision withing the allotted time.</param>
        public Task TypeChange(bool request, bool timeout)
        {
            using (var db = new PersistedRepository())
            {
                // Diagnostics
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                // Save choice
                db.Player.RequestTypeChange(Context.ConnectionId, request, timeout);

                // Get AccessCode and Grid
                string accessCode = "";
                int gridId = 0;
                var player = db.Players.FirstOrDefault(p => p.ConnectionId == Context.ConnectionId);
                if (player != null)
                {
                    accessCode = player.AccessCode;
                    gridId = player.GridId;
                }

                var message = request.ToString();
                if (timeout) message = "timeout";
                message = db.Player.GetShortAccessCode(Context.ConnectionId) + " requested change: " + message;

                return HubMessageAsync(gridId, accessCode, message, "TypeChange", stopwatch.ElapsedMilliseconds, 2);
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Send a chat or script message to grids or players
        /// </summary>
        /// <param name="target">Grid or player identification</param>
        /// <param name="targetType">GridName, GridId, GridGrui, AccessCode, or PlayerId</param>
        /// <param name="message">The message</param>
        /// <param name="isScript">True if message is a script, false otherwise</param>
        public async Task ChatMessage(string target, int targetType, string message, bool isScript)
        {
            using (var db = new PersistedRepository())
            {
                // Diagnostics
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                switch (targetType)
                {
                    case 1: // GridId
                        int gridId = 0;
                        var isGridId = Int32.TryParse(target, out gridId);
                        var grid2 = db.Grids.FirstOrDefault(g => g.GridId == gridId);
                        if (grid2 != null)
                        {
                            if (grid2.IsStatic)
                            {
                                await SendMessageToGroup(grid2.GridName.ToLower(), message, isScript);
                            }
                            else
                            {
                                switch (grid2.GameTypeId)
                                {
                                    case 1:
                                        await SendMessageToGroup("mgame-" + grid2.GridGuid, message, isScript);
                                        break;
                                    case 2:
                                        await SendMessageToGroup("tgame-" + grid2.GridGuid, message, isScript);
                                        break;
                                    case 3:
                                        await SendMessageToGroup("rtmgame-" + grid2.GridGuid, message, isScript);
                                        break;
                                    case 4:
                                        await SendMessageToGroup("rttgame-" + grid2.GridGuid, message, isScript);
                                        break;
                                }
                            }
                        }
                        break;
                    case 2: // GridName
                        var grid1 = db.Grids.FirstOrDefault(g => g.GridName.Equals(target, StringComparison.OrdinalIgnoreCase));
                        if (grid1 != null)
                        {
                            await SendMessageToGroup(target.ToLower(), message, isScript);
                        }
                        break;
                    case 3: // GridGuid
                        var grid3 = db.Grids.FirstOrDefault(g => g.GridGuid.Equals(target, StringComparison.OrdinalIgnoreCase));
                        if (grid3 != null)
                        {
                            if (grid3.IsStatic)
                            {
                                await SendMessageToGroup(grid3.GridName.ToLower(), message, isScript);
                            }
                            else
                            {
                                switch (grid3.GameTypeId)
                                {
                                    case 1:
                                        await SendMessageToGroup("mgame-" + grid3.GridGuid, message, isScript);
                                        break;
                                    case 2:
                                        await SendMessageToGroup("tgame-" + grid3.GridGuid, message, isScript);
                                        break;
                                    case 3:
                                        await SendMessageToGroup("rtmgame-" + grid3.GridGuid, message, isScript);
                                        break;
                                    case 4:
                                        await SendMessageToGroup("rttgame-" + grid3.GridGuid, message, isScript);
                                        break;
                                }
                            }
                        }
                        break;
                    case 4: // AccessCode
                        var player1 = db.Players.FirstOrDefault(p => p.AccessCode.Substring(0, 8).Equals(target, StringComparison.OrdinalIgnoreCase));
                        if (player1 != null)
                        {
                            await SendMessageToPlayer(player1.ConnectionId, message, isScript);
                        }
                        break;
                    case 5: // PlayerId
                        int playerId = 0;
                        var isPlayerId = Int32.TryParse(target, out playerId);
                        var player2 = db.Players.FirstOrDefault(p => p.PlayerId == playerId);
                        if (player2 != null)
                        {
                            await SendMessageToPlayer(player2.ConnectionId, message, isScript);
                        }
                        break;
                    case 6: // ConnectionId
                        await SendMessageToPlayer(target, message, isScript);
                        break;
                }

                // Report back
                await HubMessageAsync(0, "admin", "HubChatMessage: " + target + ": Message has been sent.", "ChatMessage", stopwatch.ElapsedMilliseconds, 1);
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Push initial grid state to clients
        /// </summary>
        /// <returns></returns>
        private async Task PushInit()
        {
            using (var db = new PersistedRepository())
            {
                //Diagnostics
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                // Set common random number generator
                db.Random = _rng;

                // Loop over all grids that are setup and ready
                foreach (var g in db.Grids.Where(x => x.GridState == 4))
                {
                    // Initial round 0, just send neighborhood
                    if (!g.Players.Any(p => !p.IsReady))
                    {
                        // Get neighborhoods of all players
                        var nei = db.Game.Neighborhoods(g.GridId);

                        // Loop over a shuffled list of players
                        foreach (var p in g.Players.Shuffle(db.Random))
                        {
                            // Get player neighborhood
                            var pNei = nei.FirstOrDefault(n => n.PlayerId == p.PlayerId);
                            if (pNei != null)
                            {
                                // Set player neighborhood
                                p.Neighborhood = pNei;
                            }
                        }

                        // Save Neighborhoods to database
                        db.Save();

                        // Grid statistics
                        db.Grid.GridStats(g, nei);

                        // Logging
                        await LogGrids(g.GridId);

                        // Loop over a shuffled list of players
                        foreach (var p in g.Players.Where(p => !p.IsBot).Shuffle(db.Random))
                        {
                            // Compute client view state
                            var cv = db.View.GetClientStatus(g, p);

                            // Push state to clients
                            Clients.Client(p.ConnectionId).nextRound(cv);
                        }

                        // Reset player flags
                        db.Game.ResetPlayerFlags(g.GridId);

                        // Initial Push completed
                        db.Grid.SetState(g.GridId, 5);

                        // Report back to admin
                        await GridMessageAsync(g, "init push", "PushInit", stopwatch.ElapsedMilliseconds, 1); 
                    }
                }
            }
        }
Exemplo n.º 17
0
 //Ctor
 public LogController(SegregContext context, PersistedRepository repo)
 {
     ctx = context;
     db = repo;
 }
Exemplo n.º 18
0
        /// <summary>
        /// Answer of a ping-pong roundtrip test
        /// </summary>
        public Task PingBack()
        {
            using (var db = new PersistedRepository())
            {
                // Diagnostics
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                var player = db.Player.SetConnectionStatus(Context.ConnectionId, true);

                // Get AccessCode and Grid
                string accessCode = "";
                int gridId = 0;
                string message = "";
                if (player != null)
                {
                    accessCode = player.AccessCode;
                    gridId = player.GridId;
                    message = db.Player.GetShortAccessCode(Context.ConnectionId) + " ping pong";
                }
                else
                {
                    message = "Exception: Player not found: " + Context.ConnectionId; 
                }

                return HubMessageAsync(gridId, accessCode, message, "PingBack", stopwatch.ElapsedMilliseconds, 2);
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Relocation and type change choices of bots
        /// </summary>
        private async Task UpdateBots()
        {
            using (var db = new PersistedRepository())
            {
                //Diagnostics
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                // Set common random number generator
                db.Random = _rng;

                // Loop over all running grids
                foreach (var g in db.Grids.Where(x => x.GridState == 5 & x.BotCount > 0))
                {
                    // Relocation decisions
                    // Test if all real players are ready AND bots are not ready AND endround is not yet reached
                    if (!g.Players.Any(p => !p.IsBot & !p.IsReady) & !g.Players.Any(p => p.IsBot & p.IsReady) & g.Round < g.RoundCount & g.GameTypeId == 1)
                    {
                        var movedBots = 0;

                        // Let bots decide if they want to move
                        foreach (var p in g.Players.Where(x => x.IsBot))
                        {
                            // Try to move the bot
                            db.Game.BotRelocationDecision(g, p);
                            if (p.RequestMove) movedBots++;
                        }

                        // Save changes
                        db.Save();

                        // Report back
                        await GridMessageAsync(g, "bots moved (" + movedBots.ToString() + ")", "UpdateBots", stopwatch.ElapsedMilliseconds, 2);
                    }

                    // Type change decisions
                    // Test if all real players are ready AND bots are not ready AND endround is not yet reached
                    if (!g.Players.Any(p => !p.IsBot & !p.IsReady) & !g.Players.Any(p => p.IsBot & p.IsReady) & g.Round < g.RoundCount & g.GameTypeId == 2)
                    {
                        var changedBots = 0;

                        // Let bots decide if they want to move
                        foreach (var p in g.Players.Where(x => x.IsBot))
                        {
                            // Try to move the bot
                            db.Game.BotTypeChangeDecision(g, p);
                            if (p.RequestTypeChange) changedBots++;
                        }

                        // Save changes
                        db.Save();

                        // Report back
                        await GridMessageAsync(g, "bots changed (" + changedBots.ToString() + ")", "UpdateBots", stopwatch.ElapsedMilliseconds, 2);
                    }
                }
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Set the engine settings
        /// </summary>
        /// <param name="engineSettings">The EngineSettings Object</param>
        public Task SetEngine(EngineSettings engineSettings)
        {
            using (var db = new PersistedRepository())
            {
                // Diagnostics
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                bool wasRunning = false;
                // Stop loops if they are running
                if (_segregLoop.GameState == GameState.Started)
                {
                    wasRunning = true;
                    _segregLoop.StopGameLoop();
                    _segregLoop.StopEngineLoop();
                    //_segregLoop.StopSweepLoop();
                }

                // Update the engine in database
                db.Engine.Update(_segregLoop.Engine.EngineId, engineSettings);
                // Refresh Engine in Loop
                _segregLoop.SetEngine();

                // Restart loops if they were running
                if (wasRunning)
                {
                    _segregLoop.StartGameLoop();
                    _segregLoop.StartEngineLoop();
                    //_segregLoop.StartSweepLoop();
                }

                // Report back
                return HubMessage(0, "admin", "HubSetEngine", "SetEngine", stopwatch.ElapsedMilliseconds, 1);
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Start and stop the game loop
        /// </summary>
        /// <param name="start">If true game loop starts and stops otherwise</param>
        public void ToggleLoops(bool start)
        {
            using (var db = new PersistedRepository())
            {
                var engine = db.Engines.FirstOrDefault(e => e.EngineId == _segregLoop.Engine.EngineId);

                if (start)
                {
                    engine.GameLoop = true;
                    engine.EngineLoop = true;
                    //engine.SweepLoop = true;
                    db.Save();

                    _segregLoop.StartGameLoop();
                    _segregLoop.StartEngineLoop();
                    //_segregLoop.StartSweepLoop();
                }
                else
                {
                    engine.GameLoop = false;
                    engine.EngineLoop = false;
                    //engine.SweepLoop = false;
                    db.Save();

                    _segregLoop.StopGameLoop();
                    _segregLoop.StopEngineLoop();
                    //  _segregLoop.StopSweepLoop();
                }
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Request a ping of a specific client
        /// </summary>
        /// <param name="accessCode">The access code</param>
        /// <returns></returns>
        public async Task Ping(string accessCode)
        {
            using (var db = new PersistedRepository())
            {
                // Diagnostics
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                var player = db.Players.FirstOrDefault(p => p.AccessCode.Substring(0, 8).Equals(accessCode, StringComparison.OrdinalIgnoreCase));
                if (player != null)
                {
                    await Clients.Client(player.ConnectionId).ping();
                }

                // Report back
                Clients.Caller.chatMessage("Sent ping to player " + accessCode);
                await HubMessageAsync(0, "admin", "HubPing", "Ping", stopwatch.ElapsedMilliseconds, 1);
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Fires when a client reconnects to the hub
        /// </summary>
        public override Task OnReconnected()
        {
            using (var db = new PersistedRepository())
            {
                // Diagnostics
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                // Set connected true and return player
                var player = db.Player.SetConnectionStatus(Context.ConnectionId, true);
                if (player != null)
                {
                    HubMessage(0, player.AccessCode, player.AccessCode.Substring(0, 8) + " reconnected", "OnReconnected", stopwatch.ElapsedMilliseconds, 1);
                }
            }
            return base.OnReconnected();
        }
Exemplo n.º 24
0
        /// <summary>
        /// Move or recruit players from 
        /// </summary>
        /// <param name="originGrid">Origin grid to take from</param>
        /// <param name="destinationGrid">Destination grid to move to</param>
        /// <param name="playerCount">Number of players to recruit or move</param>
        /// <param name="pId">A Player Id (connection id or player id)</param>
        /// <param name="url">Url to navigate to</param>
        public Task GridRecruit(int originGridId, int destinationGridId, int playerCount, string url)
        {
            using (var db = new PersistedRepository())
            {
                // Diagnostics
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                // Define url for movement target
                if (string.IsNullOrEmpty(url))
                {
                    url = db.Grid.GetUrl(_segregLoop.Engine, destinationGridId);
                }

                // Get the required experience level
                var destGrid = db.Grids.FirstOrDefault(g => g.GridId == destinationGridId);
                if (destGrid == null)
                {
                    // Report back
                    return HubMessage(destinationGridId, "admin", "HubGridRecruit: Destination grid not found.", "GridRecruit", stopwatch.ElapsedMilliseconds, 1);
                }

                // Count players in origin grid
                if (db.Player.PlayerCountByGrid(destGrid) < playerCount)
                {
                    // Report back
                    return HubMessage(destinationGridId, "admin", "HubGridRecruit: Not enough players in origin grid.", "GridRecruit", stopwatch.ElapsedMilliseconds, 1);
                }
                else
                {
                    // Recruit players
                    var recruited = db.Player.RecruitPlayers(originGridId, destinationGridId, playerCount);

                    // Loop over all players
                    foreach (var player in recruited)
                    {
                        // Setup url
                        var url2 = url + "?a=" + player.AccessCode;
                        if (_segregLoop.Engine.Testing) url2 += "&test";

                        // Navigate to correspondig url
                        Clients.Client(player.ConnectionId).navigate(url2);
                    }

                    // Report back
                    return HubMessage(destinationGridId, "admin", "HubGridRecruit", "GridRecruit", stopwatch.ElapsedMilliseconds, 1);
                }
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Fires when a client disconnects from the hub
        /// </summary>
        public override Task OnDisconnected(bool stopCalled)
        {
            using (var db = new PersistedRepository())
            {
                // Diagnostics
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                // Set connected false and return player
                var player = db.Player.SetConnectionStatus(Context.ConnectionId, false);
                if (player != null)
                {
                    // Check if player is playing a game, i.e. he is in a non-static, running grid
                    if(!player.Grid.IsStatic & player.Grid.GridState == 5)
                    {
                        HubMessage(0, player.AccessCode, "*** Disconnect Exception: Player " + player.AccessCode.Substring(0, 8) + " left the game while Grid is running.", "OnDisconnected", stopwatch.ElapsedMilliseconds, 1);
                    }

                    HubMessage(0, player.AccessCode, player.AccessCode.Substring(0, 8) + " disconnected", "OnDisconnected", stopwatch.ElapsedMilliseconds, 2);
                }
            }
            return base.OnDisconnected(stopCalled);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Move a single player between grids
        /// </summary>
        /// <param name="playerId">Player Id or Access code start segment</param>
        /// <param name="destinationGrid">Destination grid id or grid guid to move to</param>
        /// <param name="url">Url to navigate to</param>
        public Task GridMove(string playerGuid, string destinationGrid, string url)
        {
            using (var db = new PersistedRepository())
            {
                // Diagnostics
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                var player = db.Player.GetByAnyId(playerGuid.Trim());
                var grid = db.Grid.GetByAnyId(destinationGrid);

                if (player != null)
                {
                    // Set ids
                    int playerId = player.PlayerId;
                    int gridId = 1;
                    if (grid != null)
                    {
                        gridId = grid.GridId;
                        // Define url for movement target
                        if (string.IsNullOrEmpty(url)) url = db.Grid.GetUrl(_segregLoop.Engine, gridId);
                    }

                    // Reformat Url
                    var context = Context.Request.GetHttpContext();
                    if (url.IndexOf("~/") >= 0) url = url.Replace("~/", context.Request.ApplicationPath + "/");

                    // If url not starts with http, add access code for local redirects
                    if (url.IndexOf("http") < 0) url += "/" + player.AccessCode;

                    // Change grid in db
                    db.Grid.MovePlayer(playerId, gridId, null);

                    // Navigate
                    Clients.Client(player.ConnectionId).navigate(url);
                    
                    //Report back
                    return HubMessage(gridId, "admin", "HubGridMove: " + url, "GridMove", stopwatch.ElapsedMilliseconds, 1);
                }
            }
            return null;
        }
Exemplo n.º 27
0
        /// <summary>
        /// Starts a new grid in a group of chained grids
        /// </summary>
        public Task StartChain()
        {
            using (var db = new PersistedRepository())
            {
                // Diagnostics
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                // Start the chain
                db.Grid.StartChain();

                // Report back
                return HubMessage(0, "admin", "HubStartChain", "StartChain", stopwatch.ElapsedMilliseconds, 1);
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Player is ready
        /// </summary>
        public Task Ready(bool timeout)
        {
            using (var db = new PersistedRepository())
            {
                // Diagnostics
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                // Save choice
                db.Player.SetReady(Context.ConnectionId, true, timeout);

                // Get AccessCode and Grid
                string accessCode = "";
                int gridId = 0;
                var player = db.Players.FirstOrDefault(p=>p.ConnectionId == Context.ConnectionId);
                if(player != null)
                {
                    accessCode = player.AccessCode;
                    gridId = player.GridId;
                }

                var message = db.Player.GetShortAccessCode(Context.ConnectionId) + " is ready";
                return HubMessageAsync(gridId, accessCode, message, "Ready", stopwatch.ElapsedMilliseconds, 2);
            }
        }
Exemplo n.º 29
0
 //Ctor
 public PowerShellController(PersistedRepository repo)
 {
     db = repo;
 }
Exemplo n.º 30
0
        /// <summary>
        /// Setup a grid from the admin web interface
        /// </summary>
        /// <param name="gridSettings">GridSettings object</param>
        public Task GridSetup(GridSettings gridSettings)
        {
            using (var db = new PersistedRepository())
            {
                // Diagnostics
                var stopwatch = new Stopwatch();
                stopwatch.Start();

                // Add the grid
                int gridId = 0;
                db.Grid.Add(gridSettings.GridName, 
                    gridSettings.GameTypeId, 
                    gridSettings.TreatmentTypeId,
                    gridSettings.RoundCount,
                    gridSettings.X, 
                    gridSettings.Y, 
                    gridSettings.PlayerCount,
                    gridSettings.BotCount,
                    gridSettings.FillFactor,
                    gridSettings.LowerThreshold, 
                    gridSettings.UpperThreshold, 
                    gridSettings.HighPayoff, 
                    gridSettings.LowPayoff,
                    gridSettings.NoiseLevel, 
                    gridSettings.RandomSeed,
                    gridSettings.ExchangeRate,
                    gridSettings.IntroTimer,
                    gridSettings.RoundTimer,
                    gridSettings.SummaryTimer,
                    gridSettings.EntryGrid, 
                    gridSettings.ExitGrid, 
                    gridSettings.PlayedMGames,
                    gridSettings.PlayedTGames,
                    gridSettings.Chained,
                    out gridId);

                // Report back
                return HubMessage(gridId, "admin", "HubGridSetup", "GridSetup", stopwatch.ElapsedMilliseconds, 1);
            }
        }