コード例 #1
0
ファイル: Reversi.cs プロジェクト: erbenmo/Reversi
 public Reversi()
 {
     cur_board = new List<List<Board.PIECE>>();
     cur_empty_neighbor_list = new List<int>();
     b = new Board(cur_board, cur_empty_neighbor_list);
     ai = new AI(b, cur_board, cur_empty_neighbor_list);
 }
コード例 #2
0
ファイル: ReversiForm.cs プロジェクト: mrexodia/reversi
        private Bitmap drawBoard(Board b)
        {
            Bitmap bitmap = new Bitmap(panelBoard.Width, panelBoard.Height);
            Graphics g = Graphics.FromImage(bitmap);
            int drawWidth = (panelBoard.Width - 1) / b.width;
            int drawHeight = (panelBoard.Height - 1) / b.height;
            const int pad = 3;

            for (int boardX = 0; boardX < b.width; boardX++)
            {
                for (int boardY = 0; boardY < b.height; boardY++)
                {
                    int drawX = boardX * drawWidth;
                    int drawY = boardY * drawHeight;

                    //draw grid
                    g.DrawRectangle(Pens.Black, drawX, drawY, drawWidth, drawHeight);

                    //draw player
                    if (!b.fields[boardX, boardY].IsEmpty())
                        g.DrawImage(b.fields[boardX, boardY].owner.image, drawX, drawY, drawWidth, drawHeight);

                    if (checkBoxHelp.Checked)
                    {
                        //draw help
                        if (b.IsValidMove(b.curPlayer, boardX, boardY))
                            g.DrawEllipse(new Pen(b.curPlayer.color), drawX + drawWidth / 4 + pad + 1, drawY + drawHeight / 4 + pad + 1, drawWidth / 2 - pad * 2,
                                drawHeight / 2 - pad * 2);
                    }
                }
            }

            return bitmap;
        }
コード例 #3
0
ファイル: NewGameForm.cs プロジェクト: mrexodia/reversi
        public NewGameForm(Board oldboard)
        {
            InitializeComponent();

            textWidth.Text = oldboard.width.ToString();
            textHeight.Text = oldboard.height.ToString();
            textName1.Text = oldboard.player1.name;
            groupBoxPlayer1.ForeColor = oldboard.player1.color;
            textName2.Text = oldboard.player2.name;
            groupBoxPlayer2.ForeColor = oldboard.player2.color;
        }
コード例 #4
0
ファイル: NewGameForm.cs プロジェクト: mrexodia/reversi
 private void buttonStart_Click(object sender, EventArgs e)
 {
     try
     {
         board = new Board(int.Parse(textWidth.Text), int.Parse(textHeight.Text),
                             new Player(textName1.Text, Color.Blue, Properties.Resources.ImageEllipseBlue),
                             new Player(textName2.Text, Color.Red, Properties.Resources.ImageEllipseRed));
         Close();
     }
     catch (Exception)
     {
         MessageBox.Show("Invalid input, make sure you specify a number in the size field.");
     }
 }
コード例 #5
0
ファイル: ReversiForm.cs プロジェクト: mrexodia/reversi
        public ReversiForm()
        {
            InitializeComponent();

            //start new game
            board = new Board(6, 6, new Player("Sonic", Color.Blue, Properties.Resources.ImageEllipseBlue),
                new Player("Mario", Color.Red, Properties.Resources.ImageEllipseRed));
            newGame();

            //register events
            panelBoard.Paint += pictureBoxBoard_Paint;
            panelBoard.MouseClick += panelBoard_MouseClick;
            panelBoard.MouseDown += panelBoard_MouseDown;
            panelBoard.MouseUp += panelBoard_MouseUp;
        }
コード例 #6
0
ファイル: AI.cs プロジェクト: erbenmo/Reversi
        // Greedy; Choose the Move with Maximum Immediate Gain.
        public int Generic_Greedy_AI(Board.PIECE caller, List<int> legal_cand, Board.WEIGHT weight)
        {
            int max_gain = -10000; int max_gain_idx = -1;

            for (int i = 0; i < legal_cand.Count; i++)
            {
                int h = legal_cand[i] / Board.SIZE, w = legal_cand[i] % Board.SIZE;
                int cur_gain = b.place_piece(cur_board, cur_empty_neighbor_list, h, w, caller, Board.MARK.Don_t_mark, weight);
                if (cur_gain > max_gain)
                {
                    max_gain = cur_gain;
                    max_gain_idx = i;
                }
            }

            return legal_cand[max_gain_idx];
        }
コード例 #7
0
ファイル: Board.cs プロジェクト: ogeraisi/THE-HORROR
        //
        // Creates a new Board object by copying an existing one.
        //
        public Board(Board board)
        {
            // Create the squares and map.
            this.squares = new int[10, 10];
            this.safeDiscs = new bool[10, 10];

            // Copy the given board.
            for (int i = 0; i < 10; ++i)
                for (int j = 0; j < 10; ++j)
                {
                    this.squares[i, j] = board.squares[i, j];
                    this.safeDiscs[i, j] = board.safeDiscs[i, j];
                }

            // Copy the counts.
            this.blackCount = board.blackCount;
            this.whiteCount = board.whiteCount;
            this.emptyCount = board.emptyCount;
            this.blackSafeCount = board.blackSafeCount;
            this.whiteSafeCount = board.whiteSafeCount;
        }
コード例 #8
0
ファイル: Board.cs プロジェクト: Joseph24/AI
        //
        // Creates a new Board object by copying an existing one.
        //
        public Board(Board board)
        {
            // Create the squares and map.
            this.squares = new int[8, 8];
            this.safeDiscs = new bool[8, 8];

            // Copy the given board.
            int i, j;
            for (i = 0; i < 8; i++)
                for (j = 0; j < 8; j++)
                {
                    this.squares[i, j] = board.squares[i, j];
                    this.safeDiscs[i, j] = board.safeDiscs[i, j];
                }

            // Copy the counts.
            this.blackCount = board.blackCount;
            this.whiteCount = board.whiteCount;
            this.emptyCount = board.emptyCount;
            this.blackSafeCount = board.blackSafeCount;
            this.whiteSafeCount = board.whiteSafeCount;
        }
コード例 #9
0
ファイル: Reversi.cs プロジェクト: Joseph24/AI
        public ReversiForm()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //

            // Create the game board.
            this.board = new Board();

            // Create the controls for each square, add them to the squares
            // panel and set up event handling.
            this.squareControls = new SquareControl[8, 8];
            int i, j;
            for (i = 0; i < 8; i++)
                for (j = 0; j < 8; j++)
                {
                    // Create it.
                    this.squareControls[i, j] = new SquareControl(i, j);
                    // Position it.
                    this.squareControls[i, j].Left = j * this.squareControls[i, j].Width;
                    this.squareControls[i, j].Top  = i * this.squareControls[i, j].Height;
                    // Add it.
                    this.squaresPanel.Controls.Add(this.squareControls[i, j]);
                    // Set up event handling for it.
                    this.squareControls[i, j].MouseMove  += new MouseEventHandler(this.SquareControl_MouseMove);
                    this.squareControls[i, j].MouseLeave += new EventHandler(this.SquareControl_MouseLeave);
                    this.squareControls[i, j].Click      += new EventHandler(this.SquareControl_Click);
                }

            // Create the column and row labels.
            this.colLabels = new Label[8];
            for (i = 0; i < 8; i++)
            {
                // Create a column label.
                this.colLabels[i] = new Label();

                // Set its display properties.
                this.colLabels[i].Text = ReversiForm.alpha.Substring(i, 1);
                this.colLabels[i].BackColor = this.cornerLabel.BackColor;
                this.colLabels[i].ForeColor = this.cornerLabel.ForeColor;
                this.colLabels[i].TextAlign = ContentAlignment.MiddleCenter;

                // Set its size and position.
                this.colLabels[i].Width = this.squareControls[0, 0].Width;
                this.colLabels[i].Height = this.cornerLabel.Height;
                this.colLabels[i].Left = this.cornerLabel.Width + i * this.colLabels[0].Width;
                this.colLabels[i].Top = 0;

                // Add it.
                this.boardPanel.Controls.Add(this.colLabels[i]);
            }
            this.rowLabels = new Label[8];
            for (i = 0; i < 8; i++)
            {
                // Create a row label.
                this.rowLabels[i] = new Label();

                // Set its display properties.
                this.rowLabels[i].Text      = (i + 1).ToString();
                this.rowLabels[i].BackColor = this.cornerLabel.BackColor;
                this.rowLabels[i].ForeColor = this.cornerLabel.ForeColor;
                this.rowLabels[i].TextAlign = ContentAlignment.MiddleCenter;

                // Set its size and position.
                this.rowLabels[i].Width  = this.cornerLabel.Height;
                this.rowLabels[i].Height = this.squareControls[0, 0].Height;
                this.rowLabels[i].Left   = 0;
                this.rowLabels[i].Top    = this.cornerLabel.Height + i * this.rowLabels[0].Width;

                // Add it.
                this.boardPanel.Controls.Add(this.rowLabels[i]);
            }

            // Initialize the game state.
            this.gameState = ReversiForm.GameState.GameOver;

            // Initialize the animation timer.
            this.animationTimer.Interval = ReversiForm.animationTimerInterval;
            this.animationTimer.Tick += new EventHandler(this.AnimateMove);

            // Initialize the window settings.
            this.windowSettings = new Rectangle(
                this.DesktopLocation.X,
                this.DesktopLocation.Y,
                this.ClientSize.Width,
                this.ClientSize.Height);

            // Load any saved program settings.
            this.settings = new ProgramSettings(ReversiForm.programSettingsFileName);
            this.LoadProgramSettings();
        }
コード例 #10
0
ファイル: Reversi.cs プロジェクト: ogeraisi/THE-HORROR
 int heuristicFunction2(Board newBoard)
 {
     return newBoard.BlackCount - newBoard.WhiteCount;
 }
コード例 #11
0
ファイル: Reversi.cs プロジェクト: Joseph24/AI
        //
        // Makes a move for the current player.
        //
        private void MakeMove(int row, int col)
        {
            // Clean up the move history to ensure that it contains only the
            // moves made prior to this one.
            while (this.moveHistory.Count > this.moveNumber - 1)
                this.moveHistory.RemoveAt(this.moveHistory.Count - 1);

            // Add the move to the move list.
            string color = "Black";
            if (this.currentColor == Board.White)
                color = "White";
            string[] subItems =
            {
                String.Empty,
                this.moveNumber.ToString(),
                color,
                (alpha[col] + (row + 1).ToString())
            };
            ListViewItem listItem = new ListViewItem(subItems);
            this.moveListView.Items.Add(listItem);

            // If necessary, scroll the list to bring the last move into view.
            this.moveListView.EnsureVisible(this.moveListView.Items.Count - 1);

            // Add this move to the move history.
            this.moveHistory.Add(new MoveRecord(this.board, this.currentColor, listItem));

            // Enable/disable the move-related menu items and tool bar buttons as
            // appropriate.
            this.undoMoveMenuItem.Enabled =
                this.undoAllMovesMenuItem.Enabled =
                this.playToolBar.Buttons[(int) ReversiForm.ToolBarButton.UndoMove].Enabled =
                this.playToolBar.Buttons[(int) ReversiForm.ToolBarButton.UndoAllMoves].Enabled = true;
            this.redoMoveMenuItem.Enabled =
                this.redoAllMovesMenuItem.Enabled =
                this.playToolBar.Buttons[(int) ReversiForm.ToolBarButton.RedoMove].Enabled =
                this.playToolBar.Buttons[(int) ReversiForm.ToolBarButton.RedoAllMoves].Enabled = false;

            // Bump the move number.
            this.moveNumber++;

            // Update the status display.
            this.statusLabel.Text = "";
            this.statusProgressBar.Visible = false;
            this.statusPanel.Refresh();

            // Clear any board square highlighting.
            this.UnHighlightSquares();

            // Make a copy of the board (for doing move animation).
            Board oldBoard = new Board(this.board);

            // Make the move on the board.
            this.board.MakeMove(this.currentColor, row, col);

            // If the animate move option is active, set up animation for the
            // affected discs.
            if (this.options.AnimateMoves)
            {
                int i, j;
                for (i = 0; i < 8; i++)
                    for (j = 0; j < 8; j++)
                    {
                        // Mark the newly added disc.
                        if (i == row && j == col)
                            this.squareControls[i, j].IsNew = true;
                        else
                        {
                            // Initialize animation for the discs that were
                            // flipped.
                            if (this.board.GetSquareContents(i, j) != oldBoard.GetSquareContents(i, j))
                                this.squareControls[i, j].AnimationCounter = SquareControl.AnimationStart;
                        }
                    }
            }

            // Update the display to reflect the board changes.
            this.UpdateBoardDisplay();

            // Save the player color.
            this.lastMoveColor = this.currentColor;

            // If the animate moves option is active, start the animation.
            if (this.options.AnimateMoves)
            {
                this.gameState = ReversiForm.GameState.InMoveAnimation;
                this.animationTimer.Start();
            }

            // Otherwise, end the move.
            else
                this.EndMove();
        }
コード例 #12
0
ファイル: Reversi.cs プロジェクト: ogeraisi/THE-HORROR
        //
        // Makes a move for the current player.
        //
        private void MakeMove(int row, int col)
        {
            // Save the current game state.
            previousGameState = new Board(board);

            // Log the move.
            logMove(row, col);

            // Make the move on the board.
            board.MakeMove(currentColor, row, col);

            // If the animate move option is active,
            // set up animation for the affected discs.
            if (options.AnimateMoves)
                setSquaresForAnimation(row, col);

            // Update the display to reflect the board changes.
            UpdateBoardDisplay();

            // Update parameters.
            lastMoveColor = currentColor;
            moveNumber++;

            // If the animate moves option is active, start the animation.
            // Otherwise, end the move.
            if (options.AnimateMoves)
            {
                gameState = ReversiForm.GameState.InMoveAnimation;
                animationTimer.Start();
            }
            else EndMove();
        }
コード例 #13
0
ファイル: Reversi.cs プロジェクト: ogeraisi/THE-HORROR
        // ===================================================================
        // This code handles initialization.
        // ===================================================================
        // Initialize Board
        private void InitializeBoard()
        {
            // Create the game board.
            this.board = new Board();

            // Create the controls for each square, add them to the squares
            // panel and set up event handling.
            this.squareControls = new SquareControl[10, 10];
            for (int i = 0; i < 10; ++i)
                for (int j = 0; j < 10; ++j)
                {
                    // Create it.
                    this.squareControls[i, j] = new SquareControl(i, j);
                    // Position it.
                    this.squareControls[i, j].Left = j * this.squareControls[i, j].Width;
                    this.squareControls[i, j].Top = i * this.squareControls[i, j].Height;
                    // Add it.
                    this.squaresPanel.Controls.Add(this.squareControls[i, j]);
                    // Set up event handling for it.
                    this.squareControls[i, j].MouseMove += new MouseEventHandler(this.SquareControl_MouseMove);
                    this.squareControls[i, j].MouseLeave += new EventHandler(this.SquareControl_MouseLeave);
                    this.squareControls[i, j].Click += new EventHandler(this.SquareControl_Click);
                }
        }
コード例 #14
0
ファイル: ReversiForm.cs プロジェクト: mrexodia/reversi
        private void panelBoard_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                int w = (panelBoard.Width - 1) / board.width;
                int h = (panelBoard.Height - 1) / board.height;
                Board old = board.Clone();
                switch (board.FieldClicked(e.X / w, e.Y / h))
                {
                    case Board.ClickStatus.ValidMove:
                        oldboard = old;
                        checkBoxHelp.Checked = false; //help is only for the current turn
                        redraw();
                        break;

                    case Board.ClickStatus.GameOver:
                        gameOver = true;
                        oldboard = old;
                        redraw();
                        break;
                }
            }
        }
コード例 #15
0
ファイル: AI.cs プロジェクト: erbenmo/Reversi
 public AI(Board board, List<List<Board.PIECE>> _cur_board, List<int> _cur_empty_neighbor_list)
 {
     b = board;
     cur_board = _cur_board;
     cur_empty_neighbor_list = _cur_empty_neighbor_list;
 }
コード例 #16
0
ファイル: Reversi.cs プロジェクト: ogeraisi/THE-HORROR
        int heuristicFunction1(Board newBoard, int forfeit, int color, int opponentMobility)
        {
            SetAIParameters();

            return
                this.forfeitWeight * forfeit +
                this.frontierWeight * (newBoard.WhiteFrontierCount - newBoard.BlackFrontierCount) +
                this.mobilityWeight * color * (newBoard.GetValidMoveCount(color) - newBoard.GetValidMoveCount(-color)) +
                this.stabilityWeight * (newBoard.WhiteSafeCount - newBoard.BlackSafeCount) +
                this.stonesWeight * (newBoard.WhiteCount - newBoard.BlackCount);
        }
コード例 #17
0
ファイル: AI.cs プロジェクト: erbenmo/Reversi
 public int Simple_Bot_AI(Board.PIECE caller, List<int> legal_cand)
 {
     return Generic_Greedy_AI(caller, legal_cand, Board.WEIGHT.Default);
 }
コード例 #18
0
ファイル: Reversi.cs プロジェクト: Joseph24/AI
 public MoveRecord(Board board, int currentColor, ListViewItem moveListItem)
 {
     this.board        = new Board(board);
     this.currentColor = currentColor;
     this.moveListItem = moveListItem;
 }
コード例 #19
0
ファイル: Reversi.cs プロジェクト: Joseph24/AI
        //
        // This function uses look ahead to evaluate all valid moves for a
        // given player color and returns the best move it can find.
        //
        private ComputerMove GetBestMove(Board board, int color, int depth, int alpha, int beta)
        {
            // Initialize the best move.
            ComputerMove bestMove = new ComputerMove(-1, -1);
            bestMove.rank = -color * ReversiForm.maxRank;

            // Find out how many valid moves we have so we can initialize the
            // mobility score.
            int validMoves = board.GetValidMoveCount(color);

            // Start at a random position on the board. This way, if two or
            // more moves are equally good, we'll take one of them at random.
            Random random = new Random();
            int rowStart = random.Next(8);
            int colStart = random.Next(8);

            // Check all valid moves.
            int i, j;
            for (i = 0; i < 8; i++)
                for (j = 0; j < 8; j++)
                {
                    // Get the row and column.
                    int row = (rowStart + i) % 8;
                    int col = (colStart + j) % 8;

                    if (board.IsValidMove(color, row, col))
                    {
                        // Update the progress bar for each move when on the
                        // first look ahead depth level.
                        if (depth == 1)
                            this.BeginInvoke(new UpdateStatusProgressDelegate(this.UpdateStatusProgress));

                        // Make the move.
                        ComputerMove testMove = new ComputerMove(row, col);
                        Board testBoard = new Board(board);
                        testBoard.MakeMove(color, testMove.row, testMove.col);
                        int score = testBoard.WhiteCount - testBoard.BlackCount;

                        // Check the board.
                        int nextColor = -color;
                        int forfeit = 0;
                        bool isEndGame = false;
                        int opponentValidMoves = testBoard.GetValidMoveCount(nextColor);
                        if (opponentValidMoves == 0)
                        {
                            // The opponent cannot move, count the forfeit.
                            forfeit = color;

                            // Switch back to the original color.
                            nextColor = -nextColor;

                            // If that player cannot make a move either, the
                            // game is over.
                            if (!testBoard.HasAnyValidMove(nextColor))
                                isEndGame = true;
                        }

                        // If we reached the end of the look ahead (end game or
                        // max depth), evaluate the board and set the move
                        // rank.
                        if (isEndGame || depth == this.lookAheadDepth)
                        {
                            // For an end game, max the ranking and add on the
                            // final score.
                            if (isEndGame)
                            {
                                // Negative value for black win.
                                if (score < 0)
                                    testMove.rank = -ReversiForm.maxRank + score;

                                // Positive value for white win.
                                else if (score > 0)
                                    testMove.rank = ReversiForm.maxRank + score;

                                // Zero for a draw.
                                else
                                    testMove.rank = 0;
                            }

                            // It's not an end game so calculate the move rank.
                            else
                                testMove.rank =
                                    this.forfeitWeight   * forfeit +
                                    this.frontierWeight  * (testBoard.BlackFrontierCount - testBoard.WhiteFrontierCount) +
                                    this.mobilityWeight  * color * (validMoves - opponentValidMoves) +
                                    this.stabilityWeight * (testBoard.WhiteSafeCount - testBoard.BlackSafeCount) +
                                                           score;
                        }

                        // Otherwise, perform a look ahead.
                        else
                        {
                            ComputerMove nextMove = this.GetBestMove(testBoard, nextColor, depth + 1, alpha, beta);

                            // Pull up the rank.
                            testMove.rank = nextMove.rank;

                            // Forfeits are cumulative, so if the move did not
                            // result in an end game, add any current forfeit
                            // value to the rank.
                            if (forfeit != 0 && Math.Abs(testMove.rank) < ReversiForm.maxRank)
                                testMove.rank += forfeitWeight * forfeit;

                            // Adjust the alpha and beta values, if necessary.
                            if (color == Board.White && testMove.rank > beta)
                                beta = testMove.rank;
                            if (color == Board.Black && testMove.rank < alpha)
                                alpha = testMove.rank;
                        }

                        // Perform a cutoff if the rank is outside tha alpha-beta range.
                        if (color == Board.White && testMove.rank > alpha)
                        {
                            testMove.rank = alpha;
                            return testMove;
                        }
                        if (color == Board.Black && testMove.rank < beta)
                        {
                            testMove.rank = beta;
                            return testMove;
                        }

                        // If this is the first move tested, assume it is the
                        // best for now.
                        if (bestMove.row < 0)
                            bestMove = testMove;

                        // Otherwise, compare the test move to the current
                        // best move and take the one that is better for this
                        // color.
                        else if (color * testMove.rank > color * bestMove.rank)
                            bestMove = testMove;
                    }
                }

            // Return the best move found.
            return bestMove;
        }
コード例 #20
0
ファイル: Reversi.cs プロジェクト: ogeraisi/THE-HORROR
        //
        // This function uses look ahead to evaluate all valid moves for a
        // given player color and returns the best move it can find.
        //
        private ComputerMove minimax(Board board, int color, int alpha, int beta, int depth = 1)
        {
            // Initialize the best move.
            ComputerMove bestMove = new ComputerMove(-1, -1);
            bestMove.rank = -color * int.MaxValue;

            // Start at a random position on the board. This way, if two or
            // more moves are equally good, we'll take one of them at random.
            Random random = new Random();
            int rowStart = random.Next(10);
            int colStart = random.Next(10);

            // Check every square on the board and try to perform
            // each and every move (up to the given depth)
            // to calculate best move for the current player.
            // We are certain that there are valid moves at this point
            // as we wouldn't be here if there weren't any
            // checks are performed in the StartTurn function.
            for (int i = 0; i < 10; ++i)
                for (int j = 0; j < 10; ++j)
                {
                    // Get the row and column.
                    int row = (rowStart + i) % 10;
                    int col = (colStart + j) % 10;

                    if (board.IsValidMove(color, row, col))
                    {
                        // We found a valid move now we copy the board
                        // and try to make that move on the new board
                        // to evaluate its weight.
                        Board tempBoard = new Board(board);
                        tempBoard.MakeMove(color, row, col);

                        // Holds the current move being tested.
                        ComputerMove moveBeingChecked = new ComputerMove(row, col);

                        // Holds the color ID of a player that has no mobility
                        // Initialized to 0 in case both are mobile.
                        int forfeit = 0;

                        // Holds the color ID of the next player.
                        int nextPlayer = -color;

                        // A flag that indicates whether either of
                        // the players is mobile or if game is over.
                        bool gameOver = false;

                        // Just like in StartTurn, after passing a turn
                        // to the next player due to no mobility for the other
                        // we need to check if the new player is mobile
                        // if not then neither can move and game is over.
                        int opponentMobility = tempBoard.GetValidMoveCount(nextPlayer);
                        if (opponentMobility == 0)
                        {
                            forfeit = nextPlayer;
                            nextPlayer = color;

                            if (!tempBoard.HasAnyValidMove(color))
                                gameOver = true;
                        }

                        if (depth >= lookAheadDepth || gameOver)
                        {
                            // Initialize AI Parameters.
                            if (this.currentColor == Board.White)
                            {
                                moveBeingChecked.rank = heuristicFunction1(tempBoard, forfeit, color, opponentMobility);
                                if (tempBoard.EmptyCount > 0 && Board.isCorner(row, col))
                                    moveBeingChecked.rank += 200;
                            }
                            else moveBeingChecked.rank = heuristicFunction2(tempBoard);
                        }
                        else
                        {
                            ComputerMove nextMove = minimax(tempBoard, nextPlayer, alpha, beta, ++depth);
                            moveBeingChecked.rank = nextMove.rank;

                            // Adjust the alpha and beta values, if necessary.
                            if (color == Board.White && moveBeingChecked.rank > beta)
                                beta = moveBeingChecked.rank;
                            if (color == Board.Black && moveBeingChecked.rank < alpha)
                                alpha = moveBeingChecked.rank;
                        }

                        // If the alpha-beta pruning is enabled
                        // perform a cut off if necessary.
                        if (alphaBeta)
                        {
                            if (color == Board.White && moveBeingChecked.rank > alpha)
                            {
                                moveBeingChecked.rank = alpha;
                                return moveBeingChecked;
                            }
                            if (color == Board.Black && moveBeingChecked.rank < beta)
                            {
                                moveBeingChecked.rank = beta;
                                return moveBeingChecked;
                            }
                        }

                        // If this is the first move tested, assume it is the
                        // best for now. otherwise, compare the test move
                        // to the current best move and take the one that
                        // is better for this color.
                        if (bestMove.row < 0)
                            bestMove = moveBeingChecked;
                        else if (color * moveBeingChecked.rank < color * bestMove.rank)
                            bestMove = moveBeingChecked;
                    }
                }

            // Return the best move found.
            return bestMove;
        }
コード例 #21
0
ファイル: Reversi.cs プロジェクト: erbenmo/Reversi
 void printChoice(int h, int w, Board.PIECE caller)
 {
     if (caller == Board.PIECE.BLACK)
         Console.WriteLine("@");
     else
         Console.WriteLine("-");
     Console.WriteLine(h + " " + w);
     Console.WriteLine();
     Console.WriteLine();
 }
コード例 #22
0
ファイル: ReversiForm.cs プロジェクト: mrexodia/reversi
 private void newGame()
 {
     NewGameForm form = new NewGameForm(board);
     form.ShowDialog(this);
     if (form.board != null)
     {
         board = form.board;
         oldboard = null;
         displayOldBoard = false;
         gameOver = false;
     }
     updateScores(board);
     redraw();
 }
コード例 #23
0
ファイル: Reversi.cs プロジェクト: Joseph24/AI
        // ===================================================================
        // Code to handle undo/redo of moves.
        // ===================================================================
        //
        // Restores the game to the state it was in before the specified move
        // was made.
        //
        private void RestoreGameAt(int n)
        {
            // Get the move record.
            MoveRecord item = (MoveRecord) this.moveHistory[n];

            // Stop any animation.
            this.StopMoveAnimation();

            // Clear any board square highlighting.
            this.UnHighlightSquares();

            // Restore the board and update the display.
            this.board = new Board(item.board);
            this.UpdateBoardDisplay();

            // Restore the current player.
            this.currentColor = item.currentColor;

            // Restore the move list.
            this.moveListView.Items.Clear();
            for (int i = 0; i < n; i++)
            {
                item = (MoveRecord) this.moveHistory[i];
                this.moveListView.Items.Add(item.moveListItem);
            }
            if (this.moveListView.Items.Count > 0)
                this.moveListView.EnsureVisible(this.moveListView.Items.Count - 1);
            else
                this.moveListView.Refresh();

            // Set the current move number.
            this.moveNumber = n + 1;

            // Enable/disable the move-related menu items and tool bar buttons
            // as appropriate.
            this.undoMoveMenuItem.Enabled =
                this.undoAllMovesMenuItem.Enabled =
                this.playToolBar.Buttons[(int) ReversiForm.ToolBarButton.UndoMove].Enabled =
                this.playToolBar.Buttons[(int) ReversiForm.ToolBarButton.UndoAllMoves].Enabled = (this.moveNumber > 1);
            this.redoMoveMenuItem.Enabled =
                this.redoAllMovesMenuItem.Enabled =
                this.playToolBar.Buttons[(int) ReversiForm.ToolBarButton.RedoMove].Enabled =
                this.playToolBar.Buttons[(int) ReversiForm.ToolBarButton.RedoAllMoves].Enabled = (this.moveNumber < this.moveHistory.Count);
            this.resumePlayMenuItem.Enabled =
                this.playToolBar.Buttons[(int) ReversiForm.ToolBarButton.ResumePlay].Enabled   = false;

            // Suspend computer play.
            this.isComputerPlaySuspended = true;
        }
コード例 #24
0
ファイル: AI.cs プロジェクト: erbenmo/Reversi
 public int Static_H_Bot_AI(Board.PIECE caller, List<int> legal_cand)
 {
     return Generic_Greedy_AI(caller, legal_cand, Board.WEIGHT.Static);
 }
コード例 #25
0
ファイル: Reversi.cs プロジェクト: Joseph24/AI
        // ===================================================================
        // Event handlers for the square controls.
        // ===================================================================
        //
        // Handles a mouse move on a board square.
        //
        private void SquareControl_MouseMove(object sender, MouseEventArgs e)
        {
            // Check the game state to ensure that it is the user's turn.
            if (this.gameState != ReversiForm.GameState.InPlayerMove)
                return;

            SquareControl squareControl = (SquareControl) sender;

            // If the square is a valid move for the current player,
            // indicate it.
            if (this.board.IsValidMove(this.currentColor, squareControl.Row, squareControl.Col))
            {
                //
                if (!squareControl.IsActive && squareControl.PreviewContents == Board.Empty)
                {
                    // If the show valid moves option is active, mark the
                    // square.
                    if (this.options.ShowValidMoves)
                    {
                        squareControl.IsActive = true;

                        // If the preview moves option is not active, update
                        // the square display now.
                        if (!this.options.PreviewMoves)
                            squareControl.Refresh();
                    }

                    // If the preview moves option is active, mark the
                    // appropriate squares.
                    if (this.options.PreviewMoves)
                    {
                        // Create a temporary board to make the move on.
                        Board board = new Board(this.board);
                        board.MakeMove(this.currentColor, squareControl.Row, squareControl.Col);

                        // Set up the move preview.
                        for (int i = 0; i < 8; i++)
                            for (int j = 0; j < 8; j++)
                                if (board.GetSquareContents(i, j) != this.board.GetSquareContents(i, j))
                                {
                                    // Set and update the square display.
                                    this.squareControls[i, j].PreviewContents = board.GetSquareContents(i, j);
                                    this.squareControls[i, j].Refresh();
                                }
                    }
                }

                // Change the cursor.
                squareControl.Cursor = System.Windows.Forms.Cursors.Hand;
            }
        }
コード例 #26
0
ファイル: ReversiForm.cs プロジェクト: mrexodia/reversi
        private void updateScores(Board b)
        {
            labelPlayer1.Text = String.Format("{0}: {1}", b.player1.name, b.GetPlayerScore(b.player1));
            labelPlayer1.ForeColor = b.player1.color;
            labelPlayer2.Text = String.Format("{0}: {1}", b.player2.name, b.GetPlayerScore(b.player2));
            labelPlayer2.ForeColor = b.player2.color;

            if (gameOver)
            {
                int score1 = b.GetPlayerScore(b.player1);
                int score2 = b.GetPlayerScore(b.player2);
                if (score1 > score2) //player1 wins
                {
                    labelGameStatus.Text = String.Format("{0} won!", b.player1.name);
                    labelGameStatus.ForeColor = b.player1.color;
                }
                else if (score2 > score1) //player2 wins
                {
                    labelGameStatus.Text = String.Format("{0} won!", b.player2.name);
                    labelGameStatus.ForeColor = b.player2.color;
                }
                else //draw
                {
                    labelGameStatus.Text = "It's a draw...";
                    labelGameStatus.ForeColor = Color.Black;
                }
            }
            else
            {
                labelGameStatus.Text = String.Format("It is {0}'s turn.", b.curPlayer.name);
                labelGameStatus.ForeColor = b.curPlayer.color;
            }
        }
コード例 #27
0
ファイル: Reversi.cs プロジェクト: Joseph24/AI
        // ===================================================================
        // Game AI code.
        // Note: These are executed in the worker thread.
        // ===================================================================
        //
        // This function starts the look ahead process to find the best move
        // for the current player color.
        //
        private ComputerMove GetBestMove(Board board)
        {
            // Initialize the alpha-beta cutoff values.
            int alpha = ReversiForm.maxRank + 64;
            int beta  = -alpha;

            // Kick off the look ahead.
            return this.GetBestMove(board, this.currentColor, 1, alpha, beta);
        }
コード例 #28
0
ファイル: AI.cs プロジェクト: erbenmo/Reversi
        public int Mini_Max_AI(Board.PIECE caller, List<int> legal_cand)
        {
            // black will maximize
            // white will minimize

            if (caller == Board.PIECE.BLACK)
            {
                max_value(copy(cur_board), new List<int>(cur_empty_neighbor_list), -infinity, infinity, SearchDepth);

                return legal_cand[best_option];
            }
            else if (caller == Board.PIECE.WHITE)
            {
                min_value(copy(cur_board), new List<int>(cur_empty_neighbor_list), -infinity, infinity, SearchDepth);

                return legal_cand[best_option];
            }

            return -1;
        }
コード例 #29
0
ファイル: AI.cs プロジェクト: erbenmo/Reversi
 public int Random_AI(Board.PIECE caller, List<int> legal_cand)
 {
     Random r = new Random();
     int random_idx = r.Next(legal_cand.Count);
     return legal_cand[random_idx];
 }
コード例 #30
0
ファイル: Reversi.cs プロジェクト: ogeraisi/THE-HORROR
        // ===================================================================
        // Game AI code.
        // Note: These are executed in the worker thread.
        // ===================================================================
        //
        // This function starts the look ahead process to find the best move
        // for the current player color.
        //
        private ComputerMove GetBestMove(Board board)
        {
            // Initialize alpha-beta parameters in case
            // alpha-beta pruning option is enabled.
            int alpha = int.MaxValue;
            int beta = int.MinValue;

            // Kick off the look ahead.
            return this.minimax(board, currentColor, alpha, beta);
        }