/// <summary> /// Public game state to all connected bots. /// </summary> /// <param name="gameStateDto"></param> /// <returns></returns> public async Task PublishGameState(GameStateDto gameStateDto) { if (runnerStateService.GetEngine().ConnectionId != Context.ConnectionId) { Logger.LogWarning("Core", "Engine endpoint invoked by unauthorized client"); await SendGameException( new GameException { ExceptionMessage = "Invalid engine connection, gameState not published." }); return; } runnerStateService.ClearBotActionsReceived(); Logger.LogInfo( "GameStatePublished", $"Tick: {gameStateDto.World.CurrentTick}, Player Count: {gameStateDto.PlayerObjects.Count}, Object Count: {gameStateDto.GameObjects.Count}"); await Clients.Group(GameGroups.Players).SendAsync("ReceiveGameState", gameStateDto); await Clients.Group(GameGroups.Components).SendAsync("ReceiveGameState", gameStateDto); await Clients.Caller.SendAsync("TickAck", gameStateDto.World.CurrentTick); }
public List <GameStateDto> GetBattleResults() { var output = new List <GameStateDto>(); Task.WaitAll(player.Start()); var waitForPlayer = Task.Run(async() => { while (true) { if (player.Ready) { break; } await Task.Delay(100); } }); if (waitForPlayer.Wait(TimeSpan.FromSeconds(10)) == false) { throw new Exception("Player bot not ready within 10 seconds"); } for (int rounds = 0; rounds < 300; rounds++) { output.Add(new GameStateDto(gameState)); foreach (var bot in gameState.Bots) { var state = new GameStateDto(gameState, bot.ID); var fleets = bot.GetFleetResponse(state); foreach (var fleet in fleets) { gameState.SendFleet(bot.ID, fleet.SourcePlanetID, fleet.DestinationPlanetID, fleet.NumberOfUnits); } } var winner = gameState.GetWinnerId(300); if (winner.HasValue) { Console.WriteLine($"Winner: {gameState.Bots.First(x => x.ID == winner).Name}"); break; } gameState.Tick(); } if (gameState.Disqualified != null) { Console.WriteLine(gameState.Disqualified); } player.Kill(); return(output); }
public JsonResult GetGameState() { var gameSession = sessionMgr.GetSessionById(userCtx.GameSessionId); var currentPlayer = gameSession.GetPlayerById(userCtx.PlayerId); var stateDto = GameStateDto.CreateFromSession(gameSession, currentPlayer); // URI сервера WebSocket stateDto.MessageServerUri = $"ws://{Request.Host.Value}/messages"; return(Json(stateDto)); }
private int GetFleetNeeded(PlanetDto myPlanet, PlanetDto enemy, GameStateDto state) { var output = enemy.NumberOfShips + GetIncomingEnemies(enemy, state) - GetIncomingSupport(enemy, state); if (enemy.OwnerID != 0) { output += TravelTime(myPlanet.Position, enemy.Position) * enemy.GrowthRate; } return(output); }
public async Task GameStateDtoTest() { var newSession = await manager.StartNewGame(GameName, testGameMaster); var testPlayer = Player.CreatePlayer("Player One"); newSession.AddPlayer(testPlayer); var stateDto = GameStateDto.CreateFromSession(newSession, testPlayer); Assert.AreNotEqual(Guid.Empty, stateDto.SessionId); Assert.IsNotNull(stateDto.Master); Assert.AreNotEqual(0, stateDto.ObjectDefinitions.Count()); Assert.AreNotEqual(0, stateDto.Players.Count()); Assert.AreNotEqual(0, stateDto.RoomScene.Objects.Count()); }
public List <FleetCommandDto> GameUpdate(GameStateDto state) { const int me = 1; var output = new List <FleetCommandDto>(); foreach (var myPlanet in state.Planets.Where(x => x.OwnerID == me)) { var enemy = state.Planets.Where(x => x.OwnerID > 0 && x.OwnerID != me).OrderBy(x => Distance(myPlanet.Position, x.Position)).FirstOrDefault(); if (enemy != null) { output.Add(new FleetCommandDto(myPlanet.ID, enemy.ID, myPlanet.NumberOfShips - 1)); } } return(output); }
public List <FleetCommandDto> GameUpdate(GameStateDto state) { const int me = 1; var output = new List <FleetCommandDto>(); foreach (var myPlanet in state.Planets.Where(x => x.OwnerID == me && x.NumberOfShips > (x.GrowthRate * 10))) { var spareFleet = (myPlanet.NumberOfShips - 1) - (myPlanet.GrowthRate * 10); var neutral = state.Planets.Where(x => x.OwnerID == 0).OrderBy(x => Distance(myPlanet.Position, x.Position)).FirstOrDefault(); if (neutral != null) { output.Add(new FleetCommandDto(myPlanet.ID, neutral.ID, spareFleet)); } } return(output); }
public GameStateDto GetGameState(Guid gameId) { var info = _uow.GameInfos.GetGameInfo(gameId); if (info == null) { throw new NotFoundException("Game not found."); } var state = new GameStateDto { Players = info.Players.Select(x => x.Key).ToList(), State = info.Status, Winner = info.Winner, }; return(state); }
private async Task OnWriteLog(GameStateDto gameStateDto) { LogWriter.LogInfo("Logger", $"Tick: {gameStateDto.World.CurrentTick}, Adding to log"); gameStateDtoLog.Add(gameStateDto); if (!verboseLogging) { return; } if (gameStateDto.World.CurrentTick % 100 != 0) { return; } var filePath = WriteFileWithSerialisation( $"{gameStateDto.World.CurrentTick}_DTO_{loggerConfig.GameStateLogFileName}", logDirectory, gameStateDtoLog.ToArray()); }
public void SaveCurrentGameState(int userId, GameStateDto state) { using (var db = new FifteenGameModel()) { var currentGame = db.CurrentGames.FirstOrDefault(cg => cg.User.Id == userId); if (currentGame == null) { var user = db.Users.FirstOrDefault(u => u.Id == userId); currentGame = db.CurrentGames.Create(); currentGame.User = user; currentGame.MoveCount = state.MoveCount; currentGame.GameStartTime = state.GameStartTime; db.CurrentGames.Add(currentGame); } else { currentGame.MoveCount = state.MoveCount; currentGame.GameStartTime = state.GameStartTime; } if (currentGame.CurrentGameCells?.Any() ?? false) { db.CurrentGameCells.RemoveRange(currentGame.CurrentGameCells); } int i = 1; foreach (var cell in state.State) { db.CurrentGameCells.Add(new CurrentGameCell { CurrentGame = currentGame, CellIndex = i, CellValue = cell, }); i++; } db.SaveChanges(); } }
public void SaveCurrentGameState(int userId, GameStateDto state) { using (var db = new FifteenGameDbFirstEntities()) { var currentGame = db.CurrentGames.FirstOrDefault(cg => cg.UserId == userId); if (currentGame == null) { currentGame = new CurrentGame { UserId = userId, MoveCount = state.MoveCount, GameStartTime = state.GameStartTime, }; db.CurrentGames.Add(currentGame); } else { currentGame.MoveCount = state.MoveCount; currentGame.GameStartTime = state.GameStartTime; } while (currentGame.CurrentGameCells.Any()) { db.CurrentGameCells.Remove(currentGame.CurrentGameCells.First()); } int i = 1; foreach (var cell in state.State) { currentGame.CurrentGameCells.Add(new CurrentGameCell { CellIndex = i, CellValue = cell, }); i++; } db.SaveChanges(); } }
public GameStateDto GetCurrentGameState(int userId) { using (var db = new FifteenGameModel()) { var currentGame = db.CurrentGames.FirstOrDefault(cg => cg.User.Id == userId); if (currentGame == null) { return(null); } var result = new GameStateDto { MoveCount = currentGame.MoveCount, GameStartTime = currentGame.GameStartTime, State = currentGame.CurrentGameCells.OrderBy(cgs => cgs.CellIndex).Select(cgs => cgs.CellValue).ToList(), }; return(result); } }
public List <FleetCommandDto> GameUpdate(GameStateDto state) { var output = new List <FleetCommandDto>(); foreach (var myPlanet in state.Planets.Where(x => x.OwnerID == me)) { var enemies = state.Planets .Where(x => x.OwnerID != me) .Select(x => (Planet: x, Score: GetFleetNeeded(myPlanet, x, state))) .Where(x => x.Score >= 0) .OrderBy(x => x.Score); if (enemies.Any()) { var enemy = enemies.First(); var fleetNeeded = enemy.Score + 1; output.Add(new FleetCommandDto(myPlanet.ID, enemy.Planet.ID, Math.Min(fleetNeeded, myPlanet.NumberOfShips - 1))); } } return(output); }
private async Task UpdateState(C4Engine engine, GameStateDto currentState) { var state = new GameStateDto { Board = engine.Board, Score = engine.Score, NumPieces = engine.NumPieces, Winner = engine.IsWinner(), Host = Environment.MachineName, LastUpdated = DateTimeOffset.UtcNow, CurrentPlayer = currentState.CurrentPlayer == 1 ? 2 : 1, }; if (state.Winner != 0) { for (var k = 0; k < 69; k++) { if (state.Score[state.Winner - 1][k] == 16) { for (var i = 0; i < 6; i++) { for (var j = 0; j < 7; j++) { if (C4Engine.Map[i][j][k] == 1) { state.WinningGrid[i][j] = state.Winner; } } } } } } await StateManager.SetStateAsync("gameState", state); GetEvent <IGameActorEvents>().GameStateChanged(state); }
private async void GameTimerOnElapsed(object sender, ElapsedEventArgs e) { Game.StateMessage = "Waiting for opponent"; GameStateDto gameState = await _gameService.GetGameStatus(); UpdateGameState(gameState); RefreshUi(); if (Game.GameState == GameState.InProgress && Game.User.Id == Game.NextPlayerId) { _gameTimer.Stop(); Game.StateMessage = "Your turn"; } if (Game.GameState == GameState.Finished) { try { _gameTimer.Stop(); var message = gameState.Winner == Game.User.Id ? "Won" : "Lost"; await _gameService.Reset(); Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { Application.Current.MainPage.DisplayAlert("Game over", $"You {message}!", "Ok"); Navigation.PushModalAsync(new LoginPage(new LoginViewModel())); }); } catch (Exception exception) { Console.WriteLine(exception); throw; } } }
public List <FleetCommandDto> GetFleetResponse(GameStateDto state) { return(Bot.GameUpdate(state)); }
private void UpdateGameState(GameStateDto gameStateDto) { Game.GameState = gameStateDto.GameState; Game.NextPlayerId = gameStateDto.NextPlayer; Game.Board = gameStateDto.Board; }
private int GetIncomingEnemies(PlanetDto planet, GameStateDto state) { return(state.Fleets.Where(x => x.OwnerID != me && x.DestinationPlanetID == planet.ID).Sum(x => x.NumberOfShips)); }
public async Task SendMessage(string gameId, GameStateDto gameState) { await Clients.All.SendAsync(gameId, gameState); }
public Task OnStateReset(GameStateDto newStateDto) => DispatchTask(new GameResetAction(new GameState(SynchronisationState.Connected, newStateDto.Code, newStateDto.Players, newStateDto.FirstName, newStateDto.LastName, newStateDto.Objectives, newStateDto.EvidenceStates, newStateDto.EvidencePossibilities, newStateDto.GhostPossibilities)));