public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            BattleShips battleShips = new BattleShips(Height, Width, Player1, Player2)
            {
                ShipsCanTouch = ShipsCanTouch
            };

            battleShips.AddDefaultShipsToPlayerShipList(Player1);
            battleShips.AddDefaultShipsToPlayerShipList(Player2);

            battleShips.PlaceShipsAutomatically(Player1);
            battleShips.PlaceShipsAutomatically(Player2);

            var save = battleShips.CreateBattleShipsSave(GameName);

            if (_context.BattleShipsSaves.Any(e => e.SaveName == GameName))
            {
                ModelState.AddModelError("GameName", "A save game with this name already exists.");
                return(Page());
            }

            await _context.BattleShipsSaves.AddAsync(save);

            await _context.SaveChangesAsync();

            return(RedirectToPage("/PlayGame", new { id = save.Id }));
        }
Esempio n. 2
0
        static string SaveGame(BattleShips game)
        {
            var saveName = AskUserForSaveGameName(1, 30);
            BattleShipsSaveJson battleShips = new BattleShipsSaveJson()
            {
                Height      = game.Height,
                Width       = game.Width,
                Player1     = game.Player1,
                Player1Turn = game.Player1Turn,
                Player2     = game.Player2,
                SaveName    = saveName,
                GameType    = game.GameType
            };

            SaveTool.SaveGameToFile(battleShips);

            using var ctx = new AppDbContext();
            var battleShipsSave = game.CreateBattleShipsSave(saveName);

            if (ctx.BattleShipsSaves.Any(e => e.SaveName == saveName))
            {
                var save = ctx.BattleShipsSaves.FirstOrDefault(e => e.SaveName == saveName);
                game.UpdateBattleShipsSave(save !);
                ctx.Update(save);
            }
            else
            {
                ctx.Add(battleShipsSave);
            }
            ctx.SaveChanges();

            return("");
        }