using ProjectGrid.AI; using ProjectGrid.Models; using ProjectGrid.TicTacToc; using System; using System.Collections.Generic; namespace ProjectGrid { public interface ITicTacTocManager { public void Restart(Mode mode); public TicTacTocResponse NextMove(TicTacTocRequest move); public TicTacTocResponse GetBoard(); } public class TicTacTocManager : ITicTacTocManager { private enum State { PLAYING, GAME_OVER } private State _state; private Mode _mode; private TicTacTocBrain _brain; //private ITicTacToctRepository _repo; private int _currentPlayer; private TicTacTocBoard _board; public TicTacTocBoard Board => _board; public int[] _playerScore = new int[] { 0, 0, 0 }; public TicTacTocManager(/*ITicTacToctRepository repo*/) { //_repo = repo; _currentPlayer = 1; Restart(Mode.CROSS_PLAYER); } public TicTacTocResponse NextMove(TicTacTocRequest move) { TicTacTocResponse response = new TicTacTocResponse(); if (_state != State.GAME_OVER) { if (_board.SetFieldValue(_currentPlayer, move.Field)) { response.Winning = _board.ValueWon(_currentPlayer); if (_currentPlayer > 0 && response.Winning != null) { response.PlayerWon = _currentPlayer; _state = State.GAME_OVER; _playerScore[_currentPlayer]++; } else if (null != _brain) { if (_board.Full) { _playerScore[0]++; _state = State.GAME_OVER; response.PlayerWon = 0; return response; } int ai = 3 - _currentPlayer; var turn = _brain.Turn(); Console.WriteLine($"Brain made move {turn} for player {ai}"); _board.SetFieldValue(ai, turn); response.Winning = _board.ValueWon(ai); if (response.Winning != null) { response.PlayerWon = ai; _playerScore[ai]++; _state = State.GAME_OVER; } } else { // switch between 1 and 2 _currentPlayer = 3 - _currentPlayer; } } if (_board.Full) { _playerScore[0]++; _state = State.GAME_OVER; } } response.Board = _board.Field; response.PlayerScore = new List(_playerScore); return response; } public void Restart(Mode mode) { _mode = mode; _currentPlayer = 1; _board = new TicTacTocBoard(); _state = State.PLAYING; _brain = null; if (Mode.TWO_PLAYER != mode) _brain = new TicTacTocBrain(_board, 3 - (int)mode); } public TicTacTocResponse GetBoard() { TicTacTocResponse response = new TicTacTocResponse(); response.Board = _board.Field; return response; } } }