Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: Connect 4 program

  1. #1
    Junior Member
    Join Date
    Apr 2012
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Connect 4 program

    Got an end of term assignment I can't figure out. I've attached the files required for the assignment, the teach wrote almost all of it but I'm required to make a "board.java" class. No clue where to start, I'm supposed to use 2D Arrays to solve this but I'm not terribly familiar with the concept. I'll paste the main parts of the program.
    Attached Files Attached Files
    Last edited by robbeh; April 29th, 2012 at 11:16 PM.


  2. #2
    Junior Member
    Join Date
    Apr 2012
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Connect 4 program

    I'm not supposed to change anything but the Board class, which simply implements the Connect4Board interface. The Board.java class shouldnt do any drawing, just represent the board itself

    This is the central class:

    package extracredit02;
     
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
     
    /**
     * A computer game version of 'Connect 4'.
     * 
     * Undocumented code - beware!  This code is not the best example of
     * programming I have done, I am rushing too much.
     * 
     * @author 
     */
    public class Connect4 extends JPanel implements ActionListener, MouseListener, MouseMotionListener
    {
        Connect4AI[] players = new Connect4AI[] {null, new NaiveAI(), new StubbornAI(), new SmartAI()};
        String[] playerNames = new String[] {"Human", players[1].getName(), players[2].getName(), players[3].getName()};
     
        int[] playerAI = new int[2];  // Red player is player 0
        int[] playerColor   = new int[] {Connect4Board.RED, Connect4Board.BLACK};
        String[] colorName  = new String[] {"red", "", "black"};
     
        JLabel message = new JLabel();
     
        boolean gameInProgress = false;
     
        Connect4Board board = new Board();
     
        JMenuItem menuItem;
     
        int proposedColumn = -1;
        int proposedRow = -1;
        int playerTurn = 0;
     
        JFrame frame;
     
        int[][] drawState = new int[8][8];
     
        /**
         * The application entry point.
         * 
         * @param args Unused.
         */    
        static public void main (String[] args)
        {
            Connect4 game = new Connect4();        
     
            game.frame = new JFrame ("CP SC 2010 - Connect 4");
            game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            game.frame.setBounds(100, 100, 800, 850);
     
            Container contents = game.frame.getContentPane();
            contents.setLayout(new BorderLayout());
     
            Container main = new JPanel();
            main.setLayout(new BorderLayout());
     
            game.message = new JLabel ("Welcome.  Please use the menu to start the game.");
            game.message.setFont(new Font("Arial", Font.BOLD, 20));
            main.add(game.message, BorderLayout.SOUTH);
            main.add(game, BorderLayout.CENTER);
     
            JMenuBar menuBar = new JMenuBar();
     
            JMenu gameMenu = new JMenu("Game");
            game.menuItem = new JMenuItem("Start game");
            gameMenu.add(game.menuItem);
            game.menuItem.addActionListener(game);
            game.addMouseListener(game);
            game.addMouseMotionListener(game);
            menuBar.add(gameMenu);
     
            contents.add(main, BorderLayout.CENTER);
            game.frame.setJMenuBar(menuBar);
            game.frame.setVisible(true);
        }
     
        synchronized public void actionPerformed (ActionEvent e)
        {
            if (gameInProgress)
            {
                gameInProgress = false;
                menuItem.setText("Start game");
                message.setText("Game aborted.  Please use the menu to start the game.");
                message.repaint();            
            }
            else
            {
                message.setText ("Select players.");
                message.repaint();
                try
                {
                    promptForPlayers();
                }
                catch (Exception ex)
                {
                    message.setText("Please use the menu to start the game.");
                    message.repaint();
                    return;
                }
                gameInProgress = true;
                board.clear();
                drawState = new int[8][8];
                menuItem.setText("Stop game");
                playerTurn = 1;
                advancePlayer();
            }
        }
     
        synchronized private void advancePlayer()
        {
            for (int row = 0; row < 8; row++)
                for (int column = 0; column < 8; column++)
                    drawState[row][column] = board.getSpaceContents(row, column);
     
            proposedColumn = -1;
            proposedRow = -1;
     
            if (board.getWinner() != 0)
            {
                gameInProgress = false;
                menuItem.setText("Start game");
                message.setText("The game is over.  Please use the menu to start the game.");
                repaint();
                message.repaint();
                JOptionPane.showMessageDialog(frame, "The " + colorName[playerColor[playerTurn]+1] + " player wins!\nCongratulations " + playerNames[playerAI[playerTurn]]);
                return;
            }
     
            if (board.isFull())
            {
                gameInProgress = false;
                menuItem.setText("Start game");
                message.setText("The game is over.  Please use the menu to start the game.");
                repaint();
                message.repaint();
                JOptionPane.showMessageDialog(frame, "It's a tie.");
                return;            
            }
     
            playerTurn = (playerTurn + 1) % 2;
            if (players[playerAI[playerTurn]] != null)
            {
                message.setText("It is " + playerNames[playerAI[playerTurn]] + " (" + colorName[playerColor[playerTurn]+1] + "s) turn, please wait.");
                new Thread(new AITurn()).start();
            }
            else
                message.setText("It is your turn, " + colorName[playerColor[playerTurn]+1] + " player.  Click the mouse to drop the piece.");
            repaint();
            message.repaint();
        }
     
        class AITurn implements Runnable
        {
            public void run ()
            {
                if (gameInProgress == false)
                    return;
     
                synchronized (this)
                {
                    long time = System.currentTimeMillis();
                    int column = players[playerAI[playerTurn]].makeMove(board, playerColor[playerTurn]);
                    if (playerColor[playerTurn] == Connect4Board.RED)
                        board.addRedChecker(column);
                    else
                        board.addBlackChecker(column);
                    if (System.currentTimeMillis() - time < 1000)
                    { try { Thread.sleep(1000); } catch (Exception e) {}}
                    repaint();
                    advancePlayer();
                }
            }
        }
     
        public void promptForPlayers ()
        {
            playerAI[0] = 0;
            playerAI[1] = 0;
     
            String s = (String) JOptionPane.showInputDialog (frame, "Who should play the red pieces?",
                                                             "Select a player",
                                                             JOptionPane.PLAIN_MESSAGE, null,
                                                             playerNames, "Human");
            for (int i = 0; i < playerNames.length; i++)
                if (s.equals(playerNames[i]))
                {
                    playerAI[0] = i;
                }
     
            s = (String) JOptionPane.showInputDialog (frame, "Who should play the black pieces?",
                                                             "Select a player",
                                                             JOptionPane.PLAIN_MESSAGE, null,
                                                             playerNames, "Human");
            for (int i = 0; i < playerNames.length; i++)
                if (s.equals(playerNames[i]))
                {
                    playerAI[1] = i;
                }
        }
     
        public void paint (Graphics g)
        {
            int width = this.getSize().width;
            int height = this.getSize().height;
     
            g.setColor(new Color(0.6f, 0.7f, 1.0f));
            g.fillRect(0, 0, width, height);
     
            g.setColor(Color.DARK_GRAY);
            g.fillRect(50, 20, 704, 704);
     
            for (int row = 0; row < 8; row++)
                for (int column = 0; column < 8; column++)
                {
                    int space = drawState[row][column];
                    if (space == Connect4Board.RED)
                        g.setColor(Color.RED);
                    else if (space == Connect4Board.BLACK)
                        g.setColor(Color.BLACK);
                    else
                        g.setColor(Color.WHITE);
                    g.fillOval (59 + 88*column, 645 - 88*row, 70, 70);
                }
     
            if (proposedColumn >= 0 && proposedRow >= 0)
            {
                g.setColor(new Color(0.7f, 1.0f, 0.7f));
                g.fillOval (59 + 88*proposedColumn, 645 - 88*proposedRow, 70, 70);
            }
        }
     
        public void mouseMoved (MouseEvent e)
        {
            if (!gameInProgress || players[playerAI[playerTurn]] != null)
                return;
     
            int x = e.getX();
     
            int nextColumn = (x - 50) / 88;
            int nextRow = 8;
            while (nextColumn >= 0 && nextColumn <= 7 && nextRow > 0 && board.getSpaceContents(nextRow-1, nextColumn) == Connect4Board.NONE)
                nextRow--;
     
            if (x < 50 || nextColumn < 0 || nextColumn > 7 || nextRow < 0 || nextRow > 7)
            {
                nextColumn = -1;
                nextRow = -1;
            }
     
            if (nextColumn != proposedColumn || nextRow != proposedRow)
            {
                proposedRow = nextRow;
                proposedColumn = nextColumn;
                repaint();
            }
        }
     
        public void mouseDragged (MouseEvent e)
        {
            mouseMoved(e);
        }
     
        public void mouseClicked (MouseEvent e)
        {
     
        }
     
        public void mousePressed (MouseEvent e)
        {
     
        }
     
        public void mouseReleased (MouseEvent e)
        {
            if (players[playerAI[playerTurn]] != null)
                return;
     
            if (proposedRow >= 0 && proposedColumn >= 0)
            {
                if (playerColor[playerTurn] == Connect4Board.BLACK)
                    board.addBlackChecker(proposedColumn);
                else
                    board.addRedChecker(proposedColumn);
     
                advancePlayer();
            }
        }
     
        public void mouseEntered (MouseEvent e)
        {
     
        }
     
        public void mouseExited (MouseEvent e)
        {
     
        }
    }

    This is the class I'm supposed to write:

    package extracredit02;
     
    public class Board implements Connect4Board
    {
     
    	/**
         * This method will clear the board's grid so that all spaces
         * are marked as having 'no checker' in each space.
         */
        public void clear()
        {
     
        }
     
        /**
         * This method adds a red checker to the specified column, if
         * possible.  (If this column is full, nothing happens.)  If
         * there is space in the column for another checker, then
         * a red checker will be placed in the lowest unoccupied
         * space in the column.
         * 
         * Column 0 corresponds to the left side of the grid.
         * 
         * @param column A column number, from 0 to 7.
         */
    	public void addRedChecker(int column) {
    		// TODO Auto-generated method stub
     
    	}
     
    	/**
         * This method adds a black checker to the specified column, if
         * possible.  (If this column is full, nothing happens.)  If
         * there is space in the column for another checker, then
         * a black checker will be placed in the lowest unoccupied
         * space in the column.
         * <p>
         * 
         * Column 0 corresponds to the left side of the grid.
         * 
         * @param column A column number, from 0 to 7.
         */
    	public void addBlackChecker(int column) {
     
     
    	}
     
    	/**
         * This method removes the topmost checker from the specified
         * column.  If the column is empty, nothing happens.
         * 
         * Column 0 corresponds to the left side of the grid.
         * 
         * @param column A column number, from 0 to 7.
         */
    	public void removeChecker(int column) {
    		// TODO Auto-generated method stub
     
    	}
     
    	 /**
         * Returns true if the board is full of checkers.
         * 
         * @return true if the board is full of checkers.
         */
    	public boolean isFull() {
    		// TODO Auto-generated method stub
    		return false;
    	}
     
    	/**
         * Returns an integer describing the checker in the specified
         * space in the grid.  Row 0 corresponds to the bottom
         * of the grid, column 0 corresponds to the left side of the grid.
         * <p>
         * 
         * Returns the RED constant (defined above) if the space has
         * a red checker in it, the BLACK constant (defined above) if the
         * space has a black checker in it, and NONE (defined above) if
         * there is no checker in the space.
         * <p>
         * 
         * If the row or column number is outside the range 0..7, this
         * method will return NONE (defined above).
         * 
         * @param row A row number, from 0 to 7.
         * @param column A column number, from 0 to 7.
         * @return An integer that describes the contents of the space.
         */
    	public int getSpaceContents(int row, int column) {
    		// TODO Auto-generated method stub
    		return 0;
    	}
     
    	 /**
         * Returns true if the board has four red checkers together in a row,
         * column, or diagonal line.  This would indicate a win for red.
         * 
         * @return True if there are four red checkers in a line.
         */
    	public boolean redHasWon() {
    		// TODO Auto-generated method stub
    		return false;
    	}
     
    	/**
         * Returns true if the board has four black checkers together in a row,
         * column, or diagonal line.  This would indicate a win for black.
         * 
         * @return True if there are four black checkers in a line.
         */
    	public boolean blackHasWon() {
    		// TODO Auto-generated method stub
    		return false;
    	}
     
    	/**
         * Returns an integer describing the winner of this game, if any.
         * <p>
         * 
         * Returns the RED constant (defined above) if red has won the
         * game, the BLACK constant (defined above) if black has won the
         * game, and NONE (defined above) if no one has won yet.
         * 
         * @return An integer that describes the winning color, if any.
         */
    	public int getWinner() {
    		// TODO Auto-generated method stub
    		return 0;
    	}
     
    }

    appreciate any help/clarification

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Connect 4 program

    Can you explain what your problems are one by one?
    If you don't understand my answer, don't ignore it, ask a question.

  4. #4
    Junior Member
    Join Date
    Apr 2012
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Connect 4 program

    I suppose I'm not sure how to actually get the connect4 class to paint the red or black checker piece when I click. As it is, when it runs, it paints the outline of the board but doesn't paint anything when I click. Would I write an onclick method within the board class?

    How do I get a checker piece to fall into the lowest position in a row when I click?

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Connect 4 program

    paint the red or black checker piece when I click
    Is the checker a component you can add a listener to? When it is clicked, the listener could set some values for the paint method to use to control waht it paints when it is called after the listener calls the repaint method.
    How do I get a checker piece to fall
    The listener could set the new location for the checker that the paint method would use when it was called after a call to repaint.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Connect Four GUI
    By gromacs in forum What's Wrong With My Code?
    Replies: 2
    Last Post: June 6th, 2011, 09:42 AM
  2. Need help to connect to PostgreSql
    By stab in forum JDBC & Databases
    Replies: 3
    Last Post: June 3rd, 2011, 09:01 AM
  3. Cant connect with database
    By ronn1e in forum JDBC & Databases
    Replies: 1
    Last Post: January 4th, 2011, 05:45 PM
  4. Cant connect with database
    By ronn1e in forum What's Wrong With My Code?
    Replies: 0
    Last Post: January 4th, 2011, 04:09 PM
  5. How to connect keyboard through COM?
    By yogesh01 in forum Java Theory & Questions
    Replies: 0
    Last Post: July 6th, 2010, 05:00 AM