public IActionResult GetMovesOfGame(string gameKey) { var game = _directChessRepository.GetGameByKey(gameKey); var moves = _directChessRepository.GetMovesOfGame(game.GameId).ToList <Move>(); var moveResponses = new List <MoveResponse>(); foreach (var move in moves) { ; moveResponses.Add(new MoveResponse { FromField = move.FromField, ToField = move.ToField }); } var response = new GameResponse { GameKey = gameKey, Player1Name = game.Player1Name, Player2Name = game.Player2Name, WhitePlayer = game.WhitePlayer, Moves = moveResponses }; return(Ok(response)); }
public GameResponse SelectDeck(string connectionId, PlayerDeck deck) { if (!UsersByConnectionId.ContainsKey(connectionId)) { Logger.LogError($"Got select deck message for unknown connection id '{connectionId}'"); return(GameResponse.Failure("An error occurred selecting your deck. Please try again later.")); } var user = UsersByConnectionId[connectionId]; var game = FindGameForUser(user.Name); if (game == null) { Logger.LogError($"Got select deck message for user '{user.Name}' with no game"); return(GameResponse.Failure("Could not select your deck because your game was not found. Please restart your game.")); } if (!game.GetPlayers().ContainsKey(user.Name)) { Logger.LogError($"Got select deck message for user '{user.Name}' game '{game.Id}' which they are not in."); return(GameResponse.Failure("An error occurred selecting your deck. Please try again later.")); } var player = game.GetPlayers()[user.Name]; var customData = JsonConvert.DeserializeObject <PlayerCustomData>(player.CustomData) ?? new PlayerCustomData(); customData.Deck = deck; player.CustomData = JsonConvert.SerializeObject(customData); return(GameResponse.Succeeded(game)); }
public void ToJson_Object_AreEqual() { var response = new GameResponse() { game = new Game() { board = new Board() { size = 1, tiles = "##" }, id = "id1", maxTurns = 1200, turn = 1, heroes = new List <Vindinium.Serialization.Hero>() { new Vindinium.Serialization.Hero() { name = "HERO 4 ever" }, } }, token = "ABCDEF1234" }; var act = response.ToJson(); var exp = "{\"game\":{\"board\":{\"size\":1,\"tiles\":\"##\"},\"finished\":false,\"heroes\":[{\"crashed\":false,\"elo\":0,\"gold\":0,\"id\":0,\"life\":0,\"mineCount\":0,\"name\":\"HERO 4 ever\",\"pos\":null,\"spawnPos\":null}],\"id\":\"id1\",\"maxTurns\":1200,\"turn\":1},\"hero\":null,\"playUrl\":null,\"token\":\"ABCDEF1234\",\"viewUrl\":null}"; Assert.AreEqual(exp, act); }
public async Task <GameResponse> ExecuteAsync(int id) { var gameResponse = new GameResponse(); try { Log.Information("Retrieving game title : [{Id}]...", id); var game = await Repository.SingleOrDefaultAsync(g => g.Id == id); if (game == null) { var exception = new Exception($"No game found by title : [{id}]."); Log.Error(exception, EXCEPTION_MESSAGE_TEMPLATE, exception.Message); HandleErrors(gameResponse, exception, 404); } else { //NOTE: Not sure if I want to do something like AutoMapper for this example. gameResponse.Game = game; gameResponse.StatusCode = 200; Log.Information("Retrieved [{NewName}] for Id: [{Id}].", gameResponse.Game.Name, id); } } catch (Exception exception) { Log.Error(exception, "Failed to get Game for title [{Id}].", id); HandleErrors(gameResponse, exception); } return(gameResponse); }
public virtual void OnGameResponse(GameResponse args) { if (GameResponse != null) { GameResponse(args); } }
public bool Update(Game newGame) { GameResponse gm = null; gm = GetAll(); try { var res = gm.Games.Find(x => x.Id == newGame.Id); if (res != null) { res.Description = newGame.Description; res.IsActive = newGame.IsActive; res.Picture = newGame.Picture; res.Size = newGame.Size; res.Title = newGame.Title; res.Selected = newGame.Selected; res.TorrentUrl = newGame.TorrentUrl; string json = gm.ToJson(); File.WriteAllText(JsonDbPath, json); return(true); } else { return(false); } } catch (Exception e) { return(false); } }
private IEnumerator publishOrJoinGame(string mapName, bool newlyCreated) { if (newlyCreated) { WWWForm gameForm = new WWWForm(); gameForm.AddField("token", LoginManager.getToken()); gameForm.AddField("mapName", mapName); WWW game = new WWW(DataServerDomain.url + "create", gameForm.data); yield return(game); GameResponse response = JsonUtility.FromJson <GameResponse>(game.text); if (response.status != 200) { Debug.Log(response.status); PhotonNetwork.Disconnect(); yield return(null); } else { gameFailed = false; ExitGames.Client.Photon.Hashtable gameIdTable = new ExitGames.Client.Photon.Hashtable(); gameIdTable.Add("gameId", response.data); PhotonNetwork.room.SetCustomProperties(gameIdTable); } } PhotonNetwork.playerName = LoginManager.getUsername(); inLobbyScene = false; PhotonNetwork.LoadLevel(mapName); }
private Task UpdateGame(string game) { _game = JsonConvert.DeserializeObject <GameResponse>(game); StateHasChanged(); Console.WriteLine("Updated game"); return(Task.CompletedTask); }
public override async Task <GameResponse> DoPlay(GameRequest request, ServerCallContext context) { _logger.LogInformation($"Player {request.Username} picked {ResultsDao.ToText(request.Pick)} against {request.Challenger}."); var challenger = _challengersService.SelectChallenger(request); var result = new GameResponse() { Challenger = request.Challenger, User = request.Username, UserPick = request.Pick }; var pick = await challenger.Pick(GetContext(context), request.TwitterLogged, request.Username); _logger.LogInformation($"Challenger {result.Challenger} picked {ResultsDao.ToText(pick.Value)} against {request.Username}."); result.ChallengerPick = pick.Value; result.IsValid = IsValid(pick); result.Result = !result.IsValid ? Result.Player : _gameService.Check(result.UserPick, result.ChallengerPick); _logger.LogInformation($"Result of User {request.Username} vs Challenger {result.Challenger}, winner: {result.Result}"); if (result.IsValid) { await _resultsDao.SaveMatch(pick, request.Username, request.Pick, result.Result); } return(result); }
public override async Task <GameResponse> DoPlay(GameRequest request, ServerCallContext context) { _logger.LogInformation($"Player {request.Username} picked {PickDto.ToText(request.Pick)} against {request.Challenger}."); var challenger = _challengersService.SelectChallenger(request); var result = new GameResponse() { Challenger = request.Challenger, User = request.Username, UserPick = request.Pick }; var pick = await challenger.Pick(GetContext(context), request.TwitterLogged, request.Username); _logger.LogInformation($"Challenger {result.Challenger} picked {PickDto.ToText(pick.Value)} against {request.Username}."); result.ChallengerPick = pick.Value; result.IsValid = IsValid(pick); result.Result = result.IsValid ? _gameService.Check(result.UserPick, result.ChallengerPick) : Result.Player; _logger.LogInformation($"Result of User {request.Username} vs Challenger {result.Challenger}, winner: {result.Result}"); if (result.IsValid && request.TwitterLogged) { await _resultsDao.SaveMatch(pick, request.Username, request.Pick, result.Result); } if (_playFabService.HasCredentials) { var username = !request.TwitterLogged ? $"${request.Username}" : request.Username; await _playFabService.UpdateStats(username, result.Result == Result.Player); } return(result); }
public async Task <GameResponse> JoinGameAsync(string connectionId, Guid gameId, string password) { if (!UsersByConnectionId.ContainsKey(connectionId)) { Logger.LogError($"Got join game message for unknown connection id '{connectionId}'"); return(GameResponse.Failure("Connection not found")); } var user = UsersByConnectionId[connectionId]; if (!GamesById.ContainsKey(gameId)) { Logger.LogError($"Got join game message for unknown game id '{gameId}'"); return(GameResponse.Failure("Game not found")); } var game = GamesById[gameId]; var joinResponse = game.Join(user, password); if (!joinResponse.Success) { return(joinResponse); } await subscriber.PublishAsync(RedisChannels.UpdateGame, JsonConvert.SerializeObject(game)); return(joinResponse); }
public void OnTopicMessageReceived(string message) { var result = StaticResources.sevicebusLogs.Where(sbl => sbl == message).FirstOrDefault(); if (result == null) { StaticResources.sevicebusLogs.Add(message); Transfer transfer = JsonConvert.DeserializeObject <Transfer>(message); if (transfer.type == MessageType.Action) { GameAction action = JsonConvert.DeserializeObject <GameAction>(transfer.message); Player player = StaticResources.PlayerList.Where(Speler => Speler.PlayerId == action.playerId).First(); if (action.action == PlayerAction.shoot) { if (action.coordinates.field == StaticResources.user.orderNumber) { // shot is directed at my field bool hit = StaticResources.field.CheckForHit(action.coordinates); bool gameOver = StaticResources.field.CheckForGameOver(); sender.SendHitResponseMessage(action.coordinates, hit, gameOver, action.playerId); } // reset timer and increase turn TimerHandler.ResetTime(); } } if (transfer.type == MessageType.Surrender) { var settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All }; SurrenderResponse response = JsonConvert.DeserializeObject <SurrenderResponse>(transfer.message, settings); Player player = StaticResources.PlayerList.Where(Speler => Speler.PlayerId == response.playerId).First(); // enter code here to display surrender message in log string logEntry = "{player} has surrendered"; logEntry = logEntry.Replace("{player}", player.name); WriteMessageToLog(logEntry); // start gameover function HandleGameOver(response.playerId, response.field); // reset timer and increase turn TimerHandler.ResetTime(); } if (transfer.type == MessageType.GameResponse) { GameResponse response = JsonConvert.DeserializeObject <GameResponse>(transfer.message); HandleHitResponse(response); } } }
public async Task <GameResponse> StartGameAsync(string connectionId) { if (!UsersByConnectionId.ContainsKey(connectionId)) { Logger.LogError($"Got start game message for unknown connection id '{connectionId}'"); return(GameResponse.Failure("Connection not found")); } var user = UsersByConnectionId[connectionId]; var game = FindGameForUser(user.Name); if (game == null) { Logger.LogError($"No games found to start for {user.Name}"); return(GameResponse.Failure("Game not found")); } if (game.Owner != user.Name) { return(GameResponse.Failure("You are not the game owner and cannot start the game.")); } await Task.Delay(1); return(GameResponse.Succeeded(game)); }
public GameResponse GetGame(string gameId) { return(_gameContext.Games .Where(x => x.Id == gameId) .Select(x => GameResponse.FromGame(x)) .FirstOrDefault()); }
public GameResponse Execute(UpdateGameTitleInput input) { var gameResponse = new GameResponse(); try { CheckInputValidity(input); Log.Information("Updating GameId: [{Id}] to new title [{NewTitle}]...", input.Id, input.NewTitle); var gameToUpdate = Repository.SingleOrDefault(game => game.Id == input.Id); if (gameToUpdate == null) { var exception = new Exception($"Failed to find game for id: [{input.Id}]."); Log.Error(exception, EXCEPTION_MESSAGE_TEMPLATE, exception.Message); HandleErrors(gameResponse, exception, 404); return(gameResponse); } gameToUpdate.Name = input.NewTitle; var updatedGame = Repository.Update(gameToUpdate); gameResponse.Game = updatedGame; gameResponse.StatusCode = 200; Log.Information("Successful updated GameId: [{Id}] to title [{NewTitle}].", input.Id, input.NewTitle); } catch (Exception exception) { Log.Error(exception, EXCEPTION_MESSAGE_TEMPLATE, exception.Message); HandleErrors(gameResponse, exception); } return(gameResponse); }
public static GameResponse GetAccountGames(ulong steamID) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Global.gamesURL + steamID); request.ContentType = "application/json; charset=utf-8"; HttpWebResponse response = request.GetResponse() as HttpWebResponse; string data = ""; using (Stream responseStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); data = reader.ReadToEnd(); } //Console.WriteLine("Data return " + data); Dictionary <string, GameResponse> r = JsonConvert.DeserializeObject <Dictionary <string, GameResponse> >(data); //string steamID = ""; GameResponse objData = r["response"]; /* * Console.WriteLine("Game Count: " + objData.game_count); * for(int i =0;i<objData.games.Count;i++) * { * Console.WriteLine("Game appID: " + objData.games[i].appid); * Console.WriteLine("Game Name: " + objData.games[i].name); * Console.WriteLine("Game Image Icon Hash: " + objData.games[i].img_icon_url); * Console.WriteLine("Game Image Logo Hash: " + objData.games[i].img_logo_url); * Console.WriteLine("Playtime Total: " + objData.games[i].playtime_forever); * if(objData.games[i].playtime_2weeks != null) * Console.WriteLine("Playtime Last 2 Weeks: " + objData.games[i].appid +"\n"); * }*/ return(objData); }
private void OnTimeOut(GameResponse response) { Request waitingRequest = _waitingRequests[response]; _timerRequest.Remove(response); _waitingRequests.Remove(response); //SendRequest(Servers.Game, waitingRequest.RequestType, response, waitingRequest.OnSuccess, waitingRequest.OnFail); }
public Game(GameResponse response) { AppId = response.appid; Name = response.name; PlaytimeForever = response.playtime_forever; HasCommunityVisibleStats = response.has_community_visible_stats; IconUrl = response.img_icon_url; LogoUrl = response.img_logo_url; }
private void SendRequest(string uri, string parameters) { using (var client = new WebClient()) { client.Headers[HttpRequestHeader.ContentType] = Client.ContentType; var json = client.UploadString(uri, parameters); this.Response = GameResponse.FromJson(json); } }
public void Update(GameResponse rawData) { _rawData = rawData; _map.Parse(rawData.game.board.tiles); //TODO: --> stuff like this needs to be bot specific foreach (var q in _charts.Values) { UpdateChart(q.Grid, q.SeedFunction, q.CostFunction); } }
public GameResponse Game(GameRequest gameRequest) { using (new OperationContextScope((IClientChannel)proxy)) { AuthenticatedUser currentLogedUser = AuthenticatedUser.Instance; WebOperationContext.Current.OutgoingRequest.Headers.Add("Authentication", currentLogedUser.Authentication.ToString()); GameResponse response = proxy.Game(gameRequest); return(response); } }
// GET: api/Games/1234 public async Task<IHttpActionResult> Get(string id) { var gameDocument = await _games.GetGame(id); if (gameDocument == null) { return NotFound(); } Game game = new Game(gameDocument); var gameResponse = new GameResponse(game); return Ok(gameResponse); }
public GameResponse GetAll() { GameResponse gm = null; var json = ReadFile(); if (json != null) { gm = GameResponse.FromJson(json); } return(gm); }
public GameResponse CreateGame() { var game = new Game { Id = KeyUtils.RandomString(6) }; _currentGames.Add(game.Id, game); _gameContext.Games.Add(game); _gameContext.SaveChanges(); return(GameResponse.FromGame(game)); }
public async Task <IActionResult> Get(int id) { try { GameResponse game = await _serviceGame.GetById(id); return(Ok(game)); } catch (Exception) { return(BadRequest(new GameResponse(NotificacaoDto.ErroPadrao))); } }
private void OnFindGame(GameResponse gameResponse) { if (!gameResponse.gamefound) { playerRequest.FindGame(this); } else { //Debug.Log(gameResponse.game.gamedata.bplayer); playerRequest.GetAllGameInfo(gameResponse.game.id, this); //SetLobbyRequestInProgress(false); } }
public GameDTO ConvertToGameDTO(GameResponse game) { return(new GameDTO { GameId = game.Id, Name = game.Name, Added = game.Added, Metacritic = game.Metacritic, Rating = game.Rating, Released = game.Released, Updated = game.Updated }); }
// used to mark a hit in the field + log message public GameResponse GetHitResponseDummyData() { List <Player> players = StaticResources.PlayerList; /* * Fields == 2-4 * col == 0-9 * row == 0-9 */ ChangeLog log = StaticResources.log; int logCount = log.shotLog.Count; int field = 2; int col = 0; int row = 0; if (logCount > 0) { ICoordinate coordinates = log.shotLog.Last().coordinate; if (coordinates.col == 9 && coordinates.row == 9 && coordinates.field == 4) { return(null); } col = (coordinates.col + 1) < 10 ? (coordinates.col + 1) : 0; int increase = col == 0 ? 1 : 0; row = (coordinates.row + increase) < 10 ? (coordinates.row + increase) : 0; increase = row == 0 && col == 0 ? 1 : 0; field = (coordinates.field + increase) < 10 ? (coordinates.field + increase) : 0; } Random rnd = new Random(); int hit = rnd.Next(0, 2); GameResponse response = new GameResponse() { playerId = players[1].PlayerId, fieldNumber = field, coordinates = new Coordinate() { field = field, col = col, row = row }, hit = hit == 0 ? true : false }; return(response); }
public Knowledge(GameResponse rawData) { _rawData = rawData; int mapSize = _rawData.game.board.size; _map = new TileMap(mapSize); _map.Parse(_rawData.game.board.tiles); int index = 0; _heroes = _rawData.game.heroes.Select(data => new HeroInfo(this, index++)).ToList(); _hero = _heroes.First(h => h.ID == _rawData.hero.id); }
public void HandleHitResponse(GameResponse gameResponse = null) { if (gameResponse == null) { return; } GameResponse response = gameResponse == null?dummy.GetHitResponseDummyData() : gameResponse; ShotLog shotLog = new ShotLog() { coordinate = gameResponse.coordinates, hit = gameResponse.hit }; StaticResources.log.shotLog.Add(shotLog); Player player = StaticResources.PlayerList.Where(p => p.PlayerId == response.playerId).FirstOrDefault(); string newstring = _placeholderShotReponse.Replace("{player}", player.name) .Replace("{field}", response.coordinates.field.ToString()) .Replace("{row}", response.coordinates.row.ToString()) .Replace("{col}", response.coordinates.col.ToString()) .Replace("{hit}", response.hit ? "landed a hit" : "missed"); WriteMessageToLog(newstring); if (player.PlayerId == StaticResources.user.PlayerId) { if (response.hit == true) //highscore bijhouden { StaticResources.records.hits += 1; StaticResources.records.currenctHitStreak += 1; if (StaticResources.records.currenctHitStreak > StaticResources.records.highestHitStreak) { StaticResources.records.highestHitStreak = StaticResources.records.currenctHitStreak; } } else { StaticResources.records.currenctHitStreak = 0; } } // start gameover function if player is gameover if (response.gameOver) { HandleGameOver(response.senderId); } }
protected override async Task OnInitAsync() { try { _error = false; _game = await Http.GetJsonAsync <GameResponse>($"api/Game/{Id}"); await SetupRefresh(); } catch (Exception e) { _error = true; _errorMessage = e.Message; } }
/// <summary> /// System error message display to client /// </summary> /// <param name="res">Response error message</param> void IGameManagerCallback.CatchError(GameResponse res) { System.Console.WriteLine(res.Message); }
/// <summary> /// Response on client's attempt to watch the game /// </summary> /// <param name="res">Response with success or failure message</param> void IGameManagerCallback.HasWatchedGame(GameResponse res) { System.Console.WriteLine(res.Message); }