So I have an assignment due tomorrow and I've been trying to get this program to work, but it's quite difficult for me to do. I need help in taking the user's input and placing it on the grid and checking for all the matches to see if one of the players won.

Thank-you!

/*
 * CPT program
 */

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;        
import java.util.Scanner;

public class CPT implements ActionListener 
{
  JFrame frame;
  JPanel contentPane;
  JButton displayMessage;
  
  public CPT()
  {
    /* Create and set up the frame */
    frame = new JFrame("Connect Four");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    /* Create a content pane with a BoxLayout and empty borders */
    contentPane = new JPanel();
    contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    contentPane.setBackground(Color.white);
    contentPane.setLayout(new GridLayout(0, 2, 5, 10));
    
    /* Create a button */
    displayMessage = new JButton("Play Now!");
    displayMessage.setBackground(Color.yellow);
    displayMessage.setForeground(Color.blue);
    displayMessage.addActionListener(this);
    contentPane.add(displayMessage);
    
    /* Add content pane to frame */
    frame.setContentPane(contentPane);
    
    /* Size and then display the frame. */
    frame.pack();
    frame.setVisible(true);
  }
  
  /**
   * Handle a the button click
   * pre: none
   * post: A message has been displayed.
   */
  public void actionPerformed(ActionEvent event) 
  {    
    Scanner input = new Scanner(System.in);
    String player1;
    String player2;
    int choice;
    int currentPlayer;
    int player1Turn = 1;
    int player2Turn = 2;
    
    int draw = 0;
    int win = 0;
    int count =0;
    
    //Columns
    int col1 = 12;
    int col2 = 13;
    int col3 = 14;
    int col4 = 15;
    
    //Prompt Player for Name
    System.out.print("Player one, enter your name:");
    player1 = input.nextLine();
    player1 = player1.toUpperCase();
    
    System.out.print("Player two, enter your name:");
    player2 = input.nextLine();
    player2 = player2.toUpperCase();
    
    //Assign Players a Color (Black or Red)
    System.out.println(player1 + "  " + "you are BLACK." + "  " +  player2 + "  " +"you are RED");
    System.out.println("");
    
    do
    {
    //Display Grid
    String [] grid = new String [16];
    System.out.println("1 2 3 4");
    for (int i = 0; i<grid.length; i++)
    {
      grid[i]="*";
    }
    for (int i = 0; i <grid.length; i++)
    {
      
      System.out.print (grid[i]+ " ");
      
      
      if(i%4 == 3)
        
      {
        System.out.println (" ");
      }
    }
    
    //Ask user what spot they want to play their chip
    System.out.println(player1 + " , which column do you want to place your chip in?");
    choice = input.nextInt();
    
    count = count + 1;
    
    // Check whose turn
      if (player1Turn ==1)
      {
        System.out.println ("B"); player2Turn=2; 
        
      }
      else 
      {
        System.out.println ("R"); player1Turn=1;
      }
      


    //Check if spot is free on board
    if (grid[choice].equals ("R") || grid[choice].equals("B"))
    {
      System.out.println("This spot is already taken. Try again!");
      choice = input.nextInt();
    }
    
    else
    {
      grid[choice] = "R";
    }
    

    
    
    //Check if tie game
    if (count == 16)
    {
      System.out.print("Tie Game.");
      draw = 1;
    }
    }while (draw==0 && win==0);
    
  }
  
  
  /**
   * Create and show the GUI.
   */
  private static void runGUI() 
  {
    JFrame.setDefaultLookAndFeelDecorated(true);
    
    CPT myApplication = new CPT();
  }
  
  public static void main(String[] args) 
  {
    /* Methods that create and show a GUI should be 
     run from an event-dispatching thread 
     */
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        runGUI();
      }
    });
  }
}

Recommended Answers

All 15 Replies

What are you having trouble with?

What are you having trouble with?

Taking the user's input (column #) and placing the chip accoridng to them (Red or Black) on the board. Also, checking if the user won vertically, horizontally, etc.

That sounds like a description of the assignment. Given that you need to think of the steps the program needs to take to do the job. When you get those steps figured out, then you start writing the code.

What are the programming steps you are having problems with?

That sounds like a description of the assignment. Given that you need to think of the steps the program needs to take to do the job. When you get those steps figured out, then you start writing the code.

What are the programming steps you are having problems with?

I just need help in figuring out how to check horizontally, etc.
I don't know how to check for it.

how to check horizontally

Given a row, you want to check the columns near a given column for their contents?
You do that by changing the column index by -1 for the left and +1 for the right.

That makes my doubts clear! Thank you very much!

Given a row, you want to check the columns near a given column for their contents?
You do that by changing the column index by -1 for the left and +1 for the right.

I have a another question. How do I keep track of the users turn and when to switch?

Go by the rules of the game.
When is a user's turn over?

Have a variable that refers to the current player.

Go by the rules of the game.
When is a user's turn over?

Have a variable that refers to the current player.

Okay. So I have to place the user's chip in the lowest spot available and I have variables for each column that store the lowest spot (ex. col1=12).

I'm havng trouble in taking the input and actually placing it on the grid. Whenever I enter in the column # the 'B' doesn't come on the grid. It displays before the grid prints.

Try debugging the code by adding println statements to show execution flow and the values of variables as they change. The output should help you understand what the code is doing.

When I enter a column #, I'm getting
"Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 4
at CPT.actionPerformed(CPT.java:174)"

Why is it out of bounds?

This is my current code:

/*
 * CPT program
 */

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;        
import java.util.Scanner;

public class CPT implements ActionListener 
{
  JFrame frame;
  JPanel contentPane;
  JButton displayMessage;
  
  public CPT()
  {
    /* Create and set up the frame */
    frame = new JFrame("Connect Four");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    /* Create a content pane with a BoxLayout and empty borders */
    contentPane = new JPanel();
    contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    contentPane.setBackground(Color.white);
    contentPane.setLayout(new GridLayout(0, 2, 5, 10));
    
    /* Create a button */
    displayMessage = new JButton("Play Now!");
    displayMessage.setBackground(Color.yellow);
    displayMessage.setForeground(Color.blue);
    displayMessage.addActionListener(this);
    contentPane.add(displayMessage);
    
    /* Add content pane to frame */
    frame.setContentPane(contentPane);
    
    /* Size and then display the frame. */
    frame.pack();
    frame.setVisible(true);
  }
  
  /**
   * Handle a the button click
   * pre: none
   * post: A message has been displayed.
   */
  public void actionPerformed(ActionEvent event) 
  {    
    Scanner input = new Scanner(System.in);
    String player1;
    String player2;
    String currentPlayer;
    int playerTurn=0;
    
    int choice;
    int draw = 0;
    int win = 0;
    int count =0;
    
    //Columns
    final int COL = 4;
    final int ROWS = 4;
    int col1 = 12;
    int col2 = 13;
    int col3 = 14;
    int col4 = 15;
    int [] column = new int [COL];
    int [] row = new int [ROWS];
    
    //Prompt Player for Name
    System.out.print("Player one, enter your name:");
    player1 = input.nextLine();
    player1 = player1.toUpperCase();
    
    System.out.print("Player two, enter your name:");
    player2 = input.nextLine();
    player2 = player2.toUpperCase();
    
    //Assign Players a Color (Black or Red)
    System.out.println(player1 + "  " + "you are BLACK." + "  " +  player2 + "  " +"you are RED");
    System.out.println("");
    
    do
    {
      //Display Grid
      String [] grid = new String [16];
      System.out.println("0 1 2 3");
      for (int i = 0; i<grid.length; i++)
      {
        grid[i]="*";
      }
      for (int i = 0; i <grid.length; i++)
      {
        
        System.out.print (grid[i]+ " ");
        
        
        if(i%4 == 3)
          
        {
          System.out.println (" ");
        }
      }
         
      //Counter- to keep track of how many plays have taken place & who's currentPlayer
      count = count + 1;
      playerTurn = 1;
      
      
      // Check whose turn
      if (playerTurn ==1)
      {
        System.out.println (player1 + "it is your turn."); 
        currentPlayer = player1;
        playerTurn=2; 
        
      }
      else 
      {
        System.out.println (player2 + "it is your turn."); 
        currentPlayer = player2;
        playerTurn=1;
      }
      
      //Ask user what spot they want to play their chip
      System.out.println(currentPlayer + " , which column do you want to place your chip in?");
      choice = input.nextInt();
      
      
      //Check if spot is free on board
      if (grid[choice].equals ("B") || grid[choice].equals("R"))
      {
        System.out.println("This spot is already taken. Try again!");
        choice = input.nextInt();
      }
      
      else
      {
        grid[choice] ="B";
      }
      
      //Check ROWS
      for (int rows =0; rows<ROWS; rows++)
      {
        for (int i=0; i< COL; i++)
        {
          
          if (column[i] == -4 || column[i] == 4)
          {
            System.out.print(currentPlayer + ", you won!");
            win = 1;
          }
        }
      }
      
      
      //Check COLUMNS
      for (int columns=0; columns < COL; columns++){
        for (int j=0; j < ROWS; j++){
          if (row[j] == -4 || row[j] == 4)
          {
            System.out.print(currentPlayer + ", you won!");
            win = 1;
          }
        }
      }
      
      
      //Check DIAGONALS
      for (int i=0; i< COL; i++)
      {  
        
        if (((column[i] == (choice)) && (row[i] ==(choice))) || ((column[ROWS-i] == (choice)) && (row[i] == (choice))) )
          
        {count++;           
          if (count == 4)                 
          {                     
            System.out.print(currentPlayer + ", you won!");
            win = 1;           
          }              
        }
      }
      
      for (int i=0; i< COL; i++)
      {  
        
        if (((column[i] == (choice)) && (row[i] ==(choice))) || ((column[ROWS+i] == (choice)) && (row[i] == (choice))) )
          
        {count++;           
          if (count == 4)                 
          {                     
            System.out.print(currentPlayer + ", you won!");
            win = 1;             
          }              
        }
      }
      
      //Check if draw(tie) game
      if (count == 16)
      {
        System.out.print("Tie Game - Game Over!");
        draw = 1;
      }
    }while (draw==0 && win==0);
    
  }
  
  
  /**
   * Create and show the GUI.
   */
  private static void runGUI() 
  {
    JFrame.setDefaultLookAndFeelDecorated(true);
    
    CPT myApplication = new CPT();
  }
  
  public static void main(String[] args) 
  {
    /* Methods that create and show a GUI should be 
     run from an event-dispatching thread 
     */
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        runGUI();
      }
    });
  }
}

Why is it out of bounds?

Because the array has less than 5 slots.
Remember arrays are indexed from 0 the the length-1

Because the array has less than 5 slots.
Remember arrays are indexed from 0 the the length-1

So how can I fix this?

Change the value of index to the array so that it stays in bounds.

Change the value of index to the array so that it stays in bounds.

Alright, thanks a lot for your help! Much appreciated :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.