public ActionResult Index(TicTacToeGameRequest gameRequest) { switch (gameRequest.GameMethod) { case "Get Placement": var getPlacementRequest = new GetPlacementRequest(); UpdateModel(getPlacementRequest); var response = GetPlacement(getPlacementRequest); return(Json(response)); default: throw new Exception("Unhandled game method: " + gameRequest.GameMethod); } }
public override IGameResponse ProcessRequest <T>(IGameRequest request) { IGameResponse response = null; if (request is GetPlacementRequest) { GetPlacementRequest gpr = (GetPlacementRequest)request; response = GetPlacementRequest(gpr); } else { throw new NotImplementedException(); } return(response); }
public override IGameStatus ProcessGameStep() { // Get the next placement for the current player var request = new GetPlacementRequest(_CurrentPlayer.Name, _Grid); var response = _CurrentPlayer.ProcessRequest <GetPlacementResponse>(request) as GetPlacementResponse; // Is it a valid placement? if (IsValidPlacement(response.Placement)) { // Place it _Grid[response.Placement.X][response.Placement.Y] = _CurrentPlayer.Name; // Switch the current player to the next one _CurrentPlayer = _CurrentPlayer == Players[0] ? Players[1] : Players[0]; } return(GetGameStatus()); }
protected virtual GetPlacementResponse GetPlacement(GetPlacementRequest request) { GetPlacementResponse response = new GetPlacementResponse(); // Get a list of all empty locations List <Coordinate> emptyLocations = new List <Coordinate>(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (string.IsNullOrEmpty(request.Grid[i][j])) { emptyLocations.Add(new Coordinate(i, j)); } } } // Can we win? Coordinate winningLocation = null; foreach (Coordinate emptyLocation in emptyLocations) { if (IsWinningLocation(emptyLocation, request.Grid, request.MyName)) { winningLocation = emptyLocation; break; } } if (winningLocation != null) { response.Placement = winningLocation; return(response); } // Can we keep the opponent from winning? string opponentName = string.Empty; for (int i = 0; i < 3 && opponentName.Length == 0; i++) { for (int j = 0; j < 3 && opponentName.Length == 0; j++) { string name = request.Grid[i][j]; if (string.IsNullOrEmpty(name)) { continue; } if (name == request.MyName) { continue; } opponentName = name; } } if (!string.IsNullOrEmpty(opponentName)) { winningLocation = null; foreach (Coordinate emptyLocation in emptyLocations) { if (IsWinningLocation(emptyLocation, request.Grid, opponentName)) { winningLocation = emptyLocation; break; } } if (winningLocation != null) { response.Placement = winningLocation; return(response); } } // Choose randomly Random random = new Random(); Coordinate placement = emptyLocations[random.Next(emptyLocations.Count)]; response.Placement = placement; return(response); }