public virtual GameMoveType GetNextMove(GameState gameState, IGameInteractionService interactionService) { var loggingService = ServiceContainer.Resolve<ILoggingService> (); var emptyLocation = gameState.GameField.GetUnusedItemLocation (); // Prepare a path to the target treasure if it hasn't happened yet. The AI decides first what path it will take, then it will follow it until // it fails or until it reaches the treasure. The current path is reset in UpdatePlayer() because this means that it's the other player's turn. if (this.currentPath == null || this.currentPath.Count <= 0) { #if EXTENSIVE_LOGGING loggingService.Log ("AI calculates a new path."); #endif // Populate the path finding algorithm and start at the unused item location. var populatedGrid = AIHelpers.PreparePathGrid (gameState.GameField, emptyLocation, gameState.GetActiveCard()); // Get the location of the current active card. This may return NULL if the AI cannot remember the location. GridLocation currentTreasureLocation = this.GetPresumedLocationOfTreasure(gameState.GetActiveCard()); // The AI has no clue where the active treasure is. It will pick a random location to move to. if (currentTreasureLocation == null) { currentTreasureLocation = this.GetRandomLocationAvoidingTreasures (gameState); #if EXTENSIVE_LOGGING loggingService.Log ("AI has no clue where '{0}' is located. Will move to random location {1}.", gameState.GetActiveCard(), currentTreasureLocation); #endif } // Log how AI calculates the distances. #if EXTENSIVE_LOGGING loggingService.Log ("AI sees the grid with these distances, starting at {0} to reach (presumed!) {1} at {2}:", emptyLocation, gameState.GetActiveCard(), currentTreasureLocation); for (int row = 0; row < populatedGrid.Rows; row++) { string s = string.Empty; for (int col = 0; col < populatedGrid.Columns; col++) { s += populatedGrid.GetItem (row, col).ToString ("000") + " |"; } loggingService.Log (s); } #endif // Find the path from the current unused location to the treasure, avoiding all other treasures if possible. var pathList = AIHelpers.GetPathToLocation (gameState.GameField, populatedGrid, emptyLocation, currentTreasureLocation, gameState.GetActiveCard()); // We need to reverse it to get the corret order when copying onto a stack. pathList.Reverse (); // Copy the path onto a stack for better processing. this.currentPath = new Stack<GridLocation>(pathList); pathList = null; // Log the path the AI will go. #if EXTENSIVE_LOGGING loggingService.Log ("AI's path to (presumed!) {0}:", gameState.GetActiveCard()); for (int row = 0; row < populatedGrid.Rows; row++) { string s = string.Empty; for (int col = 0; col < populatedGrid.Columns; col++) { var isPath = (from pathItem in this.currentPath where pathItem.Row == row && pathItem.Column == col select pathItem).Any (); if (isPath) { s += populatedGrid.GetItem (row, col).ToString ("000") + "X|"; } else { s += populatedGrid.GetItem (row, col).ToString ("000") + " |"; } } loggingService.Log (s); } #endif // A correct path has to contain at least two locations: the start and the target. if (this.currentPath.Count < 2) { // The AI failed and could not find a path from the unused location to the active treasure. Stupid AI. Should not happen and means there is a problem in the algorithm. loggingService.Log ("AI path is invalid. Path length: [{0}]. Next move will be random.", this.currentPath.Count.ToString ()); // Return a random move. var randomMove = AIHelpers.GetRandomMove (gameState.GameField, emptyLocation, gameState.GetActiveCard()); loggingService.Log ("AI moves randomly: {0}", randomMove); // Bail out. return randomMove; } else { // The found path is valid. Remove the first entry because this is the start location. No need to move, we're already there. // TODO: Verify that if the next treaure is the one that is currently active, the AI will spot that it is already uncovered. this.currentPath.Pop (); } } // Here the current path has either just been populated or we're following a previously populated path. // Get next location to move to. var moveLocation = this.currentPath.Pop (); // Remember that we visited that location. We want to avoid it for the next couple of moves. this.lastVisitedLocations.Enqueue (moveLocation); // Remember the treasure that has just been discoverd fully. this.LearnAboutTreasure (gameState.GameField.GetItem(moveLocation).Treasure, moveLocation); // Convert location to a move. var move = AIHelpers.GetMoveToAdjacentLocation (emptyLocation, moveLocation); loggingService.Log ("AI will move from [{0}] to [{1}], this is a move of type [{2}].", emptyLocation, moveLocation, move); // The AI forgets a bit after each move. this.ForgetTreasures (); return move; }
/// <summary> /// Gets a random location on the board and avoids treasures. /// </summary> /// <returns>The random location avoiding treasures.</returns> /// <param name="gameState">Game state.</param> protected virtual GridLocation GetRandomLocationAvoidingTreasures(GameState gameState) { var platformServices = ServiceContainer.Resolve<IPlatformServices> (); var loggingService = ServiceContainer.Resolve<ILoggingService> (); GridLocation location; bool continueRandomization = false; // Loop until a (presumably) empty location was found. do { // Get a location that has not been visited recently. bool isRememberedLocation = false; do { location = new GridLocation (platformServices.GetRandomNumber (0, gameState.GameField.Rows), platformServices.GetRandomNumber (0, gameState.GameField.Columns)); isRememberedLocation = this.lastVisitedLocations.Contains (location); #if EXTENSIVE_LOGGING loggingService.Log("Randomized location '{0}' was picked previously? {1}.", location, isRememberedLocation); #endif } while(isRememberedLocation); // Remember the location to prevent visiting it again immediately. this.lastVisitedLocations.Enqueue (location); // Now check if the location has a treasure. If yes, we don't want to go there unless it is the current active treasure. var treasureMemory = this.HasLocationPresumablyTreasure(location); // We want to pick a location that we don't know about. if(treasureMemory == LocationMemory.DontKnow) { // Let's head there if the AI does not know about the location. continueRandomization = false; #if EXTENSIVE_LOGGING loggingService.Log("Randomized location. AI does not know what's at '{0}'. Active treasure: {1}.", location, gameState.GetActiveCard()); #endif } else if(treasureMemory == LocationMemory.HasNothing) { // If the AI knows that there is nothing at the location, it won't go there. continueRandomization = true; #if EXTENSIVE_LOGGING loggingService.Log("Randomized location. AI knows that there is nothing at '{0}'. Active treasure: {1}.", location, gameState.GetActiveCard()); #endif } else if(treasureMemory == LocationMemory.HasTreasure) { // If there is a treasure, the AI will avoid it, untless it is the current searched treasure. var treasureItem = gameState.GameField.GetItem(location).Treasure; if(treasureItem == gameState.GetActiveCard()) { continueRandomization = false; } else { // Keep searching a new random location. continueRandomization = true; } #if EXTENSIVE_LOGGING loggingService.Log("Randomized location. AI knows there is a treasure '{0}'. Active treasure: {1}.", location, gameState.GetActiveCard()); #endif } } while(continueRandomization); return location; }
/// <summary> /// Draws the game field. /// </summary> /// <param name="gameState">Game state.</param> public void DrawGameField(GameState gameState) { int right = gameState.GameField.Columns * colScale + gameState.GameField.Columns; // Show the current player's name. this.Write (0, right + 5, ConsoleColor.Gray, "Current Player: {0}", gameState.CurrentPlayer.ToString ()); // Show the current card to be searched. this.Write (2, right + 5, ConsoleColor.Gray, "Search treasure: {0}", gameState.GetActiveCard()); this.Write (3, right + 5, ConsoleColor.Gray, "Treasures left: {0}", gameState.Cards.Count); // Show the scores. this.Write (5, right + 5, ConsoleColor.Gray, "Local player score: {0}", gameState.LocalPlayerScore); this.Write (6, right + 5, ConsoleColor.Gray, "Opponent player score: {0}", gameState.OpponentPlayerScore); // Draw a grid. for (int row = 0; row < gameState.GameField.Rows; row++) { for (int col = 0; col < gameState.GameField.Columns; col++) { this.DrawHorizLine (row, col); this.DrawVertLine (row, col); } } // Draw the bottom most horizontal line. for (int col = 0; col < gameState.GameField.Columns; col++) { this.DrawHorizLine (gameState.GameField.Rows, col); } // Draw the right most vertical line./ for (int row = 0; row < gameState.GameField.Rows; row++) { this.DrawVertLine (row, gameState.GameField.Columns); } // Draw the bottom right corner of the game field. screen.SetItem (gameState.GameField.Rows * rowScale + gameState.GameField.Rows, gameState.GameField.Columns * colScale + gameState.GameField.Columns, '+'.ToColorChar(gridColor)); // Draw representations of the game field content. for (int row = 0; row < gameState.GameField.Rows; row++) { for (int col = 0; col < gameState.GameField.Columns; col++) { GameFieldItem item = gameState.GameField.GetItem (row, col); ColorChar pyramidChar = new ColorChar(); switch(item.Pyramid) { case PyramidType.PyramidA: pyramidChar = 'X'.ToColorChar (ConsoleColor.White, ConsoleColor.DarkRed); break; case PyramidType.PyramidB: pyramidChar = 'X'.ToColorChar (ConsoleColor.White, ConsoleColor.Blue); break; case PyramidType.None: pyramidChar = ' '.ToColorChar (ConsoleColor.Black); break; default: throw new InvalidOperationException ("Unhandled pyramid type!"); } for(int i = 0; i < rowScale; i++) { for(int j = 0; j < colScale; j++) { screen.SetItem (row * rowScale + row + 1 + i, col * colScale + col + 1 + j, pyramidChar); } } // If there's a treasure, show the first few characters to ease debugging. if (item.Treasure != TreasureType.None) { // By default show treasure if it is at the empty location. if (this.ShowTreasureNames || pyramidChar.C == ' ') { var treasureString = item.Treasure.ToString (); for (int j = 0; j < colScale; j++) { if (j < treasureString.Length) { screen.SetItem (row * rowScale + row + 1, col * colScale + col + 1 + j, treasureString [j].ToColorChar (ConsoleColor.Black, ConsoleColor.Yellow)); } else { screen.SetItem (row * rowScale + row + 1, col * colScale + col + 1 + j, ' '.ToColorChar (ConsoleColor.Black, ConsoleColor.Yellow)); } } } } } } }