Sign in to follow this  
kyokai

[java] Help with Connect 4

Recommended Posts

I've been teaching myself Java for about 4 months now, and I'm stuck. I'm trying to write connect 4 using the console, and instead of a player vs. a computer, I want it to be able to read in a text file and print out the results based on the text file. The input from the text file is as follows 1 0 4 5 3 6 Where the numbers equal which column the piece belongs in. I've gotten to the point where I have read in the file, but when I try to print out the results of the game, I can't get the pieces to stack up properly. Here's what I have so far...
import java.io.*;
import java.util.*;

public class Connect4Processor {
    public Connect4Processor() {
    }

    ArrayList moves = new ArrayList();
    //Ints repsresenting the height of each of the columns
    int c0 = 5;
    int c1 = 5;
    int c2 = 5;
    int c3 = 5;
    int c4 = 5;
    int c5 = 5;
    int c6 = 5;


    public void startup() throws FileNotFoundException {
        Scanner in = new Scanner(new File("test.txt"));
        Scanner in2 = new Scanner(new File("test2.txt"));
        Scanner in3 = new Scanner(new File("test3.txt"));
        System.out.println(
                "Please insert the name of the file you would like to input");

        while (in.hasNext()) {
            moves.add(in.next());
        }
        in.close();
        in2.close();
        in3.close();
        // System.out.println("0123456");//prints out the game board

    }

    public void board() {
        System.out.println("");
        System.out.println("0123456");

    }

    public void move() throws FileNotFoundException {
        Connect4Processor c4p = new Connect4Processor();
        for (int i = 0; i < moves.size(); i++) {
            //System.out.print("" + i);
            if (moves.get(i).equals("0")) {
                c4p.board();
                for (int j = 0; j < c0; j++) {
                    System.out.println("");
                }

                System.out.println("0");
                c0--;
            }
            if (moves.get(i).equals("1")) {
                c4p.board();
                for (int j = 0; j < c1; j++) {
                    System.out.println("");

                }

                System.out.println(" 1");
                c1--;

            }
            if (moves.get(i).equals("2")) {
                c4p.board();
                for (int j = 0; j < c2; j++) {
                    System.out.println("");

                }

                System.out.println("  2");
                c2--;

            }
            if (moves.get(i).equals("3")) {
                c4p.board();
                for (int j = 0; j < c3; j++) {
                    System.out.println("");

                }

                System.out.println("   3");
                c3--;

            }
            if (moves.get(i).equals("4")) {
                c4p.board();
                for (int j = 0; j < c4; j++) {
                    System.out.println("");

                }

                System.out.println("    4");
                c4--;

            }
            if (moves.get(i).equals("5")) {
                c4p.board();
                for (int j = 0; j < c5; j++) {
                    System.out.println("");

                }

                System.out.println("     5");
                c5--;

            }
            if (moves.get(i).equals("6")) {
                c4p.board();
                for (int j = 0; j < c6; j++) {

                    System.out.println();

                }
                c6--;

                System.out.println("      6");
            }

        }
        System.out.println(moves);
        System.out.println("" + c0 + "" + c1 + "" + c2 + "" + c3 + "" + c4 + "" +
                           c5 + "" + c6);

    }

    public static void main(String[] args) throws FileNotFoundException {
        Connect4Processor c4p = new Connect4Processor();
        c4p.startup();
        c4p.move();
    }
}

test.txt 0 0 0 1 1 1 2 2 4 3 3 5 6 6 5 6 4 6 3 6 Thanks much [Edited by - kyokai on June 10, 2007 5:20:24 PM]

Share this post


Link to post
Share on other sites
Where are you storing the actual contents of your game board? You can't determine who wins if you only store the heights.

Declaring 7 different integer variables for the heights is bad. Have you learned about arrays yet?

Share this post


Link to post
Share on other sites
Well I'm looking through your code and I see some things that could be done much easier.

Your whole block of if statements in your move method would be much better served with a switch statement. Like this:


int temp = moves.get(i)

switch(temp)
{
case 0:
c4p.board();
for (int j = 0; j < c0; j++) {
System.out.println("");
}
System.out.println("0");
c0--;
break;
case 1:
c4p.board();
for (int j = 0; j < c1; j++) {
System.out.println("");
}
System.out.println(" 1");
c1--;
break;
case 2:
c4p.board();
for (int j = 0; j < c2; j++) {
System.out.println("");
}
System.out.println(" 2");
c2--;
break;
case 3:
c4p.board();
for (int j = 0; j < c3; j++) {
System.out.println("");
}
System.out.println(" 3");
c3--;
break;
case 4:
c4p.board();
for (int j = 0; j < c4; j++) {
System.out.println("");
}
System.out.println(" 4");
c4--;
break;
case 5:
c4p.board();
for (int j = 0; j < c5; j++) {
System.out.println("");
}
System.out.println(" 5");
c5--;
break;
case 6:
c4p.board();
for (int j = 0; j < c6; j++) {
System.out.println();
}
c6--;
System.out.println(" 6");
break;
default:
break;


and now thats a little bit more organized

also, your move method really isnt a move method, its more of a playTheGame method . . . you should have your move method be something like:
private void move(int column)
{
... code to move stuff
}

the actual job of doing all the moves should be in your main method, which should call the move method a number of times. Thats just good organization, at least in my opinion.

I realize I didnt solve all your problems, but those suggestions will at least make your code easier to use and more logical.

Share this post


Link to post
Share on other sites
Well, there are a couple of problems with the way you are trying to do things. I have made some modifications to your code and hopefully was successful in keeping what you were trying to do. So here is my version.

/**
* File: Connect4Processor.java
*
* Version 1.0
*
* Revisions:
* 1.1 Initial Revision from Gamedev.net post
* 1.2 Fixed problems with output and board storage.
*/


package gdnetfixes;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

/**
* A connect 4 game that uses input files to specify a players sequence of moves
* extended to multiple players current only one player and the input file is
* hard-coded to be named test.txt and must be in the same directory as this
* game is being run from.
*/

public class Connect4Processor {

//all the moves to be made by a particular player.
private ArrayList moves = new ArrayList();

//Two dimensional array representing the board.
private int board[][] = new int[6][5]; //columns by rows

/**
* Empty Constructor, does nothing.
*/

public Connect4Processor() {
//empty constructor. Could call startup().
}

/**
* Creates and initializes the game as well as reads in all the moves
* by each of the players.
*
* @throws IOException Thrown if there is an error reading the input files.
*/

public void startup() throws IOException {
BufferedReader in = new BufferedReader(
new FileReader(new File("test.txt")) );
//Scanner in2 = new Scanner(new File("test2.txt"));
//Scanner in3 = new Scanner(new File("test3.txt"));
System.out.println(
"Please insert the name of the file you would like to input");

String strln = null;
while ( (strln = in.readLine()) != null ) {
moves.add(strln);
}
in.close();
//in2.close();
//in3.close();
// System.out.println("0123456");//prints out the game board
initBoard();
}

/**
* We need to make sure that all locations on the board are set to -1 in
* order to check for empty spaces when a move occurs.
*/

public void initBoard() {
for( int c = 0; c < board.length; c++ ) {
for( int r = 0; r < board[c].length; r++ ) {
board[c][r] = -1; //make sure all numbers are set to -1
}
}
}

/**
* It is easier to display a board if we have a 2D array. We simply iterate
* through each rows and print the integer or if it is empty (or equals -1)
* then we want to print a blankspace.
*/

public void displayBoard() {
System.out.println("");
System.out.println("0123456");

//loop through the board by rows.
for( int r = 0; r < board[0].length; r++ ) {
for( int c = 0; c < board.length; c++ ) {
if( board[c][r] == -1 ) {
System.out.print(" ");
}else{
System.out.print(board[c][r]);
}
}

//the last column is reached so move to the next line.
System.out.print("\n");
}

System.out.println();
}

/**
* This method loops through each move and plays the move. This method
* should be responsible for maintaining players and checking to see if
* the game is in a win state if so then it should display a notice of who
* one and exit the game loop. Or simply exit when all moves have been
* preformed.
*/

public void playGame() {

int player = 1;

for (int i = 0; i < moves.size(); i++) {
//make the next move
int move = Integer.parseInt((String) moves.get(i));

if( !move( move, player ) ) {
//the column was full
System.out.println("Column " + move + " is full!");
}

//now print the board.
displayBoard();
}

System.out.println("Game Over!");
}

/**
* Places a players piece on the game board by checking all the pieces in
* the column starting with the bottom most piece and then places a piece
* with the players number in the first empty location.
*
* @param column The column the player wishes to slide a piece to.
* @param player The number of the player who is currently moving.
*/

public boolean move( int column, int player ) {

//move is the column number so we know that now find next empty row
//iterating up from the bottom of the board.
for( int i = board[column].length-1; i >= 0; i--) {

//if the spot on the board is empty
if( board[column][i] == -1 ) {
// you can place a piece
board[column][i] = player;
return true;
}
}

return false; //the column is full.
}

/**
* The main entry point for the game. This method recieves command line
* arguments in the array of strings args. Creates a new Connect4Processor
* and initializes it and plays the game.
*
* @param args Variable array of command line arguments
* @throws IOException Thrown by Connect4Processor if a file error occurs.
*/

public static void main(String[] args) throws IOException {
Connect4Processor c4p = new Connect4Processor();
c4p.startup();
c4p.playGame();
}

} //end Connect4Processor class



What about the last move?
One of the main problems with your displaying code is that you don't have a way of knowing the last state of the game so then you don't know what to print out once you do.

What about different Players?
The integers for the height of each column was an interesting idea but how do you know which player placed a piece there?

Some Advice!
Usually with a game that involves a 2 dimensional board you want to store that board, if reasonably sized, in some type of data structure. I used a primitive array you could use a ArrayList or perhaps a HashMap or LinkedList.

Moving Forward
From this point forward you might want to consider a two player game and make the loop in the playGame method switch between each player. Next you might consider working on the algorithm that will determine if a move connects four.

Good luck and if you have any questions about my code or run into further problems please post.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this