Results 1 to 3 of 3
  1. #1
    timkd127 is offline Member
    Join Date
    Dec 2008
    Posts
    41
    Rep Power
    0

    Default Help with game algorithm

    Im designing a GUI that is supposed to mimic the game connect four, which i have to design an AI for. I have a working build of the board but im having a hard time coming up with a good way to check for a winner without just brute forcing it with loops. Any help greatly appreciated.

    Java Code:
    package connectfour;
    
    import java.awt.*;
    import java.awt.event.*;
    
    /**
     *Tim McColgan
     * 
     */
    public class Board extends Frame {
    
        final int row = 6;
        final int col = 7;
        int player = 1;
        int score = 0;
        final Panel game = new Panel();
        Button[][] buttons = new Button[row][col];
        Button newGame = new Button("RESTART");
        int[][] points = new int[row][col];
    
        Board() {
            super("Connect Four");
    
            addWindowListener(new WindowAdapter() {
    
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
    
            setSize(500, 500);
            setVisible(true);
            setLayout(new BorderLayout());
            game.setLayout(new GridLayout(row, col));
            for (int i = 0; i < row; i++) {
                for (int j = 0; j < col; j++) {
                    buttons[i][j] = new Button();
                    buttons[i][j].setBackground(Color.GRAY);
                    buttons[i][j].addActionListener(new ButtonListener());
                    points[i][j] = 0;
                    game.add(buttons[i][j]);
                }//end j
            }//end i
            add(game, BorderLayout.CENTER);
            newGame.addActionListener(new ButtonListener());
            add(newGame, BorderLayout.NORTH);
        }//end Board()
    
        private class ButtonListener implements ActionListener {
    
            public void actionPerformed(ActionEvent e) {
                boolean restart = false;
                if (e.getSource() == newGame) {
                    newGame();
                    restart = true;
                    player = 1 - player;
                }
                player = 1 - player;
    
                int y = 0;
                int x = 0;
                if (!restart) {
                    while (buttons[x][y] != e.getSource()) {
                        x++;
                        if (y == col) {
                            y = 0;
                        }
                        if (x == row) {
                            x = 0;
                            y++;
                        }//end if
    
                    }//end while
    
                    while (x < row - 1 
                            && buttons[x + 1][y].getBackground() != Color.red 
                            && buttons[x + 1][y].getBackground() != Color.blue
                            && !restart) {
                        
                        if (player == 0) {
                            buttons[x][y].setBackground(Color.BLUE);
                        } else {
                            buttons[x][y].setBackground(Color.RED);
                        }//end elseif
                        try {
                            Thread.sleep(75);//Animate piece drop.
                        } catch (Exception exc) {
                            System.out.println("!");
                        }//end try-catch
                        if (buttons[x][y].getBackground() != null) {
                            buttons[x][y].setBackground(Color.GRAY);
                            x++;
                        }// end if
    
                    }//end while
    
    
                    if (player == 0) {
                        buttons[x][y].setBackground(Color.blue);
                        points[x][y] = -1;
                    } else {
                        buttons[x][y].setBackground(Color.red);
                        points[x][y] = 1;
                    }//end elseif
                    buttons[x][y].setEnabled(false);
                }
                score = gameScore();
                if ((score <= 4 && score >= 1) || (score >= -4 && score <= -1)) {
                    System.out.println("Winz");
                }
            }//end if
        }//end actionPerformed()
    
        public int gameScore() {
            int status = 0;
            for (int i = row - 1; i > 1; i--) {
                for (int j = col - 1; j > 1; j--) {
                    status += points[i][j];
                    System.out.println(i+" "+j + "at point: "+points[i][j]);
                }
                if ((status <= 4 && status >= 1) || (status>= -4 && status <= -1)) {
                    return status;
                }
                status = 0;
            }
     
            return status;
        }
    
        public void newGame() {
            for (int i = 0; i < row; i++) {
                for (int j = 0; j < col; j++) {
                    buttons[i][j].setBackground(Color.GRAY);//reset buttons
                    buttons[i][j].setEnabled(true);         //turn on buttons
                }//end j
                }//end i
            }//end newGame()
        }//end inner class
    //}//end outer class
    The for loop in the gameScore() calculates a win horizontally.

  2. #2
    toadaly is offline Senior Member
    Join Date
    Jan 2009
    Posts
    671
    Rep Power
    6

    Default

    There's nothing wrong with brute force when it makes sense to use it, but if you want an algorithm that finds line segments, consider the Hough transform. Treat the grid as if it were an image.

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,001
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by timkd127 View Post
    Im designing a GUI that is supposed to mimic the game connect four, which i have to design an AI for. I have a working build of the board but im having a hard time coming up with a good way to check for a winner without just brute forcing it with loops. Any help greatly appreciated.
    You can reduce the search space tremendously by applying a bit of reasoning: before the move was made there was no winner so the position of the last move must be part of the winning configuration. Search, starting from that last position in all eight (*) directions and count the number of coins that have the same colour as the current coin that are adjacent; if you find four or more that last move was a winning move and the game ends.

    kind regards,

    Jos

    (*) actually there are seven directions because the current coin has to be the topmost coin so you don't need to search upwards.
    Last edited by JosAH; 02-26-2010 at 05:09 PM.

Similar Threads

  1. Replies: 2
    Last Post: 08-05-2010, 04:49 AM
  2. Help with an Algorithm
    By Manfizy in forum New To Java
    Replies: 22
    Last Post: 07-03-2009, 07:16 AM
  3. O(log n) algorithm help !!!!!!
    By itseeker87 in forum New To Java
    Replies: 8
    Last Post: 09-09-2008, 05:12 PM
  4. Alpha-beta algorithm, game tree
    By ljaf_1985 in forum New To Java
    Replies: 0
    Last Post: 03-28-2008, 04:21 PM
  5. Help with algorithm
    By susan in forum New To Java
    Replies: 1
    Last Post: 07-13-2007, 10:26 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •