Beispiel #1
0
        private Game()
        {
            // register event handlers.
            GameField.Instance.FieldFullEvent += HandleGameFieldFullEvent;

            _players[0] = new HumanPlayer('X');
            _players[1] = new ComputerPlayer('O');
        }
 private static IPlayer CreateComputerPlayer()
 {
     logger.LogMessageAndGoNextLine(Resources.GameMessagesResources.ChooseBotPlayerName);
     var botName = logger.ReadMessage();
     var secretNumber = new SecretNumber(logger);
     var botSecretNumber = secretNumber.GenerateSecretNumber();
     var computerPlayer = new ComputerPlayer(botName, botSecretNumber);
     return computerPlayer;
 }
Beispiel #3
0
        //Each player gets one of these, they "own" it
        public AIWindow(ComputerPlayer p)
        {
            InitializeComponent();

            Player = p;
            PlayerTiles.PlayerName = p.Name;
            this.Title = String.Concat("SharpScrabble - Player: ", p.Name);
            WordInPlay = new Dictionary<Point, Tile>(); //initialize

            RedrawBoard();  //calling this again to show tiles.
        }
Beispiel #4
0
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            graphics.PreferredBackBufferWidth = 800;
            graphics.PreferredBackBufferHeight = 600;

            gameState = GameState.Play;
            whoseTurn = PlayerType.Human;
            computer = new ComputerPlayer();
            turnTracker = false;

            IsMouseVisible = true;
        }
        public static ComputerPlayer InitiateGame()
        {
            Console.WriteLine("Would you like to face Rick(1) or Bob (2)");
            int picker = Validator.GetIntChoice(1, 2);

            if (picker == 0)
            {
                ComputerPlayer comp = new ComputerPlayer("Rick", true);
                return(comp);
            }
            else
            {
                ComputerPlayer comp = new ComputerPlayer("Bob", false);
                return(comp);
            }
        }
Beispiel #6
0
        public void GameStopsForWinTest()
        {
            IPlayer whitePlayer = new ComputerPlayer();
            IPlayer blackPlayer = new ComputerPlayer();
            Board   board       = TestHelper.CreateEmptyBoard();

            board[3][6] = "X";
            board[4][1] = "O";
            board[4][3] = "O";
            board[4][5] = "O";
            board[4][7] = "O";

            GameManager target = new GameManager(whitePlayer, blackPlayer, board);

            Assert.IsTrue(target.Winner == "White");
        }
Beispiel #7
0
        public void GetLastMove_Test2()
        {
            var game = new Game();

            game.MakeMove(Player.Human, 0, 0);
            game.MakeMove(Player.Computer, 2, 0);
            game.MakeMove(Player.Human, 0, 1);
            game.MakeMove(Player.Computer, 1, 1);
            game.MakeMove(Player.Human, 1, 0);

            var computerPlayer = new ComputerPlayer(_winDetector, _scenarioCalculator);

            var(x, y) = computerPlayer.NextMove(game);
            Assert.AreEqual(0, x);
            Assert.AreEqual(2, y);
        }
        public void It_correctly_gets_computer_game_winner()
        {
            // Arrange
            var humanPlayer    = new HumanPlayer("HumanPlayer");
            var computerPlayer = new ComputerPlayer();

            _sut = new Game(humanPlayer, computerPlayer);
            _sut.AddPointToTheWinner(computerPlayer);

            // Act
            var winner = _sut.GetGameWinner();

            // Assert
            winner.Should().NotBeNull();
            winner.Should().BeSameAs(computerPlayer);
        }
Beispiel #9
0
        public static GameUI ComposeStartupForm()
        {
            IBoard       board       = new Board();
            IGameManager gameManager = new GameManager(board);

            IGameService gameService = new GameService(gameManager);

            IComputerPlayer computerPlayer = new ComputerPlayer(gameService);
            IHumanPlayer    humanPlayer    = new HumanPlayer(gameService);

            IController controller = new Controller(computerPlayer, humanPlayer, gameService);

            GameUI form = new GameUI(gameService, controller);

            return(form);
        }
Beispiel #10
0
        private void MenuNew_Click(object sender, EventArgs e)
        {
            this.Text = "";

            HumanPlayer    pl1 = new HumanPlayer(Properties.Settings.Default.SouthName);
            ComputerPlayer pl2 = CreatePlayer(Properties.Settings.Default.NorthDll, Properties.Settings.Default.NorthName);
            ComputerPlayer pl3 = CreatePlayer(Properties.Settings.Default.EastDll, Properties.Settings.Default.EastName);
            ComputerPlayer pl4 = CreatePlayer(Properties.Settings.Default.WestDll, Properties.Settings.Default.WestName);

            if (pl2 == null || pl3 == null || pl4 == null)
            {
                MessageBox.Show("Player not properly configured. See 'Settings->Players' for details.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            pl1.AnnounceMaking += new HumanPlayer.AnnounceMakingHandler(HumanPlayerIsBidding);
            pl2.AnnounceMade   += new ComputerPlayer.AnnounceMadeHandler(CompPlayerBidded);
            pl3.AnnounceMade   += new ComputerPlayer.AnnounceMadeHandler(CompPlayerBidded);
            pl4.AnnounceMade   += new ComputerPlayer.AnnounceMadeHandler(CompPlayerBidded);

            pl1.CardPlaying += new Player.CardPlayingHandler(HumanPlayerIsPlaying);
            pl2.CardPlayed  += new Player.CardPlayedHandler(ComputerPlayerPlayed);
            pl3.CardPlayed  += new Player.CardPlayedHandler(ComputerPlayerPlayed);
            pl4.CardPlayed  += new Player.CardPlayedHandler(ComputerPlayerPlayed);

            pl1.CardsChanged += new Player.PlayerCardsChangedHandler(DrawCards);
            pl2.CardsChanged += new Player.PlayerCardsChangedHandler(DrawCards);
            pl3.CardsChanged += new Player.PlayerCardsChangedHandler(DrawCards);
            pl4.CardsChanged += new Player.PlayerCardsChangedHandler(DrawCards);

            pl1.CardCombinationAnnouncing += new HumanPlayer.CardCombinationAnnouncingHandler(HumanCardCombinationAnnouncing);
            pl2.CardCombinationAnnounced  += new ComputerPlayer.CardCombinationAnnouncedHandler(CombinationAnnounced);
            pl3.CardCombinationAnnounced  += new ComputerPlayer.CardCombinationAnnouncedHandler(CombinationAnnounced);
            pl4.CardCombinationAnnounced  += new ComputerPlayer.CardCombinationAnnouncedHandler(CombinationAnnounced);

            this._game = new BelotGame(pl1, pl3, pl2, pl4);
            this._game.BiddingCompleted += new BelotGame.BiddingCompletedHandler(BiddingCompleted);
            this._game.DealStarted      += new BelotGame.DealEventHandler(DealStarted);
            this._game.DealCompleted    += new BelotGame.DealEventHandler(DealCompleted);
            this._game.HandClosed       += new BelotGame.HandClosedHandler(HandClosed);
            this._game.GameCompleted    += new BelotGame.GameCompletedHandler(GameOver);

            this._game.CapotRemovesDouble    = Properties.Settings.Default.CapotRemovesDouble;
            this._game.ExtraPointsAreDoubled = Properties.Settings.Default.ExtraPointsAreDoubled;

            this._game.StartGame();
        }
        static void Main(string[] args)
        {
            //Initial test
            Deck deck = new Deck();

            deck.Initialize();
            Random randomNumberGenerator = new Random();

            deck.Shuffle(randomNumberGenerator);
            Card card = deck.DrawCard();


            //Game implementation
            Game           game;
            ComputerPlayer computerPlayer;

            if (File.Exists(GAMEFILENAME))
            {
                //Continued game
                Console.WriteLine("Continued Game of 31!");
                game           = Game.DeserializeGame(File.ReadAllText(GAMEFILENAME));
                computerPlayer = (ComputerPlayer)game.Players[0];  //Type casting
            }
            else
            {
                //New game
                Console.WriteLine("Let's play 31!");
                computerPlayer = new ComputerPlayer("Computer");
                game           = new Game(randomNumberGenerator, computerPlayer, new ConsolePlayer("You"));
            }

            bool isGameOver = false;

            while (!isGameOver)
            {
                File.WriteAllText(GAMEFILENAME, game.SerializeGame()); // Save game state

                Console.WriteLine($"{game.CurrentPlayer.Name} turn!");
                isGameOver = game.NextTurn();
                Console.WriteLine($"{computerPlayer.Name} {computerPlayer.LastAction}");
            }

            File.Delete(GAMEFILENAME);
            Console.WriteLine("----------------------------------------------------------------------------");
            Console.WriteLine($"--- GAME OVER, {game.Winner.Name} WON WITH {game.Winner.Hand.ToListString()} ---");
            Console.ReadLine();
        }
        public void DetermineAValidMove()
        {
            var board = new List <string>
            {
                "o", " ", " ",
                " ", " ", " ",
                " ", " ", " "
            };

            var computerPlayer = new ComputerPlayer("x");
            var solver         = new Solver();
            var solve          = solver.Solve(board);

            var result = computerPlayer.Move(board);

            Assert.AreEqual(1, result);
        }
Beispiel #13
0
        public void ReturnTwoToStopUserFromWinning()
        {
            var computer = new ComputerPlayer("X");
            var board    = new Board(3)
            {
                Squares = new[]
                {
                    "", "X", "",
                    "X", "O", "",
                    "O", "", ""
                },
            };

            var computerMove = computer.Solve(board);

            Assert.AreEqual(2, computerMove);
        }
        public void ShouldSelectCenter()
        {
            //Arrange
            CellCollection cellCollection        = new CellCollection();
            ComputerPlayer playerOne             = new ComputerPlayer(new Glyph('@'), new HardComputerSelectMoveAction());
            ComputerPlayer playerTwo             = new ComputerPlayer(new Glyph('&'), new HardComputerSelectMoveAction());
            Board          board                 = new Board(cellCollection, new GameState(cellCollection), new FakePrinter.Builder().Print().Build());
            HardComputerSelectMoveAction subject = new HardComputerSelectMoveAction();

            board.ClaimEndsGame(BoardPosition.TopRight, playerOne);

            //Act
            ICell cell = subject.Act(board, playerTwo, playerOne);

            //Assert
            cell.Value().Should().Be(BoardPosition.MiddleCenter.Value());
        }
Beispiel #15
0
        public void ConstruktorComputerPlayerTest(int i)
        {
            Point a = new Point(0, 0);

            Point[] path = new Point[1];
            Point[] tab1 = new Point[4];
            for (int ii = 0; ii < tab1.Length; ii++)
            {
                tab1[i] = new Point(0, 0);
            }
            Point[] tab2 = tab1;

            Point  start = new Point(10, 10);
            Dice   dice  = new Dice();
            Player p1    = new ComputerPlayer(i, tab1, tab2, start, dice);

            Assert.AreEqual(i, p1.Number);
        }
Beispiel #16
0
 public MemoryGame(Point i_GameSize, string i_FirstName, string i_SecondName, bool i_PvP)
 {
     InitializeComponent();
     Rows = i_GameSize.X;
     Cols = i_GameSize.Y;
     ComputerTurnState   = eComputerTurnState.FirstTileToChoose;
     r_MemoryBoard       = new GameBoard(Rows, Cols);
     r_IsPvP             = i_PvP;
     r_ComputerPlayer    = r_IsPvP ? new ComputerPlayer(Rows, Cols) : null;
     r_Player1NameLength = i_FirstName.Length;
     Player1Name.Text    = string.Format(i_FirstName + ": 0 Pair(s)");
     r_Player2NameLength = i_SecondName.Length;
     Player2Name.Text    = Player2Name.Text = string.Format(i_SecondName + ": 0 Pair(s)");
     SetCurrentPlayerName();
     initializeTiles();
     Size = new Size(new Point(TileButtonMatrix[Rows - 1, Cols - 1].Right + 50, TileButtonMatrix[Rows - 1, Cols - 1].Bottom + 170));
     Controls.Remove(TileButton);
 }
Beispiel #17
0
        public MemoryGame(GameType i_GameType, int i_Rows, int i_Cols, string i_Player1, string i_Player2)
        {
            m_Player1  = new Player(i_Player1);
            m_GameType = i_GameType;

            if (m_GameType.IsAgainstTheComputer() == true)
            {
                m_Computer = new ComputerPlayer(i_Player2, i_Rows, i_Cols);
            }
            else
            {
                m_Player2 = new Player(i_Player2);
            }
            m_GameBoard      = new CardBoard(i_Rows, i_Cols);
            m_Turn           = new GameTurn();
            m_IsGameOver     = false;
            m_NumOfOpenPairs = 0;
        }
Beispiel #18
0
        public void next_action_busted_because_total_is_greater_than_21()
        {
            IPlayer player     = new ComputerPlayer();
            Hand    dealerHand = new Hand();
            Card    card0      = new Card(Suit.Spades, Rank.King);

            dealerHand.AddCard(card0);

            Card card1 = new Card(Suit.Clubs, Rank.King);
            Card card2 = new Card(Suit.Clubs, Rank.Seven);
            Card card3 = new Card(Suit.Clubs, Rank.Five);

            player.GetHand().AddCard(card1);
            player.GetHand().AddCard(card2);
            player.GetHand().AddCard(card3);
            PlayerAction action = player.NextAction(dealerHand);

            Assert.AreEqual(PlayerAction.Busted, action);
        }
        public void ComputerPlayerCreatedSuccessfullyForGoodMap()
        {
            _validPointA = new Mock <IMapPoint>();
            _validPointA.Setup(p => p.X).Returns(0);
            _validPointA.Setup(p => p.Y).Returns(0);
            _validPointB = new Mock <IMapPoint>();
            _validPointB.Setup(p => p.X).Returns(1);
            _validPointB.Setup(p => p.Y).Returns(0);
            _gameMap = new Mock <IGameMap>();
            _gameMap.Setup(m => m.SetupMap(2, 1)).Returns(true);
            _gameMap.Setup(m => m.MaxX).Returns(2);
            _gameMap.Setup(m => m.MaxY).Returns(1);
            _gameMap.Setup(m => m.MapArea).Returns(new IMapPoint[, ] {
                { _validPointA.Object, _validPointB.Object }
            });

            _player = new ComputerPlayer(_gameMap.Object);
            Assert.IsNotNull(_player);
        }
Beispiel #20
0
        private ComputerPlayer CreatePlayer(string assemblyName, string playerName)
        {
            ComputerPlayer player = null;

            Assembly a = Assembly.LoadFrom(assemblyName);

            Type[] types = a.GetExportedTypes();
            foreach (Type t in types)
            {
                if (t.IsSubclassOf(typeof(ComputerPlayer)))
                {
                    object[] o = new object[1];
                    o[0]   = playerName;
                    player = Activator.CreateInstance(t, o) as ComputerPlayer;
                }
            }

            return(player);
        }
Beispiel #21
0
        public void next_action_stay_when_total_is_17_or_more()
        {
            IPlayer player = new ComputerPlayer();
            Dealer  dealer = new Dealer();
            Card    card0  = new Card(Suit.Spades, Rank.King);
            Card    card1  = new Card(Suit.Spades, Rank.Six);

            dealer.AddCardToHand(card0);
            dealer.AddCardToHand(card1);

            Card card2 = new Card(Suit.Clubs, Rank.King);
            Card card3 = new Card(Suit.Clubs, Rank.Seven);

            player.AddCardToHand(card1);
            player.AddCardToHand(card2);
            PlayerAction action = player.NextAction(dealer.GetHand());

            Assert.AreEqual(PlayerAction.Stand, action);
        }
Beispiel #22
0
        static void Main(string[] args)
        {
            Console.WriteLine("Let's play 31!");
            Random         r  = new Random();
            ComputerPlayer cp = new ComputerPlayer("Computer");

            cp.Done += Cp_Done;
            Game G          = new Game(r, cp, new ConsolePlayer("You"));
            bool isGameOver = false;

            while (!isGameOver)
            {
                Console.WriteLine($"{G.Players[G.CurrentTurn].Name} turn!");
                isGameOver = G.NextTurn();
            }
            Console.WriteLine("----------------------------------------------------------------------------");
            Console.WriteLine($"--- GAME OVER, {G.Winner.Name} WON WITH {G.Winner.Hand.ToListString()} ---");
            Console.ReadLine();
        }
Beispiel #23
0
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to Super-Awesome TicTacToe!!");
            Console.WriteLine();
            Console.Write("Any key to start");
            Console.ReadKey();

            // Create these objects and inject them into the game object, such
            // that the game has no idea about where it's drawing to, or what kind of players
            // are playing (Human / Computer etc)
            GenericGameState gameState = new GenericGameState();
            ConsoleGameDrawer drawer = new ConsoleGameDrawer();
            ComputerPlayer player1 = new ComputerPlayer("Jim", SpaceState.X);
            ComputerPlayer player2 = new ComputerPlayer("Susan", SpaceState.O);

            Game3x3 game = new Game3x3(gameState, drawer, player1, player2);

            RunGame(game);
        }
Beispiel #24
0
        public void ShootAtOpponent_ShouldLetTheComputerShootWhenAllBombsAreShot()
        {
            AssertThatGameIsConstructed();

            //Arrange
            var     shootingStrategyMock = new Mock <IShootingStrategy>();
            IPlayer computerPlayer       = new ComputerPlayer(_settings, shootingStrategyMock.Object);

            _player2Builder.WithBombsLoaded(true);
            IPlayer humanPlayer = _player2;

            _game = new Game(_settings, computerPlayer, humanPlayer);
            _game.Start();

            GridCoordinate targetCoordinate = new GridCoordinateBuilder().Build();

            Mock <IPlayer> humanPlayerMock    = _player2Builder.BuildMock();
            ShotResult     expectedShotResult = ShotResult.CreateMissed();

            humanPlayerMock.Setup(p => p.ShootAt(It.IsAny <IPlayer>(), It.IsAny <GridCoordinate>()))
            .Returns(() =>
            {
                _player2Builder.WithBombsLoaded(false);
                return(expectedShotResult);
            });

            //Act
            ShotResult result = _game.ShootAtOpponent(_player2.Id, targetCoordinate);

            humanPlayerMock.Verify(p => p.ShootAt(computerPlayer, targetCoordinate), Times.Once,
                                   "The ShootAt method of the human player is not called correctly.");

            shootingStrategyMock.Verify(s => s.DetermineTargetCoordinate(), Times.AtLeast(1),
                                        "The computer player did not shoot. You must call the ShootAutomatically method of the computer player. " +
                                        "The ShootAutomatically method should in turn call the DetermineTargetCoordinate method of the shooting strategy of the computer. " +
                                        "This test fails because no call to the DetermineTargetCoordinate method is detected.");

            humanPlayerMock.Verify(p => p.ReloadBombs(), Times.Once,
                                   "The ReloadBombs method of the human player should be called after the computer is done with shooting.");

            Assert.That(result, Is.SameAs(expectedShotResult), "The ShotResult returned by the ShootAt method (of the human player) should be returned.");
        }
Beispiel #25
0
 // constructor, makes instance of the computer player and initializes global variables based on arguments
 public Levels(Card[] deckOfCards, Drawable background, Texture2D selector, SpriteFont font, Player player1, List<Texture2D> particles, SoundEffect shuffling, SoundEffect playingcard, SoundEffectInstance shuffinstance, bool isSoundOn, bool powerUpsOn, bool vibrateOn, Difficulty difficulty, PowerUp powerup)
 {
     computer = new ComputerPlayer("Computer", false);
     deck = deckOfCards;
     _background = background;
     _selector = selector;
     _font = font;
     _player1 = player1;
     _particles = particles;
     this.shuffling = shuffling;
     this.playingCard = playingcard;
     shuffleInstance = shuffinstance;
     this.isSoundOn = isSoundOn;
     isPowerUpOn = powerUpsOn;
     isVibrateOn = vibrateOn;
     _level = 1;
     myState = LevelState.Starting;
     myDiff = difficulty;
     freeze = powerup;
 }
        /// <inheritdoc cref="ISessionManager"/>
        public void BuildSession()
        {
            var players = new List <IPlayer>();

            for (uint h = 0; h < _humanPlayerCount; h++)
            {
                var humanPlayer = new HumanPlayer(h + 1);
                humanPlayer.Round += HumanPlayer_Round;
                players.Add(humanPlayer);
            }

            for (uint c = 0; c < _computerPlayerCount; c++)
            {
                var computerPlayer = new ComputerPlayer(_humanPlayerCount + 1 + c);
                computerPlayer.RoundComplete += ComputerPlayer_RoundComplete;
                players.Add(computerPlayer);
            }

            _session = new Session(players.ToArray());
        }
        public void StartGame_Black_Depth1_Breadth5()
        {
            // arrange
            var computer = new ComputerPlayer(TeamColor.Black, 1, 5);
            var board    = new OrdinaryChessBoard();
            var boardVm  = new BoardViewModel(board);

            // act
            var move = computer.NextMove(boardVm);

            // assert
            Assert.NotNull(move);
            Assert.Greater(move.Score, 9);

            var figure = board.RemoveFigure(move.From);

            figure.Move(move.Destination);
            board.SetFigure(figure, move.Destination);

            Assert.AreEqual(move.Score, board.GetScoreForTeam(TeamColor.Black));
        }
Beispiel #28
0
        static void Main(string[] args)
        {
            var validations = new List <IValidation>()
            {
                new WordCountValidation(),
                new ColourValidation()
            };

            var validator      = new InputValidator(validations);
            var consoleService = new ConsoleIoService();

            var inputProcessor = new InputProcessor(consoleService, validator);

            var computerPlayer = new ComputerPlayer();
            var game           = new Game(computerPlayer);

            var messageFormatter = new MessageFormatter();
            var gameEngine       = new GameEngine(inputProcessor, consoleService, messageFormatter);

            gameEngine.Mastermind(game); // method should be a verb!
        }
Beispiel #29
0
        private void ComputerDiscardCardFromHand()
        {
            if (humanDiscard)
            {
                ComputerPlayer.Move move    = ComputerPlayer.ComputerMove(ComputerCards).Item1;
                Cards.Card          discard = ComputerPlayer.ComputerMove(ComputerCards).Item2.Value;
                Discards.Add(discard);
                ComputerCards.Remove(discard);
                humanDiscard = false;
                playerTurn   = true;

                if (move == ComputerPlayer.Move.Gin)
                {
                    endGame();
                }
                else if (move == ComputerPlayer.Move.Knock)
                {
                    endGame();
                }
            }
        }
        public void ComputerPlayerTooBigShipThrowsException()
        {
            _validPointA = new Mock <IMapPoint>();
            _validPointA.Setup(p => p.X).Returns(0);
            _validPointA.Setup(p => p.Y).Returns(0);
            _validPointB = new Mock <IMapPoint>();
            _validPointB.Setup(p => p.X).Returns(1);
            _validPointB.Setup(p => p.Y).Returns(0);
            _gameMap = new Mock <IGameMap>();
            _gameMap.Setup(m => m.SetupMap(2, 1)).Returns(true);
            _gameMap.Setup(m => m.MaxX).Returns(2);
            _gameMap.Setup(m => m.MaxY).Returns(1);
            _gameMap.Setup(m => m.MapArea).Returns(new IMapPoint[, ] {
                { _validPointA.Object, _validPointB.Object }
            });

            _player = new ComputerPlayer(_gameMap.Object);
            Assert.IsNotNull(_player);

            Assert.ThrowsException <ShipException>(() => _player.PlaceShips(2, 1));
        }
Beispiel #31
0
        public void next_action_stand_because_score_greater_or_equal_than_probable_dealers_score()
        {
            IPlayer player      = new ComputerPlayer();
            Hand    dealerHand  = new Hand();
            Card    dealerCard1 = new Card(Suit.Spades, Rank.Eight);

            dealerCard1.Visible = false;
            Card dealerCard2 = new Card(Suit.Hearts, Rank.Seven);

            dealerHand.AddCard(dealerCard1);
            dealerHand.AddCard(dealerCard2);

            Card playerCard1 = new Card(Suit.Clubs, Rank.King);
            Card playerCard2 = new Card(Suit.Diamonds, Rank.Eight);

            player.GetHand().AddCard(playerCard1);
            player.GetHand().AddCard(playerCard2);
            PlayerAction action = player.NextAction(dealerHand);

            Assert.AreEqual(PlayerAction.Stand, action);
        }
Beispiel #32
0
        public void DoMoveTestForJumpUpdateDownRight()
        {
            IPlayer whitePlayer = new ComputerPlayer();
            IPlayer blackPlayer = new ComputerPlayer();
            Board   gameBoard   = TestHelper.CreateEmptyBoard();

            gameBoard[2][1] = "O";
            gameBoard[3][2] = "X";
            Game target = new Game(whitePlayer, blackPlayer, gameBoard);
            Move move   = new Move()
            {
                From = new Tuple <int, int>(2, 1), To = new Tuple <int, int>(4, 3), IsJump = true
            };

            target.DoMove(move);

            //Validate that the board is correctly updated after a jump
            Assert.IsTrue(target.GameBoard[3][2] == ".");
            Assert.IsTrue(target.GameBoard[2][1] == ".");
            Assert.IsTrue(target.GameBoard[4][3] == "O");
        }
        public void StartHumanGame(bool compiBegin)
        {
            if (m_serverGame)
            {
                StopServerGame();
            }

            // set player's name
            m_view.SetComputerName("Computer");
            m_view.SetHumanName("Player");

            // start computer player
            m_compi = new ComputerPlayer(this);

            SetStarter(compiBegin);

            if (compiBegin)
            {
                m_compi.Play();
            }
        }
Beispiel #34
0
        /// <summary>
        /// Handles all <see cref="Control"/> events related to changing algorithm options.
        /// </summary>
        /// <param name="sender">
        /// The <see cref="CheckBox"/> control sending the event.</param>
        /// <param name="args">
        /// An <see cref="EventArgs"/> object containing event data.</param>
        /// <remarks>
        /// <b>OnOptionsChanged</b> adjusts the algorithm options used by the selected <see
        /// cref="ComputerPlayer"/> to reflect the current contents of the "Selected Computer
        /// Player" <see cref="GroupBox"/>, and sets the <see cref="DataChanged"/> flag if any
        /// changes were made.</remarks>

        private void OnOptionsChanged(object sender, EventArgs args)
        {
            if (this._ignoreEvents)
            {
                return;
            }

            // retrieve selected computer player, if any
            ComputerPlayer computer = SelectedComputerPlayer;

            if (computer == null)
            {
                return;
            }

            // retrieve selected algorithm options
            int  targetLimit    = (int)TargetLimitUpDown.Value;
            bool useRandomBuild = (RandomBuildToggle.IsChecked == true);
            bool useRandomPlace = (RandomPlaceToggle.IsChecked == true);
            bool useScripting   = (ScriptingToggle.IsChecked == true);

            // check selected options against current values
            bool anyChanges =
                (computer.Options.TargetLimit != targetLimit) ||
                (computer.Options.UseRandomBuild != useRandomBuild) ||
                (computer.Options.UseRandomPlace != useRandomPlace) ||
                (computer.Options.UseScripting != useScripting);

            // update current values with selected options
            computer.Options.TargetLimit    = targetLimit;
            computer.Options.UseRandomBuild = useRandomBuild;
            computer.Options.UseRandomPlace = useRandomPlace;
            computer.Options.UseScripting   = useScripting;

            // broadcast data changes, if any
            if (anyChanges)
            {
                UpdatePlayers();
            }
        }
Beispiel #35
0
    public async Task OpponentNoMoves()
    {
        var initial = new InitialHiveBuilder();

        initial += " ⬡ ⬡ ⬡ ⬡ ⬡ ⬡ ⬡ ⬡";
        initial += "⬡ ⬡ ⬡ ⬡ ⬡ ⬡ ⬡ ⬡ ";
        initial += " ⬡ ⬡ A q A ⬡ ⬡ ⬡";
        initial += "⬡ ⬡ ⬡ ⬡ ⬡ ⬡ ⬡ ⬡ ";
        initial += "⬡ ⬡ ⬡ ⬡ ⬡ ⬡ ⬡ ⬡ ";

        var expected = new ExpectedAiBuilder();

        expected += " ⬡ ⬡ ⬡ ⬡ ⬡ ⬡ ⬡ ⬡";
        expected += "⬡ ⬡ ✔ ⬡ ⬡ ✔ ⬡ ⬡ ";
        expected += " ⬡ ✔ A q A ✔ ⬡ ⬡";
        expected += "⬡ ⬡ ✔ ⬡ ⬡ ✔ ⬡ ⬡ ";
        expected += "⬡ ⬡ ⬡ ⬡ ⬡ ⬡ ⬡ ⬡ ";

        var tile = new Tile(50, 0, Creatures.Ant);

        var player1 = new Player(0, "P1") with {
            Tiles = new HashSet <Tile> {
                tile
            }
        };
        var hive = HiveFactory.CreateInProgress(new[] { player1, new Player(1, "P1") }, initial.AllCells, 0);

        foreach (var tileMove in hive.Players.First().Tiles)
        {
            foreach (var coords in tileMove.Moves)
            {
                initial.AddPlayerTrayOriginMove(coords);
                expected.PlayerTrayMoves.Add((coords, tileMove));
            }
        }

        var player = new ComputerPlayer(hive);

        (await player.GetMove()).Should().MatchHive(initial, expected);
    }
Beispiel #36
0
        /// <summary>
        /// Creates a new <see cref="FactionListItem"/> for the specified <see cref="Faction"/>.
        /// </summary>
        /// <param name="faction">
        /// The <see cref="Faction"/> to process.</param>
        /// <returns>
        /// A new <see cref="FactionListItem"/> containing the specified <paramref name="faction"/>,
        /// its controlling <see cref="Player"/>, and details on the latter.</returns>
        /// <remarks>
        /// <b>CreateFactionRow</b> shows the e-mail address or computer player algorithm of the
        /// <see cref="Player"/> that controls the specified <paramref name="faction"/>, or an empty
        /// string if no details are available.</remarks>

        private static FactionListItem CreateFactionRow(Faction faction)
        {
            // retrieve controlling player
            Player         player   = PlayerManager.Instance.GetPlayer(faction);
            HumanPlayer    human    = player as HumanPlayer;
            ComputerPlayer computer = player as ComputerPlayer;

            string details = "";

            if (human != null)
            {
                // show e-mail or "Hotseat" for human players
                details = StringUtility.Validate(human.Email, Global.Strings.LabelLocalHotseat);
            }
            else if (computer != null)
            {
                // show algorithm for computer players
                details = computer.Options.Algorithm.Name;
            }

            return(new FactionListItem(faction, player, details));
        }
Beispiel #37
0
        public static IPlayer createPlayerOfType(ePlayerType i_PlayerType)
        {
            IPlayer player = null;
            switch (i_PlayerType)
            {
                case ePlayerType.Human:
                    player = new HumanPlayer();
                    break;
                case ePlayerType.DumbComputer:
                    player = new ComputerPlayer();
                    break;
                case ePlayerType.OkComputer:
                    player = createSmartPlayerWithSearchDepthOf(0);
                    break;
                case ePlayerType.SmartComputer:
                    player = createSmartPlayerWithSearchDepthOf(2);
                    break;
                case ePlayerType.GeniusComputer:
                    player = createSmartPlayerWithSearchDepthOf(4);
                    break;
            }

            return player;
        }
Beispiel #38
0
    static int Main(string[] args)
    {
        Program p = new Program();
        char gameOn = 'y';//keeps track if game is ongoing
        int input;//variable to keep track of players choice of boardsize

        while (gameOn == 'y')
        {
            // get the size of the board that the user wants
            Console.Write("\nWelcome to Tic-Tac-Toe!\n\n");
            Console.Write("1. 3x3 (Standard)\n");
            Console.Write("2. 5x5\n");
            Console.Write("\nWhat size do you want on the board? (3 or 5): ");

            input = Convert.ToInt32(Console.ReadLine());

            // set the board size, based on the user's input
            if (input == 3 || input == 5)
            {
                p.boardWidth = input;
                p.boardSize = p.boardWidth * p.boardWidth;
            }
            else
            {
                Console.WriteLine("\nYou entered an invalid size!Try again! \n\n");
                continue;

            }

            // Array for the board
            char[] board = new char[p.boardSize];

            // Set all of the board items to empty
            for (int i = 0; i < p.boardSize; i++)
                board[i] = empty;

            bool win = false;
            int size = p.boardSize;//Varibles for the boardssize to pass as parameters in methodcallings
            int width = p.boardWidth;//pass as parameters in methodcallings

            Console.WriteLine("\nChoose opponent\n");
            Console.WriteLine("1. Human opponent");
            Console.WriteLine("2. Computer ");
            int chosenOpponent = int.Parse(Console.ReadLine());//Player input if they want to play
                                                                //against another human or the computerplayer

            // Draw the board
            Console.WriteLine();
            Console.Write(@"The board looks like this and you choose your position by entering the number
            representing the position you want:");
            Player play = new Player(size,width);
            Board b = new Board(size, width);
            ComputerPlayer cp = new ComputerPlayer(size,width);
            // reset moveCount
            play.moveCount = 0;
            b.DrawBoard(board, true);
            Console.WriteLine("\n\n");

            while (win == false)//While there is no winner
            {
                // Ask player1 for a move
                play.AskForMove(board,player1);

                // Draw the board
                b.DrawBoard(board, false);

                // Check to see if player 1 has won
                win = false;
                win = play.IsWinner(board, player1, size);
                if (win == true)
                {
                    Console.WriteLine("\n\nPlayer X has won!\n\n");
                    break;
                }

                // Check for a draw
                if (play.IsDraw())
                {
                    Console.WriteLine("\n\nIt's a draw!\n\n");
                    break;
                }

                // Ask player2 for a move
                if (chosenOpponent == 2 && input == 3)//If player wanted computer opponent and a 3x3board
                    cp.AskForComputerMoveThree(board,player2);

                else if (chosenOpponent == 2 && input == 5)//If player wanted computer opponent and a 5x5 board
                    cp.AskForComputerMoveFive(board, player2);

                else
                    play.AskForMove(board, player2);//If player wanted human opponent

                // Draw board again
                b.DrawBoard(board, false);

                // Check to see if player 2 has won
                win = false;
                win = play.IsWinner(board, player2, size);
                if (win == true)
                {
                    Console.Write("\n\nPlayer O has won!\n\n");
                    break;
                }

                // Check for a draw again
                if (play.IsDraw())
                {
                    Console.Write("\n\nIt's a draw!\n\n");
                    break;
                }
            }

            // Ask if player want to play again
            Console.WriteLine("\n\nWould you like to play again? (y/n): ");
            gameOn = Convert.ToChar(Console.ReadLine());

            //If the player don´t want to play again exit the application else start new game
            if (gameOn == 'n')
                Environment.Exit(0);

            else
                continue;
            Console.ReadKey();
        }

        return 0;
    }
Beispiel #39
0
        public GameController(bool b, Position pos, bool blackIsAI, bool whiteIsAI)
        {
            this.board = new Board(b, pos, this, !blackIsAI);
            board.setup();
            this.position = pos;
            this.movegen = new MoveGenerator();
            this.Subscribe(this);

            this.blackIsAI = blackIsAI;
            this.whiteIsAI = whiteIsAI;

            TurnGenerator = SetupTurnGenerator();

            if (blackIsAI & whiteIsAI)
            {
                bw = new BackgroundWorker();
                bwSetup();
            }else{
                AI = new ComputerPlayer(engine.engineProcess.StandardOutput, engine.engineProcess.StandardInput);
                ResetEngineDifficulty();
            }
        }
Beispiel #40
0
 /**
  * Gets the best move playable by an AI player.
  */
 private String GetAIMove(ComputerPlayer AIPlayer)
 {
     AIPlayer.UpdatePosition(previousMoves);
     AIPlayer.StartSearch();
     String bestMove = AIPlayer.GetBestMove();
     return bestMove;
 }
Beispiel #41
0
 /**
  * Get a Turn Generator using the ComputerPlayer class
  */
 private ComputerPlayer SetupTurnGenerator()
 {
     ComputerPlayer turnGen = new ComputerPlayer(engine.engineProcess.StandardOutput, engine.engineProcess.StandardInput);
     turnGen.setMoveDepth(5);
     return turnGen;
 }