public ActionResult Create(ArmyModel a)
        {
            if (ModelState.IsValid)
            {
                GameEntities ent  = new GameEntities();
                Army         unit = new Army();

                unit.Name        = a.Name;
                unit.Attack      = a.Attack;
                unit.Defence     = a.Defence;
                unit.KingdomId   = a.KingdomId;
                unit.Knowledge   = a.Knowledge;
                unit.MagicResist = a.MagicResist;
                unit.Quantity    = a.Quantity;

                ent.Armies.Add(unit);
                ent.SaveChanges();


                return(RedirectToAction("Index"));
            }
            else
            {
                GameEntities ent = new GameEntities();

                ViewData["Kingdom"] = ent.Kingdoms.Select(x => new SelectListItem()
                {
                    Value = x.Id.ToString(), Text = x.Name
                }).ToList();

                return(View(a));
            }
        }
        public ActionResult Edit(ArmyModel a)
        {
            if (ModelState.IsValid) // jezeli spelnia atrybuty, walidatory
            {
                GameEntities ent = new GameEntities();
                Army         unit;// = new Army();
                unit             = ent.Armies.Where(x => x.Id == a.UnitId).FirstOrDefault();
                unit.Name        = a.Name;
                unit.Attack      = a.Attack;
                unit.Defence     = a.Defence;
                unit.KingdomId   = a.KingdomId;
                unit.Knowledge   = a.Knowledge;
                unit.MagicResist = a.MagicResist;
                unit.Quantity    = a.Quantity;
                ent.Entry(ent.Armies.Where(x => x.Id == a.UnitId).First()).CurrentValues.SetValues(unit);
                ent.SaveChanges();
                return(RedirectToAction("Index"));
            }

            else
            {
                GameEntities ent = new GameEntities();
                ViewData["Kingdom"] = ent.Kingdoms.Select(x => new SelectListItem()
                {
                    Value = x.Id.ToString(), Text = x.Name
                }).ToList();
                return(View(a));
            }
        }
        public ActionResult Delete(int id)
        {
            GameEntities ent = new GameEntities();

            Army army = ent.Armies.Where(x => x.Id == id).First();

            ent.Armies.Remove(army);
            ent.SaveChanges();
            return(RedirectToAction("Index"));
        }
        public IHttpActionResult CreateGame([FromBody] List <string> players)
        {
            try
            {
                using (var db = new GameEntities())
                {
                    //Add the user who made the call to the list of game participants.
                    if (!players.Contains(User.Identity.Name))
                    {
                        players.Add(User.Identity.Name);
                    }

                    //Get the ID and username for each participant.
                    var participants = db.AspNetUsers.Where(x => players.Contains(x.UserName)).Select(x => new { x.Id, x.UserName }).ToList();

                    //Create a list of GameUser objects using the participants. The user who made the call will have a status of 2 (active), while all others will be 1 (pending).
                    var newGameUsers = participants.Select(x => new GameUser
                    {
                        UserID = x.Id,
                        Status = (x.UserName == User.Identity.Name) ? 2 : 1
                    }).ToList();

                    //Check that all game participants have accounts (and were found) in the database. If not, return an error.
                    if (newGameUsers.Count() != players.Count())
                    {
                        return(Content(HttpStatusCode.NotFound, "One or more of the game participants were not found in the database."));
                    }

                    string createGameMessage = null;
                    if (!logic.TryCreateGame(ref createGameMessage, participants.Select(x => x.UserName).ToList()))
                    {
                        return(Content(HttpStatusCode.BadRequest, createGameMessage));
                    }

                    Game g = new Game()
                    {
                        Start     = DateTime.Now,
                        GameUsers = newGameUsers
                    };

                    db.Games.Add(g);
                    db.SaveChanges();

                    return(Ok(g.ID));
                }
            }
            catch (ArgumentNullException e)
            {
                return(Content(HttpStatusCode.InternalServerError, "The database encountered an error while attempting to retrieve information about the participants."));
            }
            catch (Exception e)
            {
                return(Content(HttpStatusCode.InternalServerError, "The server encountered an error and was unable to create the game. Please inform the development team."));
            }
        }
예제 #5
0
파일: Form1.cs 프로젝트: indij/KatanaMUD
        private void Form1_Load(object sender, EventArgs e)
        {
            var context = new GameEntities("Server=KATANAMUD\\SQLEXPRESS;Database=KatanaMUD;integrated security=True;");

            context.LoadFromDatabase();

            //var races = Btrieve.GetAllRaces(new FileInfo(@"C:\Users\spsadmin\Documents\MMUDDats\wccrace2.dat").FullName, context.RaceTemplates);
            //var classes = Btrieve.GetAllClasses(new FileInfo(@"C:\Users\spsadmin\Documents\MMUDDats\wccclas2.dat").FullName, context.ClassTemplates);
            var items = Btrieve.GetAllItems(new FileInfo(@"C:\CleanP\wccitem2.dat").FullName, context.ItemTemplates);


            //var rooms = Btrieve.GetAllRooms(new FileInfo(@"C:\CleanP\wccmp002.dat").FullName);

            //Regex r = new Regex("\\s+");
            //var descriptions = rooms.GroupBy(x => x.Description).ToList();//.OrderBy(x => x.Key).ToList();

            //foreach (var group in descriptions)
            //{
            //    var textBlock = context.TextBlocks.New();
            //    textBlock.Text = group.Key;

            //    foreach (var room in group)
            //    {
            //        var dbRoom = room.ToRoom(null);
            //        dbRoom.TextBlock = textBlock;
            //        context.Rooms.Add(dbRoom, false);
            //    }
            //}

            //foreach (var room in rooms)
            //{
            //	var dbRoom = room.ToRoom(context.Rooms.SingleOrDefault(x => x.Id == RoomBuffer.GetRoomNumber(room.MapNumber, room.RoomNumber)));
            //}



            //var notdrop = items.Where(x => x.NotDroppable != 0).ToList();
            //var retain = items.Where(x => x.RetainAfterUses != 0).ToList();
            //var destroy = items.Where(x => x.DestroyOnDeath != 0).ToList();



            //context.RaceTemplates.AddRange(races, true);
            //context.ClassTemplates.AddRange(classes, true);
            //context.ItemTemplates.AddRange(items, true);
            context.SaveChanges();
        }
        public ActionResult Delete(int id)
        {
            GameEntities ent = new GameEntities();

            List <Army> army = ent.Armies.Where(x => x.KingdomId == id).ToList();

            foreach (Army a in army)
            {
                ent.Armies.Remove(a);
            }


            Kingdom kingdom = ent.Kingdoms.Where(x => x.Id == id).First();

            ent.Kingdoms.Remove(kingdom);
            ent.SaveChanges();
            return(RedirectToAction("Index"));
        }
        public ActionResult Edit(KingdomModel kingdom)
        {
            if (ModelState.IsValid) // jezeli spelnia atrybuty, walidatory np. Required
            {
                GameEntities ent = new GameEntities();
                Kingdom      k   = ent.Kingdoms.Where(x => x.Id == kingdom.Id).FirstOrDefault();
                k.Name       = kingdom.Name;
                k.Place      = kingdom.Place;
                k.Population = kingdom.Population;

                ent.Entry(ent.Kingdoms.Where(x => x.Id == k.Id).First()).CurrentValues.SetValues(k);
                ent.SaveChanges();
                return(RedirectToAction("Index"));
            }
            else
            {
                return(View(kingdom));
            }
        }
예제 #8
0
        public IHttpActionResult UpdatePersonalDetails(AspNetUser user)
        {
            try
            {
                using (var db = new GameEntities())
                {
                    AspNetUser u = db.AspNetUsers.Single(us => us.Id == user.Id);

                    if (user.LastName != null)
                    {
                        u.LastName = user.LastName;
                    }

                    if (user.FirstName != null)
                    {
                        u.FirstName = user.FirstName;
                    }

                    if (user.Email != null && ValidEmailCheck(user.Email))
                    {
                        u.Email = user.Email;
                    }

                    if (user.PhoneNumber != null && ValidPhoneNumCheck(user.PhoneNumber))
                    {
                        u.PhoneNumber = user.PhoneNumber;
                    }

                    db.SaveChanges();

                    return(Ok());
                }
            }
            catch (ArgumentNullException e)
            {
                return(Content(System.Net.HttpStatusCode.BadRequest, "No data found."));
            }
            catch (Exception e)
            {
                return(Content(System.Net.HttpStatusCode.InternalServerError, "The server encountered an error and was unable to create the game. Please inform the development team."));
            }
        }
예제 #9
0
 public IHttpActionResult DeleteUser()
 {
     try
     {
         using (var db = new GameEntities())
         {
             db.AspNetUsers.Single(x => x.UserName == User.Identity.Name).Active = false; // set active to false
             db.SaveChanges();
         }
         return(Ok("The user account has been successfully deactivated."));
     }
     catch (ArgumentNullException e)
     {
         return(Content(System.Net.HttpStatusCode.InternalServerError, "The user account could not be deleted because it does not exist in the database."));
     }
     catch (Exception e)
     {
         return(Content(System.Net.HttpStatusCode.InternalServerError, "The server encountered an error while attempting to deactive the account. Please inform the development team."));
     }
 }
        public ActionResult Create(KingdomModel k)
        {
            if (ModelState.IsValid)
            {
                GameEntities ent  = new GameEntities();
                Kingdom      king = new Kingdom();
                king.Name       = k.Name;
                king.Place      = k.Place;
                king.Population = k.Population;

                ent.Kingdoms.Add(king);
                ent.SaveChanges();


                return(RedirectToAction("Index"));
            }
            else
            {
                return(View(k));
            }
        }
예제 #11
0
파일: Game.cs 프로젝트: indij/KatanaMUD
        async public static void Run()
        {
            ScriptManager.LoadScripts();
            Data = new GameEntities("Server=KATANAMUD\\SQLEXPRESS;Database=KatanaMUD;integrated security=True;");
            Data.LoadFromDatabase();

            var gameTime = Data.Settings.Find("GameTime");

            if (gameTime == null)
            {
                GameTime       = new TimeSpan(0);
                gameTime       = Data.Settings.New("GameTime");
                gameTime.Value = 0.ToString();
            }
            else
            {
                GameTime = new TimeSpan(long.Parse(gameTime.Value));
            }

            DateTime lastTime = DateTime.UtcNow;
            var      saveTime = lastTime.AddMinutes(1);

            Console.WriteLine("KatanaMUD 0.2 Server Started");
            while (true)
            {
                try
                {
                    var newTime        = DateTime.UtcNow;
                    var timeDifference = newTime.Subtract(lastTime);
                    GameTime       = GameTime.Add(timeDifference);
                    gameTime.Value = GameTime.Ticks.ToString();

                    // handle connections/disconnections
                    Connections.HandleConnectsAndDisconnects();

                    // Handle all timed events.
                    while (_eventQueue.Count > 0 && _eventQueue.FindMin().ExecutionTime < GameTime)
                    {
                        var ev = _eventQueue.DeleteMin();
                        ev.Execute();
                    }

                    // Grab a snapshot of all active actors (will clear the active list)
                    var actors = ActiveActors.Snapshot();

                    // Extract the messages from the actors, and order them by time.
                    var messages = actors.Select(x =>
                    {
                        bool remaining;
                        var message = x.GetNextMessage(out remaining);
                        return(Tuple.Create(x, message, remaining));
                    }).OrderBy(x => x.Item2?.MessageTime).ToList();

                    // If any actors have more messages, re-add them to the active list.
                    // we only grab the top message from each actor because each action may have a time component to it,
                    // so that if the action causes the user to pause, we cannot process the second message yet.
                    // We'll grab the next message on the next game loop. It's not the best system, but it's
                    // workable, and it serves to effectively limit messages to 1 per loop, or about 10-20 per second
                    // depending on how long the loop sleep period is. I don't believe this will be a problem in practice,
                    // though I suppose there's always the possibility of a timing exploit somewhere.
                    foreach (var message in messages.Where(x => x.Item3 == true))
                    {
                        ActiveActors.Add(message.Item1);
                    }

                    foreach (var message in messages.Where(x => x.Item2 != null))
                    {
                        message.Item2.Process(message.Item1);
                    }

                    //TODO: This could really be done in parallel, or even on separate threads.
                    // I figure this should be addressed sooner rather than later, since once combat is enabled, output messages could get
                    // laggy if we simply perform awaits on each one instead of letting the hardware do its thing and go on to the next.
                    foreach (var connection in Connections.GetConnections())
                    {
                        var handler = connection?.Actor?.MessageHandler as ConnectionMessageHandler;
                        if (handler != null)
                        {
                            await handler.SendMessages();
                        }
                    }


                    lastTime = newTime;

                    // Save changes to the database.
                    if (Data.ForceSave || saveTime < newTime)
                    {
                        Data.ForceSave = false;
                        // TODO: Make the save time configurable eventually.
                        saveTime = newTime.AddMinutes(1);
                        Data.SaveChanges();
                    }

                    Thread.Sleep(50);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(String.Format("[{0}] Exception: {1}", DateTime.Now.ToShortTimeString(), ex.ToString()));
                }
            }
        }
        public IHttpActionResult UpdateUserStatus(int newStatus, int gID)
        {
            try
            {
                using (var db = new GameEntities())
                {
                    // Create game object from game ID, gID, to minimize db calls
                    Game game = db.Games.Single(x => x.ID == gID);

                    // Checks if game is already over
                    if (game.Status == 3)
                    {
                        return(Content(HttpStatusCode.BadRequest, "Game is inactive. No more status changes allowed."));
                    }

                    // Creates tuple list of userName and status
                    var userNameStatusList = db.GameUsers.Where(x => x.GameID == gID).Include(x => x.AspNetUser).ToList()
                                             .Select(x => new Tuple <string, int>(x.AspNetUser.UserName, x.Status)).ToList();

                    //Get the list of game states for the id provided and order them by descending.
                    IQueryable <GameState> gameStatesDesc = db.GameStates.Where(x => x.GameID == gID).OrderByDescending(x => x.TimeStamp);

                    //If game states were found, set the latest one to gameState.
                    string newGameState = "";
                    string gameState    = "";
                    if (gameStatesDesc.Any())
                    {
                        gameState = gameStatesDesc.First().GameState1;
                    }

                    int statusCode = logic.TryUpdateUserStatus(ref newGameState, gameState, gID, userNameStatusList, User.Identity.Name, newStatus);
                    if (statusCode > 0)
                    {
                        // Update game user's status in db
                        db.GameUsers.Single(x => x.GameID == gID && x.AspNetUser.UserName == User.Identity.Name).Status = newStatus;

                        // Update game state in db
                        if (!String.IsNullOrEmpty(newGameState))
                        {
                            GameState gameSt = new GameState
                            {
                                GameState1 = newGameState,
                                TimeStamp  = DateTime.Now,
                                GameID     = gID
                            };
                            game.GameStates.Add(gameSt);
                        }

                        // Update game status (active/inactive) if needed
                        switch (statusCode)
                        {
                        case (int)GameLogicResponseCodes.Valid:
                            break;

                        case (int)GameLogicResponseCodes.GameActive:
                            game.Status = 2;
                            break;

                        case (int)GameLogicResponseCodes.GameInactive:
                            game.Status = 3;
                            foreach (var gu in db.GameUsers.Where(x => x.GameID == gID))
                            {
                                gu.Status = 3;
                            }
                            game.End = DateTime.Now;
                            break;

                        default:
                            //If we receive a status > 3, the game logic class is bad.
                            return(Content(HttpStatusCode.InternalServerError, "The server encountered an issue while processing the request. Please inform the development team."));
                        }
                        db.SaveChanges();

                        //If TryUpdateUserStatus returned a new gamestate, return it to the calling user.
                        if (!string.IsNullOrWhiteSpace(newGameState))
                        {
                            return(Ok(newGameState));
                        }

                        //Otherwise, return an empty OK response.
                        return(Ok());
                    }
                    else
                    {
                        return(Content(System.Net.HttpStatusCode.BadRequest, "Invalid status change request."));
                    }
                }
            }
            catch (InvalidOperationException)
            {
                return(Content(System.Net.HttpStatusCode.NotFound, "Cound not find game with an ID of " + gID));
            }
            catch (Exception e)
            {
                return(Content(System.Net.HttpStatusCode.InternalServerError, "The server encountered an error updating game user status. Please inform the development team."));
            }
        }
        public IHttpActionResult Update(int gameId, [FromBody] string requestedTurn)
        {
            try
            {
                string outputGameState = null;

                using (GameEntities db = new GameEntities())
                {
                    //Get the latest gamestate for the requested game
                    GameState currentGameState;
                    Game      currentGame = db.Games.Include(x => x.GameStates).First(g => g.ID == gameId);

                    // Checks if game is already over
                    if (currentGame.Status == 3)
                    {
                        return(Content(HttpStatusCode.BadRequest, "Game is inactive. No more status changes allowed."));
                    }

                    IEnumerable <GameState> gameStatesDesc = currentGame.GameStates.Where(gs => gs.GameID == gameId).OrderByDescending(x => x.TimeStamp);

                    //As long as at least one game state exists, process player's turn
                    if (gameStatesDesc.Any())
                    {
                        currentGameState = gameStatesDesc.First();
                        string callingUsername = User.Identity.Name;
                        //Validate player's turn with the implementation of IGameLogic, returns GameLogicResponseCode
                        int tryTurnResult = logic.TryTakeTurn(ref outputGameState, currentGameState.GameState1, gameId, callingUsername, requestedTurn);

                        // Process response code
                        switch (tryTurnResult)
                        {
                        case (int)GameLogicResponseCodes.Invalid:     //Invalid player turn, no change to game status
                            return(BadRequest());

                        case (int)GameLogicResponseCodes.Valid:     //Valid player turn, no change to game status
                            break;

                        case (int)GameLogicResponseCodes.GameActive:     //Valid player turn, game status changes to active
                            currentGame.Status = 2;
                            break;

                        case (int)GameLogicResponseCodes.GameInactive:     //Valid player turn, game status changes to inactive
                            currentGame.Status = 3;
                            foreach (var gu in db.GameUsers.Where(x => x.GameID == gameId))
                            {
                                gu.Status = 3;
                            }
                            currentGame.End = DateTime.Now;
                            break;

                        default:
                            //If we receive a status > 3, the game logic class is bad.
                            return(Content(HttpStatusCode.InternalServerError, "The server encountered an issue while processing the request. Please inform the development team."));
                        }

                        //If TryTakeTurn returned a new gamestate, save it in the database
                        if (!string.IsNullOrWhiteSpace(outputGameState))
                        {
                            GameState gameState = new GameState
                            {
                                GameID     = currentGameState.GameID,
                                GameState1 = outputGameState,
                                TimeStamp  = DateTime.Now
                            };
                            currentGame.GameStates.Add(gameState);
                        }
                    }
                    //No gamestates exist for requested game, turn not allowed
                    else
                    {
                        return(Content(HttpStatusCode.NotFound, "The game " + gameId + " has no gamestates."));
                    }
                    db.SaveChanges();
                }

                //If TryTakeTurn returned a new gamestate, return it to the calling user
                if (!string.IsNullOrWhiteSpace(outputGameState))
                {
                    return(Ok(outputGameState));
                }

                //Otherwise, return an empty OK response.
                return(Ok());
            }
            catch (InvalidOperationException)
            {
                return(Content(HttpStatusCode.NotFound, "Could not find a game with an ID of " + gameId));
            }
            catch (Exception)
            {
                return(Content(HttpStatusCode.InternalServerError, "The server encountered an error when attempting to update the game state."));
            }
        }