Jump to content

Help with connect four win check

- - - - -

  • Please log in to reply
11 replies to this topic

#1
computer0101

computer0101

    Newbie

  • Members
  • Pip
  • 7 posts
I am a highschool student and I am making a connect four game for a school project. BUT I am having some difficulties trying to check for a winner. Help please!

Here is the code so far:



/*
*
*/


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

public class ConnectFourOne implements ActionListener
{
JFrame frame;
JPanel contentPane;
JButton displayMessage;

public ConnectFourOne()
{
/* Create and set up the frame */
frame = new JFrame("ConnectFourOne");
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("Begin");
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)
{
String [] spaceArray = new String [25];
int pickOne;
int colOne = 25;
int colTwo = 26;
int colThree = 27;
int colFour = 28;
int colFive = 29;
Scanner input = new Scanner(System.in);

for(int i = 0; i < spaceArray.length; i++)
{
spaceArray[i] = new String(" - ");
}
// create the board
System.out.println(" 1 2 3 4 5");
System.out.println("");
System.out.println(" " + spaceArray[0] + " " + spaceArray[1] + " " + spaceArray[2] + " " + spaceArray[3] + " " + spaceArray[4]);
System.out.println(" " + spaceArray[5] + " " + spaceArray[6] + " " + spaceArray[7] + " " + spaceArray[8] + " " + spaceArray[9]);
System.out.println(" " + spaceArray[10] + " " + spaceArray[11] + " " + spaceArray[12] + " " + spaceArray[13] + " " + spaceArray[14]);
System.out.println(" " + spaceArray[15] + " " + spaceArray[16] + " " + spaceArray[17] + " " + spaceArray[18] + " " + spaceArray[19]);
System.out.println(" " + spaceArray[20] + " " + spaceArray[21] + " " + spaceArray[22] + " " + spaceArray[23] + " " + spaceArray[24]);
System.out.println("");

for(int j = 0; j < spaceArray.length; j++)
{
if ( j % 2 == 0)
{
System.out.println("Player One: In which column do you want to place the 'O'? (1,2,3,4,5) ");
pickOne = input.nextInt();
if (pickOne == 1)
{
colOne = colOne-5;
spaceArray[colOne] = " O ";
}
else if (pickOne == 2)
{
colTwo = colTwo-5;
spaceArray[colTwo] = " O ";
}
else if (pickOne == 3)
{
colThree = colThree-5;
spaceArray[colThree] = " O ";
}
else if (pickOne == 4)
{
colFour = colFour-5;
spaceArray[colFour] = " O ";
}
else if (pickOne == 5)
{
colFive = colFive-5;
spaceArray[colFive] = " O ";
}

//add chip to board
System.out.println(" 1 2 3 4 5");
System.out.println("");
System.out.println(" " + spaceArray[0] + " " + spaceArray[1] + " " + spaceArray[2] + " " + spaceArray[3] + " " + spaceArray[4]);
System.out.println(" " + spaceArray[5] + " " + spaceArray[6] + " " + spaceArray[7] + " " + spaceArray[8] + " " + spaceArray[9]);
System.out.println(" " + spaceArray[10] + " " + spaceArray[11] + " " + spaceArray[12] + " " + spaceArray[13] + " " + spaceArray[14]);
System.out.println(" " + spaceArray[15] + " " + spaceArray[16] + " " + spaceArray[17] + " " + spaceArray[18] + " " + spaceArray[19]);
System.out.println(" " + spaceArray[20] + " " + spaceArray[21] + " " + spaceArray[22] + " " + spaceArray[23] + " " + spaceArray[24]);
System.out.println("");
}
else
{
System.out.println("Player Two: In which column do you want to place the 'T'? (1,2,3,4,5) ");
pickOne = input.nextInt();
if (pickOne == 1)
{
colOne = colOne-5;
spaceArray[colOne] = " T ";
}
else if (pickOne == 2)
{
colTwo = colTwo-5;
spaceArray[colTwo] = " T ";
}
else if (pickOne == 3)
{
colThree = colThree-5;
spaceArray[colThree] = " T ";
}
else if (pickOne == 4)
{
colFour = colFour-5;
spaceArray[colFour] = " T ";
}
else if (pickOne == 5)
{
colFive = colFive-5;
spaceArray[colFive] = " T ";
}

//add chip to board
System.out.println(" 1 2 3 4 5");
System.out.println("");
System.out.println(" " + spaceArray[0] + " " + spaceArray[1] + " " + spaceArray[2] + " " + spaceArray[3] + " " + spaceArray[4]);
System.out.println(" " + spaceArray[5] + " " + spaceArray[6] + " " + spaceArray[7] + " " + spaceArray[8] + " " + spaceArray[9]);
System.out.println(" " + spaceArray[10] + " " + spaceArray[11] + " " + spaceArray[12] + " " + spaceArray[13] + " " + spaceArray[14]);
System.out.println(" " + spaceArray[15] + " " + spaceArray[16] + " " + spaceArray[17] + " " + spaceArray[18] + " " + spaceArray[19]);
System.out.println(" " + spaceArray[20] + " " + spaceArray[21] + " " + spaceArray[22] + " " + spaceArray[23] + " " + spaceArray[24]);
System.out.println("");
}

}
}

/**
* Create and show the GUI.
*/
private static void runGUI()
{
JFrame.setDefaultLookAndFeelDecorated(true);

ConnectFourOne myApplication = new ConnectFourOne ();
}

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();
}
});
}
}

#2
computer0101

computer0101

    Newbie

  • Members
  • Pip
  • 7 posts
The action performed part:

public void actionPerformed(ActionEvent event) 

{ 

String [] spaceArray = new String [25]; 

int pickOne;

int colOne = 25;

int colTwo = 26;

int colThree = 27;

int colFour = 28;

int colFive = 29;

Scanner input = new Scanner(System.in);


for(int i = 0; i < spaceArray.length; i++) 

{ 

spaceArray[i] = new String(" - ");

}

// create the board

System.out.println(" 1 2 3 4 5");

System.out.println("");

System.out.println(" " + spaceArray[0] + " " + spaceArray[1] + " " + spaceArray[2] + " " + spaceArray[3] + " " + spaceArray[4]);

System.out.println(" " + spaceArray[5] + " " + spaceArray[6] + " " + spaceArray[7] + " " + spaceArray[8] + " " + spaceArray[9]);

System.out.println(" " + spaceArray[10] + " " + spaceArray[11] + " " + spaceArray[12] + " " + spaceArray[13] + " " + spaceArray[14]);

System.out.println(" " + spaceArray[15] + " " + spaceArray[16] + " " + spaceArray[17] + " " + spaceArray[18] + " " + spaceArray[19]);

System.out.println(" " + spaceArray[20] + " " + spaceArray[21] + " " + spaceArray[22] + " " + spaceArray[23] + " " + spaceArray[24]);

System.out.println("");


for(int j = 0; j < spaceArray.length; j++)

{

if ( j % 2 == 0)

{

System.out.println("Player One: In which column do you want to place the 'O'? (1,2,3,4,5) ");

pickOne = input.nextInt();

if (pickOne == 1)

{

colOne = colOne-5;

spaceArray[colOne] = " O ";

}

else if (pickOne == 2)

{

colTwo = colTwo-5;

spaceArray[colTwo] = " O ";

}

else if (pickOne == 3)

{

colThree = colThree-5;

spaceArray[colThree] = " O ";

}

else if (pickOne == 4)

{

colFour = colFour-5;

spaceArray[colFour] = " O ";

}

else if (pickOne == 5)

{

colFive = colFive-5;

spaceArray[colFive] = " O ";

}


//add chip to board

System.out.println(" 1 2 3 4 5");

System.out.println("");

System.out.println(" " + spaceArray[0] + " " + spaceArray[1] + " " + spaceArray[2] + " " + spaceArray[3] + " " + spaceArray[4]);

System.out.println(" " + spaceArray[5] + " " + spaceArray[6] + " " + spaceArray[7] + " " + spaceArray[8] + " " + spaceArray[9]);

System.out.println(" " + spaceArray[10] + " " + spaceArray[11] + " " + spaceArray[12] + " " + spaceArray[13] + " " + spaceArray[14]);

System.out.println(" " + spaceArray[15] + " " + spaceArray[16] + " " + spaceArray[17] + " " + spaceArray[18] + " " + spaceArray[19]);

System.out.println(" " + spaceArray[20] + " " + spaceArray[21] + " " + spaceArray[22] + " " + spaceArray[23] + " " + spaceArray[24]);

System.out.println("");

}

else 

{

System.out.println("Player Two: In which column do you want to place the 'T'? (1,2,3,4,5) ");

pickOne = input.nextInt();

if (pickOne == 1)

{

colOne = colOne-5;

spaceArray[colOne] = " T ";

}

else if (pickOne == 2)

{

colTwo = colTwo-5;

spaceArray[colTwo] = " T ";

}

else if (pickOne == 3)

{

colThree = colThree-5;

spaceArray[colThree] = " T ";

}

else if (pickOne == 4)

{

colFour = colFour-5;

spaceArray[colFour] = " T ";

}

else if (pickOne == 5)

{

colFive = colFive-5;

spaceArray[colFive] = " T ";

}


//add chip to board

System.out.println(" 1 2 3 4 5");

System.out.println("");

System.out.println(" " + spaceArray[0] + " " + spaceArray[1] + " " + spaceArray[2] + " " + spaceArray[3] + " " + spaceArray[4]);

System.out.println(" " + spaceArray[5] + " " + spaceArray[6] + " " + spaceArray[7] + " " + spaceArray[8] + " " + spaceArray[9]);

System.out.println(" " + spaceArray[10] + " " + spaceArray[11] + " " + spaceArray[12] + " " + spaceArray[13] + " " + spaceArray[14]);

System.out.println(" " + spaceArray[15] + " " + spaceArray[16] + " " + spaceArray[17] + " " + spaceArray[18] + " " + spaceArray[19]);

System.out.println(" " + spaceArray[20] + " " + spaceArray[21] + " " + spaceArray[22] + " " + spaceArray[23] + " " + spaceArray[24]);

System.out.println("");

}


}

}


#3
gregwarner

gregwarner

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 853 posts
  • Location:Arkansas
Can you be a little more specific with your problem? That's an awful lot of code for us to look over.

Try posting just the relevant portions of your code, along with a more descriptive explanation of the problem. (Can't compile? Unhandled runtime exceptions? Producing incorrect logic results?) If you're getting IDE error messages or stack traces, post those as well. Let us know what we're looking for.
Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.

– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid


#4
computer0101

computer0101

    Newbie

  • Members
  • Pip
  • 7 posts
Oh, sorry about that.
So far the code works fine. All that code allows players one and two to put in the chips/counters in the chosen column.

I am unsure as to how I could even try to find a winner and where would I put the code.

Btw, I must use arrays, NOT 2D arrays, and loops. :$

#5
gregwarner

gregwarner

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 853 posts
  • Location:Arkansas
I'm a little confused. Why must you not use 2D arrays? Isn't Connect 4 played on a 2D grid? Seems pretty intuitive to use 2D arrays if you ask me.

Also, wouldn't this:

// create the board

System.out.println(" 1 2 3 4 5");

System.out.println("");

System.out.println(" " + spaceArray[0] + " " + spaceArray[1] + " " + spaceArray[2] + " " + spaceArray[3] + " " + spaceArray[4]);

System.out.println(" " + spaceArray[5] + " " + spaceArray[6] + " " + spaceArray[7] + " " + spaceArray[8] + " " + spaceArray[9]);

System.out.println(" " + spaceArray[10] + " " + spaceArray[11] + " " + spaceArray[12] + " " + spaceArray[13] + " " + spaceArray[14]);

System.out.println(" " + spaceArray[15] + " " + spaceArray[16] + " " + spaceArray[17] + " " + spaceArray[18] + " " + spaceArray[19]);

System.out.println(" " + spaceArray[20] + " " + spaceArray[21] + " " + spaceArray[22] + " " + spaceArray[23] + " " + spaceArray[24]);

System.out.println("");

be better done in a loop? Also, since you've copied and pasted this block of code several times, that's a good indicator that this should go in a function, not copied multiple times.
Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.

– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid


#6
computer0101

computer0101

    Newbie

  • Members
  • Pip
  • 7 posts

  /**

   * Handle a the button click

   * pre: none

   * post: A message has been displayed.

   */

  public void actionPerformed(ActionEvent event) 

  {   

    String [] spaceArray = new String [25]; 

    int pickOne;

    int user = -1;

    int colOne = 25;

    int colTwo = 26;

    int colThree = 27;

    int colFour = 28;

    int colFive = 29;

    String playOne = " O ";

    String playTwo = " T ";

    

    Scanner input = new Scanner(System.in);

    

    for(int i = 0; i < spaceArray.length; i++)                         

    { 

      spaceArray[i] = new String(" - ");

    }

    // create the board

    System.out.println("  1   2   3   4   5");

    System.out.println("");

    System.out.println(" " + spaceArray[0] + " " + spaceArray[1] + " " + spaceArray[2] + " " + spaceArray[3] + " " + spaceArray[4]);

    System.out.println(" " + spaceArray[5] + " " + spaceArray[6] + " " + spaceArray[7] + " " + spaceArray[8] + " " + spaceArray[9]);

    System.out.println(" " + spaceArray[10] + " " + spaceArray[11] + " " + spaceArray[12] + " " + spaceArray[13] + " " + spaceArray[14]);

    System.out.println(" " + spaceArray[15] + " " + spaceArray[16] + " " + spaceArray[17] + " " + spaceArray[18] + " " + spaceArray[19]);

    System.out.println(" " + spaceArray[20] + " " + spaceArray[21] + " " + spaceArray[22] + " " + spaceArray[23] + " " + spaceArray[24]);

    System.out.println("");

    

    do 

    {

      user = user + 1;

      if ( user % 2 == 0)

      {

        System.out.println("Player One: In which column do you want to place the 'O'? (1,2,3,4,5) ");

        pickOne = input.nextInt();

        if (pickOne == 1)

        {

          colOne = colOne-5;

          if (colOne > -5)

          {

            spaceArray[colOne] = " O ";

          }

        }

        else if (pickOne == 2)

        {

          colTwo = colTwo-5;

          if (colTwo > -4)

          {

            spaceArray[colTwo] = " O ";

          }

        }

        else if (pickOne == 3)

        {

          colThree = colThree-5;

          if (colThree > -3)

          {

            spaceArray[colThree] = " O ";

          }

        }

        else if (pickOne == 4)

        {

          colFour = colFour-5;

          if (colFour > -2)

          {

            spaceArray[colFour] = " O ";

          }

        }

        else if (pickOne == 5)

        {

          colFive = colFive-5;

          if (colFive > -1)

          {

            spaceArray[colFive] = " O ";

          }

        }

        

      }

      else 

      {

        System.out.println("Player Two: In which column do you want to place the 'T'? (1,2,3,4,5) ");

        pickOne = input.nextInt();

        if (pickOne == 1)

        {

          colOne = colOne-5;

          if (colOne > -5)

          {

            spaceArray[colOne] = " T ";

          }

        }

        else if (pickOne == 2)

        {

          colTwo = colTwo-5;

          if (colTwo > -4)

          {

            spaceArray[colTwo] = " T ";

          }

        }

        else if (pickOne == 3)

        {

          colThree = colThree-5;

          if (colThree > -3)

          {

            spaceArray[colThree] = " T ";

          }

        }

        else if (pickOne == 4)

        {

          colFour = colFour-5;

          if (colFour > -2)

          {

            spaceArray[colFour] = " T ";

          }

        }

        else if (pickOne == 5)

        {

          colFive = colFive-5;

          if (colFive > -1)

          {

            spaceArray[colFive] = " T ";

          }

        }

      }

      //add chip to board

      System.out.println("  1   2   3   4   5");

      System.out.println("");

      System.out.println(" " + spaceArray[0] + " " + spaceArray[1] + " " + spaceArray[2] + " " + spaceArray[3] + " " + spaceArray[4]);

      System.out.println(" " + spaceArray[5] + " " + spaceArray[6] + " " + spaceArray[7] + " " + spaceArray[8] + " " + spaceArray[9]);

      System.out.println(" " + spaceArray[10] + " " + spaceArray[11] + " " + spaceArray[12] + " " + spaceArray[13] + " " + spaceArray[14]);

      System.out.println(" " + spaceArray[15] + " " + spaceArray[16] + " " + spaceArray[17] + " " + spaceArray[18] + " " + spaceArray[19]);

      System.out.println(" " + spaceArray[20] + " " + spaceArray[21] + " " + spaceArray[22] + " " + spaceArray[23] + " " + spaceArray[24]);

      System.out.println("");

      

    }while (//spaces are not filled || no win detected);

  }

  


here is the new code
i dont know how to write the code for the while statement

we havent learnt about 2D arrays yet. That's why the teacher doesnt want us to use them

#7
gregwarner

gregwarner

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 853 posts
  • Location:Arkansas
I see. So basically all you need is to write two functions for your two test cases, spaces are not filled, and no win detected.

For the spaces not filled, that's simple. Since the columns fill from the bottom up, there's no need to check all the spaces. Simply check if each of your five column indicators is at the top, and if so, then you know all the spaces have been filled.

Checking for a win is a bit trickier. To save time, you only need to check if the most recent piece added completes a sequence of 4 or more (since you could potentially have 5 in a row, given the size of your board.) From the position of the last piece added, you need to check in 4 directions: horizontal, vertical, diagonal on y=x, and diagonal on y=-x, assuming you want to allow diagonals in this game.

To do that, it's best to find a function which maps a pair of X,Y coordinates to a final position in your 1D array. (Hint, this is exactly how the C compiler does it when you use 2D arrays!) I'll give you a hint: you'll use a multiplication operator and an addition operator. Beyond that, I don't want to spoil your joy of figuring out the formula for yourself.

Once you have that function mapping a pair of coordinates to an index, it becomes trivial to check for a win, since you can simply loop over each direction, counting iterations until you find a differing or empty slot. Don't forget to check for your array bounds!

EDIT: I would also suggest you add some sort of error message when a user selects a column that's already full. That's just a little more user friendly. Also, there's still a huge portion (over 80% by the looks of it, just eyeballing) that can be eliminated by writing functions.
Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.

– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid


#8
computer0101

computer0101

    Newbie

  • Members
  • Pip
  • 7 posts
I added the error message like you suggested and I also added the code to see if there are still spaces :) Thank you

BUT I really can't figure out how to check for a win with X and Y.
Should I just write out all the possible combinations and put them in an if statement? But that is a lot of possibilities, 28 to be exact D:

ps, this program is due by friday

#9
gregwarner

gregwarner

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 853 posts
  • Location:Arkansas

computer0101 said:

Should I just write out all the possible combinations and put them in an if statement? But that is a lot of possibilities, 28 to be exact D:

No way. That would take longer than the better solution. Plus, it's too easy to make a mistake that way. You want an algorithm that is provable.

Imagine how difficult it would be to hard code every possible combination for a grid of 100 by 100! A better solution is an algorithm which works on any size grid.

The solution involves nested loops.

1st loop: First, calculate your X, Y coordinates for the most recently added piece. Once you have that, set up 4 loops: one for the vertical, one for the horizontal, and one for each diagonal. If you're clever, you can make one loop body to test each of these directions. If you can't figure that out by your deadline, just write 4 discreet loops and hard code the directions.

2ns loop: Inside the body of the loop, you need to loop two more times: One for the positive direction, and one for the negative direction. Each of these will count the number of matching pieces that go in that direction.

3rd loop: Within these two directional loops, you'll need another loop that will increment (or decrement) the appropriate coordinate element (X or Y, or both, depending on which of the 4 directional loops we're in), continuing to loop while the current grid position equals the last placed piece and the coordinate is not out of bounds. Increment a counter in the body of this loop. Your 2nd loop which reverses the direction will continue to increment this same counter, so be sure to declare it outside of the 2nd loop and initialize it every time the body of the 1st loop starts. Because you initialize it every time the 1st loop runs, you need to check for a win (counter >= 4) at the end of each iteration of the 1st loop and break if a win is detected.
Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.

– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid


#10
computer0101

computer0101

    Newbie

  • Members
  • Pip
  • 7 posts
what do you mean by "calculate x and y"
is that the array number?

#11
gregwarner

gregwarner

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 853 posts
  • Location:Arkansas
You need to calculate X and Y from the array index. X and Y are merely Cartesian coordinates. If you have a simple method of converting your array index to Cartesian coordinates and back again, it will make looping over directions (up/down, left/right, diagonal) much easier. (Or you could just use a 2D array, which would be even easier. :) )

If you've had simple geometry lessons, you'll understand this concept. In your grid, the origin (0, 0) is in the upper left corner, at element #0. The X axis is increasing in the right-hand direction, and the Y axis is increasing in the downward direction.

So for example, if you have an array index: 6, how do you know what its position is on the grid? (And I don't mean just looking at the grid. How does the computer know its position?) You need a function that will map 6 => (1, 1), see what I mean? You also need the reverse function which maps (1, 1) => 6. (Of course, 2D arrays already do this calculation implicitly, so you never have to worry about anything other than an element's Cartesian coordinates. Far simpler!)
Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.

– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid


#12
computer0101

computer0101

    Newbie

  • Members
  • Pip
  • 7 posts
Ohhhh I get it now -___-
I already handed in the assignment an hour ago.
LOL

Thank you for all your help :D
It was greatly appreciated

Have a good day :)




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users