Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.8 kB
2
Indexable
Never
using TicTacToe;

public class AIPlayer
{
    public enum Difficulty { Easy, Medium, Hard }

    public Difficulty difficulty { get; private set; }

    public AIPlayer(Difficulty difficulty)
    {
        this.difficulty = difficulty;
    }

    public (int, int) GetMove(Game game)
    {
        var availableMoves = game.GetAvailableMoves();
        if (availableMoves.Count == 0)
        {
            return (-1, -1);  // no available moves
        }

        var random = new Random();
        if (difficulty == Difficulty.Easy)
        {
            return availableMoves[random.Next(availableMoves.Count)];
        }

        var winningMove = FindWinningMove(game, Game.SquareState.O);
        if (winningMove.Item1 != -1)
        {
            return winningMove;
        }

        if (difficulty == Difficulty.Medium)
        {
            var blockingMove = FindWinningMove(game, Game.SquareState.X);
            if (blockingMove.Item1 != -1)
            {
                return blockingMove;
            }
        }

        return availableMoves[random.Next(availableMoves.Count)];
    }

    private (int, int) FindWinningMove(Game game, Game.SquareState player)
    {
        var availableMoves = game.GetAvailableMoves();
        foreach (var move in availableMoves)
        {
            game.MakeMove(move.Item1, move.Item2, player);
            if (game.CheckForWinner())
            {
                game.MakeMove(move.Item1, move.Item2, Game.SquareState.Empty);  // undo move
                return move;
            }
            game.MakeMove(move.Item1, move.Item2, Game.SquareState.Empty);  // undo move
        }
        return (-1, -1);  // no winning move found
    }
}