Beispiel #1
0
        static void Main(string[] args)
        {
            // This class should be treated as read-only for your purposes, but feel free to see how it works
            Board game = new Board();

            int player = 2;

            while (!game.IsWinningBoard() && !game.IsCatsGame())
            {
                player = player % 2 + 1; // change the players
                Console.Out.Write("Input the square number for player " + player + "'s move: ");
                string squareAsString = Console.In.ReadLine();
                int square;
                while (!Int32.TryParse(squareAsString, out square) && square >= 1 && square <= 9)
                {
                    Console.Out.WriteLine("An invalid square was entered, please try again.");
                    Console.Out.Write("Input the square number for player " + player + "'s move: ");
                    squareAsString = Console.In.ReadLine();
                }

                game.PrintBoard();
            }

            if (game.IsWinningBoard())
            {
                Console.Out.WriteLine("Player " + player + " is the winner!");
            }
            else
            {
                Console.Out.WriteLine("Cat's game!");
            }

            Console.ReadKey(); // stop the console from closing automatically
        }
Beispiel #2
0
        public void PlayGame()
        {
            Initialize();
            int numPlayers = PromptForGameMode();

            if (numPlayers == 0)
            {
                _player1 = CreateComputerPlayer(0);
                _player2 = CreateComputerPlayer(0);
            }
            else if (numPlayers == 1)
            {
                _player1 = PromptToCreatePlayer();
                _player2 = CreateComputerPlayer(1);
            }
            else
            {
                _player1 = PromptToCreatePlayer("X");
                _player2 = PromptToCreatePlayer("O");
            }

            bool playAgain = false;
            do
            {
                _board = new Board();
                playAgain = ProcessTurnsAndAskToPlayAgain();
            } while (playAgain);
        }
Beispiel #3
0
 public void AskForPlayersMove(Player pl, Board gameBoard)
 {
     int gameBoardSize = gameBoard.GetBoardSize();
     selectedColumn = moves[moveCount, 0];
     selectedRow = moves[moveCount, 1];
     moveCount++;
 }
        private static bool MakePlay(Board board, string playerName, string play)
        {
            var player = new Player();

            if (board.Player1.Name.Equals(playerName))
            {
                player = board.Player1;
            }
            else if (board.Player2 == null)
            {
                player.Name = playerName;
                player.WaitingForOpponent = false;
                player.Simbolo = "O";

                board.Player2 = player;
            }
            else if (board.Player2.Name.Equals(playerName))
            {
                player = board.Player2;
            }
            else
            {
                return false; // player not in game
            }

            if (player.WaitingForOpponent) return false;

            int position = -1;
            int.TryParse(play, out position);

            var gameOver = board.Play(player, position);

            return true;
        }
Beispiel #5
0
		public void playTurnTest ()
		{
			string errMsg;
			int boardSize = 3;
			Player player1;
			Player[][] player;
			Board boardTEST;
			//L'objet PrivateObject permet d'acceder aux methodes et attributs
			//normalement prives de l'objet clone

			player1 = new Player("Bob", "O");
			boardTEST = new Board(boardSize);

			for (int i = 1; i <= 9;i++ )
			{
				boardTEST.playTurn(i, player1);
				player = boardTEST.BoardState;
				var length = player.GetLength (0);
				errMsg = "Erreur : playTurn n'a pas fonctionné sur la cellule "+i;
				if (i % length == 0){
					Assert.IsTrue(Board.Equals(player[i/length-1][length-1],player1),errMsg);
				} 
				else {
					Assert.IsTrue(Board.Equals(player[(int)Math.Truncate((double)(i / length))][i % length - 1],player1), errMsg);
				}
			}

		}
Beispiel #6
0
 public void AskForPlayersMove(Player pl, Board gameBoard)
 {
     int gameBoardSize = gameBoard.GetBoardSize();
     ConsoleKeyInfo input ;
     do
     {
         Console.WriteLine(pl.GetPlayerName() + " it is your turn.  ");
         Console.Write("Move the cursor with the arrow keys \nand confirm the selection with spacebar");
         input = Console.ReadKey();
         if (input.Key == ConsoleKey.UpArrow)
         {
             selectedRow = selectedRow - 1;
         }
         if (input.Key == ConsoleKey.DownArrow)
         {
             selectedRow = selectedRow + 1;
         }
         if (input.Key == ConsoleKey.LeftArrow)
         {
             selectedColumn = selectedColumn - 1;
         }
         if (input.Key == ConsoleKey.RightArrow)
         {
             selectedColumn = selectedColumn + 1;
         }
         selectedRow = CorrectOutOfBounds(selectedRow, gameBoardSize);
         selectedColumn = CorrectOutOfBounds(selectedColumn, gameBoardSize);
         ClearScreen();
         Draw(gameBoard);
     } while (input.Key != ConsoleKey.Spacebar);
 }
Beispiel #7
0
        public void Test_WallE_Engine_First_Row()
        {
            var       gameBoard = new TicTacToe.Board();
            GameState state     = GameState.Playing;

            var    wallE  = new Wall_E_Engine();
            int    moves  = 1;
            Marker marker = Marker.X;

            //Play the first row
            state = gameBoard.Play(new Space {
                Marker = marker, Number = moves
            });
            marker = SwapPlayer(marker);
            while (state == GameState.Playing && moves < 9)
            {
                moves++;
                Space aIMove = wallE.GetNextMove(gameBoard, marker);
                state = gameBoard.Play(new Space {
                    Marker = marker, Number = aIMove.Number
                });
                while (state == GameState.InvalidMove)
                {
                    aIMove = wallE.GetNextMove(gameBoard, marker);
                    state  = gameBoard.Play(new Space {
                        Marker = marker, Number = aIMove.Number
                    });
                }
                marker = SwapPlayer(marker);
            }
            Debug.WriteLine($"Game result of {nameof(state)} umber of moves {moves}.");
            Assert.IsTrue(state == GameState.Winner || state != GameState.Tie);
        }
 /// <summary>
 /// Constructs a new TicTacToe game using the specified player's pieces.
 /// 
 /// </summary>
 /// <param name="player1Piece">Player one's piece</param>
 /// <param name="player2Piece">Player two's piece</param>
 public TicTacToeGame(Board.Pieces player1Piece, Board.Pieces player2Piece)
 {
     this.player1Piece = player1Piece;
     this.player2Piece = player2Piece;
     board = new Board();
     moves = new Stack<TicTacToeMove>();
 }
Beispiel #9
0
 public void InitializingBoardCreatesNumberSquaredPositions()
 {
     Board board = new Board(4);
     IEnumerable<BoardCharacter> positions = board.GetPositions();
     int positionCount = positions.Count();
     Assert.AreEqual(positionCount, 16);
 }
        public void GameClassDisplaysBoardAtEachMove()
        {
            Board board = new Board(3);
            Mock<IPlayer> player1 = new Mock<IPlayer>();
            player1.Setup(player => player.GetCharacterType()).Returns(BoardCharacter.X);
            Mock<IPlayer> player2 = new Mock<IPlayer>();
            player2.Setup(player => player.GetCharacterType()).Returns(BoardCharacter.Zero);
            var firstPlayerMoves = new Queue<Tuple<int, int>>(new[]
            {
                Tuple.Create(0, 0), Tuple.Create(0, 1), Tuple.Create(0, 2)
            });
            player1.Setup(player => player.MakeMove(board)).Returns(() => firstPlayerMoves.Dequeue());

            var secondPlayerMoves = new Queue<Tuple<int, int>>(new[]
            {
                Tuple.Create(1, 0), Tuple.Create(1, 1)
            });
            player2.Setup(player => player.MakeMove(board)).Returns(() => secondPlayerMoves.Dequeue());

            Game game = new Game(board, player1.Object, player2.Object, gameSubscriber.Object, 0);
            game.Run();
            gameSubscriber.Verify(g => g.GameUpdate(It.Is<string>(s => s == "X _ _\n_ _ _\n_ _ _")), Times.Once());
            gameSubscriber.Verify(g => g.GameUpdate(It.Is<string>(s => s == "X _ _\nO _ _\n_ _ _")), Times.Once());
            gameSubscriber.Verify(g => g.GameUpdate(It.Is<string>(s => s == "X X _\nO _ _\n_ _ _")), Times.Once());
            gameSubscriber.Verify(g => g.GameUpdate(It.Is<string>(s => s == "X X _\nO O _\n_ _ _")), Times.Once());
            gameSubscriber.Verify(g => g.GameUpdate(It.Is<string>(s => s == "X X X\nO O _\n_ _ _")), Times.Once());
        }
Beispiel #11
0
        public void Test_Is_Tie()
        {
            var       gameBoard = new TicTacToe.Board();
            GameState state;

            state = gameBoard.Play(new Space {
                Marker = Marker.X, Number = 0
            });
            state = gameBoard.Play(new Space {
                Marker = Marker.O, Number = 1
            });
            state = gameBoard.Play(new Space {
                Marker = Marker.X, Number = 2
            });
            state = gameBoard.Play(new Space {
                Marker = Marker.O, Number = 4
            });
            state = gameBoard.Play(new Space {
                Marker = Marker.X, Number = 3
            });
            state = gameBoard.Play(new Space {
                Marker = Marker.O, Number = 5
            });
            state = gameBoard.Play(new Space {
                Marker = Marker.X, Number = 7
            });
            state = gameBoard.Play(new Space {
                Marker = Marker.O, Number = 6
            });
            state = gameBoard.Play(new Space {
                Marker = Marker.X, Number = 8
            });

            Assert.IsTrue(state == GameState.Tie);
        }
        public void GameClassDisplaysMoveUpdatesAfter1Second()
        {
            Board board = new Board(3);
            Mock<IPlayer> player1 = new Mock<IPlayer>();
            player1.Setup(player => player.GetCharacterType()).Returns(BoardCharacter.X);
            Mock<IPlayer> player2 = new Mock<IPlayer>();
            player2.Setup(player => player.GetCharacterType()).Returns(BoardCharacter.Zero);
            var firstPlayerMoves = new Queue<Tuple<int, int>>(new[]
            {
                Tuple.Create(0, 0), Tuple.Create(0, 1), Tuple.Create(2, 0), Tuple.Create(2, 1), Tuple.Create(1, 2)
            });
            player1.Setup(player => player.MakeMove(board)).Returns(() => firstPlayerMoves.Dequeue());

            var secondPlayerMoves = new Queue<Tuple<int, int>>(new[]
            {
                Tuple.Create(1, 0), Tuple.Create(1, 1), Tuple.Create(0, 2), Tuple.Create(2, 2)
            });
            player2.Setup(player => player.MakeMove(board)).Returns(() => secondPlayerMoves.Dequeue());

            Game game = new Game(board, player1.Object, player2.Object, gameSubscriber.Object);

            List<DateTime> updateTimes = new List<DateTime>();
            gameSubscriber.Setup(x => x.GameUpdate(It.IsAny<string>())).Callback(() => updateTimes.Add(DateTime.Now));
            DateTime start = DateTime.Now;
            game.Run();
            DateTime previousDateTime = start;
            foreach (var updateTime in updateTimes)
            {
                Assert.IsTrue(updateTime - previousDateTime > new TimeSpan(0,0,0,0,900));
                Assert.IsTrue(updateTime - previousDateTime < new TimeSpan(0, 0, 0, 1, 100));
                previousDateTime = updateTime;
            }
        }
		public HumanPlayer(string name, Board.Pieces p)// HACK:       , TicTacToeForm tttf)
			: base(name, p)
		{

			// HACK:                   this.ticTacToeForm = tttf;

		}
Beispiel #14
0
 public int makeMove(Board board)
 {
     bestMove = 0;
     //int score = minimaxab (board, 9, -100, 100, true);
     int score = minimax (board, cPlayer, 9);
     Console.WriteLine ("Score: " + score);
     return bestMove;
 }
Beispiel #15
0
 public Grid(Vector2 position, Vector2 size, int cellSize, Board board)
     : base(board.Game)
 {
     _position = position;
     _size = size;
     _cellSize = cellSize;
     _board = board;
 }
Beispiel #16
0
 public Board newBoard(int move, char p)
 {
     Board copy = new Board ();
     for (int i=0;i<board.Length;i++) {
         copy.makeMove (i, board [i]);
     }
     copy.makeMove (move, p);
     return copy;
 }
 /// <summary>
 /// Constructor: Initializes the Node with given Board, marked at row and col position
 /// </summary>
 /// <param name="board">Board to copy into new Node</param>
 /// <param name="row">Marked where in Row</param>
 /// <param name="col">Marked where in Column</param>
 public GameTreeNode(Board board, int row, int col)
 {
     // Call Board base to copy the given Board into current Node
     _nodeBoard = new Board(board);
     Alpha = 0;
     Beta = 0;
     _row = row;
     _column = col;
 }
Beispiel #18
0
      /// <summary>
      /// Create a board by copying the squares from an existing board
      /// </summary>
      /// <param name="sourceBoard">Board to copy</param>
      public Board(Board sourceBoard)
      {
         _squares = new Square[3, 3];

         if (sourceBoard != null)
         {
            Array.Copy(sourceBoard.Squares, Squares, sourceBoard.Squares.Length);
         }
      }
Beispiel #19
0
 public Game(int players, int cpu)
 {
     turn = 0;
     cpuPlayer = cpu;
     pieces = new char[2] { 'X', 'O' };
     board = new Board ();
     numMoves = 0;
     numPlayers = players;
 }
 /// <summary>
 /// Constructs a new Node
 /// </summary>
 /// <param name="b">The board that the Node will use to evaluate itself and generate its children</param>
 /// <param name="parent">The parent of this node</param>
 /// <param name="move">The move from the parent's board that generated this node's board</param>
 public Node(Board b, Node parent, TicTacToeMove move)
 {
     this.board = b;
     this.parent = parent;
     this.move = move;
     if (parent != null)
         myPiece = Board.GetOponentPiece(parent.MyPiece);
     children = new List<Node>();
 }
Beispiel #21
0
 public void InitializingBoardCreatesEmptyBoard()
 {
     Board board = new Board(3);
     IEnumerable<BoardCharacter> positions = board.GetPositions();
     foreach (var boardPosition in positions)
     {
         Assert.AreEqual(boardPosition, BoardCharacter.Empty);
     }
 }
 public void GameClassDisplaysBoardAtStartOfGame()
 {
     Board board = new Board(3);
     IPlayer player1 = new ComputerPlayer(BoardCharacter.X);
     IPlayer player2 = new ComputerPlayer(BoardCharacter.Zero);
     Game game = new Game(board, player1, player2, gameSubscriber.Object, 0);
     game.Run();
     gameSubscriber.Verify(g => g.GameBegin(It.Is<string>(s => IsEmptyBoard(s))), Times.Once());
 }
 public formMain()
 {
     InitializeComponent();
     gameBoard = new Board();
     
     engine = new gfxSettings(panelBoard);
     gameBoard.initBoard(engine, panelBoard, labelScore);
     gameBoard.resetScore();
 }
Beispiel #24
0
        public Cleaner(Board board)
            : base(board.Game)
        {
            _board = board;
            _waypoints = CalculatePath();
            _path = new Queue<Vector2>(_waypoints);

            _pos = _waypoints.Peek();
            _speed = 10;
        }
Beispiel #25
0
        public static Board Get3DimensionBoardWithFiveFreePositions()
        {
            Board board = new Board(3);
            board.SetPosition(0, 1, BoardCharacter.X);
            board.SetPosition(0, 2, BoardCharacter.Zero);
            board.SetPosition(1, 1, BoardCharacter.X);
            board.SetPosition(1, 2, BoardCharacter.Zero);

            return board;
        }
Beispiel #26
0
        /// <summary>
        /// Copies given Board into current Board
        /// </summary>
        /// <param name="board">Board of values</param>
        /// Initializes a 2D-Array of Board and assigns states corresponding to given Board
        public Board(Board board)
        {
            // initialize 2D-Array
            States = new State[Globals.ROWS, Globals.COLS];

            // initialize states of the Board with states of given Board
            for (int i = 0; i < Globals.ROWS; ++i)
                for (int j = 0; j < Globals.COLS; ++j)
                    States[i, j] = board[i, j];
        }
		// gets a random move.  this can be used to make game play interesting
		// particularly in the beginning of the game or if you wish to weaken the computer's
		// play by adding randomness.
		protected TicTacToeMove GetRandomMove(Board b)
		{
			int openPositions = b.OpenPositions.Length;
			Random rGen = new Random();

			int squareToMoveTo = rGen.Next(openPositions);

			TicTacToeMove move = new TicTacToeMove(squareToMoveTo, this.PlayerPiece);
			return move;
		}
        public void GivenExistingBoard_ReturnsFive()
        {
            // Arrange
            Board board = new TicTacToe.Board(new char[][] {
                new char[] { 'X', '.', 'O' },
                new char[] { 'X', 'O', '.' },
                new char[] { 'X', '.', '.' }
            });

            // Assert
            Assert.Equal(5, board.counter);
        }
Beispiel #29
0
        public void SettingPositionWillAllowGettingTheSamePosition()
        {
            Board board = new Board(4);
            board.SetPosition(2, 3, BoardCharacter.X);
            Assert.AreEqual(board.GetPosition(2, 3), BoardCharacter.X);

            board.SetPosition(2, 3, BoardCharacter.Zero);
            Assert.AreEqual(board.GetPosition(2, 3), BoardCharacter.Zero);

            board.SetPosition(2, 3, BoardCharacter.Empty);
            Assert.AreEqual(board.GetPosition(2, 3), BoardCharacter.Empty);
        }
Beispiel #30
0
 public void SetUp()
 {
     topLeft = new Cell();
     topMiddle = new Cell();
     topRight = new Cell();
     middleLeft = new Cell();
     middleMiddle = new Cell();
     middleRight = new Cell();
     bottomLeft = new Cell();
     bottomMiddle = new Cell();
     bottomRight = new Cell();
     var cells = new List<Cell>{topLeft, topMiddle, topRight, middleLeft, middleMiddle, middleRight, bottomLeft, bottomMiddle, bottomRight};
     board = new Board(cells);
 }
Beispiel #31
0
 public Game(int playersCount, int boardSize, OutputType outputType)
 {
     writer = new Output(outputType);
     if(outputType == OutputType.File)
     {
         FileWriter.ClearFile();
     }
     players = new List<Player>();
     for (int i = 0; i < playersCount; i++)
     {
         players.Add(new Player(players, outputType));
     }
     board = new Board(boardSize);
     Toss();
 }
        public void GivenExistingBoard_WhereGameIsWon_ReturnsTrue()
        {
            // Arrange
            Board board = new TicTacToe.Board(new char[][]
            {
                new char[] { 'X', '.', 'O' },
                new char[] { 'X', 'O', '.' },
                new char[] { 'X', '.', '.' }
            });

            // Act
            var result = board.CheckBoardStatus('X');

            // Assert
            Assert.True(result);
        }
Beispiel #33
0
        public void Test_Is_Playing()
        {
            var       gameBoard = new TicTacToe.Board();
            GameState state;

            state = gameBoard.Play(new Space {
                Marker = Marker.X, Number = 0
            });
            state = gameBoard.Play(new Space {
                Marker = Marker.O, Number = 3
            });
            state = gameBoard.Play(new Space {
                Marker = Marker.X, Number = 1
            });

            Assert.IsTrue(state == GameState.Playing);
        }
        public void GivenANewPieceToPlace_WhereSpaceIsEmpty_ReturnsTrue()
        {
            // Arrange
            Board board = new TicTacToe.Board(new char[][]
            {
                new char[] { 'X', '.', 'O' },
                new char[] { 'X', 'O', '.' },
                new char[] { '.', '.', '.' }
            });
            Player playerOne = new TicTacToe.Player('X');

            // Act
            var result = board.PlaceAPiece(2, 0, playerOne);

            // Assert
            Assert.True(result);
        }
Beispiel #35
0
        public void Test_InvalidMove()
        {
            var       gameBoard = new TicTacToe.Board();
            GameState state;

            //Play the first X on 4
            state = gameBoard.Play(new Space {
                Marker = Marker.X, Number = 4
            });

            //Try and play space 4 again
            state = gameBoard.Play(new Space {
                Marker = Marker.X, Number = 4
            });

            Assert.IsTrue(state == GameState.InvalidMove);
        }
        private static Board CreateNewBoard(string boardName, string playerNamer)
        {
            var player = new Player();
            player.Name = playerNamer;
            player.WaitingForOpponent = false;
            player.Simbolo = "X";

            var board = new Board();
            board.Name = boardName;
            board.Player1 = player;
            board.GameStarted = DateTime.Now;
            board.LastPlaySuccess = false;

            boards.Add(board);

            return board;
        }
Beispiel #37
0
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            background = new Background();
            board = new Board();
            playerX = new SmartPlayer(board);
            playerO = new SmartPlayer(board);
            newGameTile = new NewGameTile();

            GameState.Initialize();
            GameState._whosTurn = PlayerTurn.O; // should make this random
            GameState._gameOver = false;

            IsMouseVisible = true;

            gameType = new MessageDialog("One player or two player?");

            base.Initialize();
        }
Beispiel #38
0
        public void Test_PlaceDiagonalTwo_Winning()
        {
            var       gameBoard = new TicTacToe.Board();
            GameState state;

            state = gameBoard.Play(new Space {
                Marker = Marker.X, Number = 2
            });
            state = gameBoard.Play(new Space {
                Marker = Marker.O, Number = 3
            });
            state = gameBoard.Play(new Space {
                Marker = Marker.X, Number = 4
            });
            state = gameBoard.Play(new Space {
                Marker = Marker.O, Number = 7
            });
            state = gameBoard.Play(new Space {
                Marker = Marker.X, Number = 6
            });

            Assert.IsTrue(state == GameState.Winner);
        }
Beispiel #39
0
        public void Test_PlaceSecondRow_Winning()
        {
            var       gameBoard = new TicTacToe.Board();
            GameState state;

            state = gameBoard.Play(new Space {
                Marker = Marker.X, Number = 3
            });
            state = gameBoard.Play(new Space {
                Marker = Marker.O, Number = 0
            });
            state = gameBoard.Play(new Space {
                Marker = Marker.X, Number = 4
            });
            state = gameBoard.Play(new Space {
                Marker = Marker.O, Number = 1
            });
            state = gameBoard.Play(new Space {
                Marker = Marker.X, Number = 5
            });

            Assert.IsTrue(state == GameState.Winner);
        }