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 })); }
private static void SetUpPlayerShips(BattleShips battleShips, Player player, Menu menu) { string userInput; do { Console.WriteLine("Enter 'D' for a default ship setup or 'C' to create custom ships."); Console.Write(">"); userInput = Console.ReadLine()?.Trim().ToUpper() ?? "D"; } while (userInput != "D" && userInput != "C"); if (userInput == "D") { battleShips.AddDefaultShipsToPlayerShipList(player); } else { do { Console.WriteLine($"({player.Ships.Count + 1}) Enter ship name: "); Console.Write(">"); var shipName = Console.ReadLine()?.Trim().ToUpper() ?? "Default"; var(shipWidth, _, _) = AskForUserInput($"({player.Ships.Count + 1}) Enter ship width", battleShips.Width >= battleShips.Height ? battleShips.Width : battleShips.Height, 1, menu); battleShips.AddShipToPlayerShipList(player, new Ship() { Name = shipName, Width = shipWidth }); } while (player.Ships.Count < 5); } }
private static string HumanVsAiNewGame() { var menu = new Menu(MenuLevel.Level1); menu.AddNewMenuItem(new MenuItem("Save game", "S", null)); (int height, _, _) = AskForUserInput("Please enter the board height", 20, 10, menu); (int width, _, _) = AskForUserInput("Please enter the board width", 20, 10, menu); Player player1 = new Player(); Player player2 = new Player(); BattleShips battleShips = new BattleShips(height, width, player1, player2); Console.WriteLine("Enter 'T' if the ships can touch. Enter any other symbol if not."); Console.Write(">"); var touchRules = Console.ReadLine()?.Trim().ToUpper() ?? "E"; if (touchRules != "T") { battleShips.ShipsCanTouch = false; } Console.Clear(); Console.WriteLine("Player 1 ships"); SetUpPlayerShips(battleShips, player1, menu); PlacePlayerShipsOnBoard(battleShips, player1, menu); Console.Clear(); battleShips.AddDefaultShipsToPlayerShipList(player2); battleShips.PlaceShipsAutomatically(player2); battleShips.GameType = GameType.HumanVsAi; var userChoice = ""; userChoice = HumanVsHumanMainGame(battleShips, menu); return(userChoice !); }