Question

Hello I am having trouble with a connectFour java program. this issue is in my findLocalWinner...

Hello I am having trouble with a connectFour java program. this issue is in my findLocalWinner method, it declares a winner for horizontal wins, but not for vertical. if anyone can see what im doing wrong.

public class ConnectFour {

    /** Number of columns on the board. */
    public static final int COLUMNS = 7;

    /** Number of rows on the board. */
    public static final int ROWS = 6;
    
    /** Character for computer player's pieces */
    public static final char COMPUTER = 'X';

    /** Character for human player's pieces */
    public static final char HUMAN = 'O';

    /** Character for blank spaces. */
    public static final char NONE = '.';

    public static void dropPiece(char[][] board, char player, int column) {
        // TODO You have to write this.
    for(int i=0; i<ROWS;i++) {
//loop over all rows
    if (board[i][column] == NONE) {
// checks if spot on board is empty
    board[i][column] = player;  //if empty make that spot into player.
    break;

    }
    }
   
    }
    
    public static boolean isFull(char[][] board) {
        // TODO You have to write this.
    for (int j = 0; j < COLUMNS; j++ ) {
    if (board[ROWS-1][j] == NONE) {
    return false;
    }
    }  return true; // emplies board is full
   
   
    }
   
    public static boolean isLegalMove(char[][] board, int column) {
    
    for(int i=0; i<ROWS;i++) { //loop over all rows
     if (column >= 0 && column < COLUMNS) { //makes sure column is not out of bounds
      if (board[i][column] == NONE) {  //makes sure spot on board is empty
       return true;
    }
     }
        
    }
       return false;
    }
    public static char getOpposite(char player) {
        // TODO You have to write this.
    if (player == HUMAN) {        //if human just moved, its computers next move
    return COMPUTER;
    } 
    return HUMAN;        //if computer just moved its human next move
      
        }
    public static char findLocalWinner(char[][] board, int r, int c,
            int rowOffset, int colOffset) {
// TODO You have to write this.
        char player = board[r][c];               //player at that index
        //int counter = 0;
        if(player == NONE || c >= (COLUMNS - 3) ) {  //if player at r, c is NONE, also checks if win is possible
            player = NONE;
        //    return player;
        }
        
        if(rowOffset == 0 && colOffset != 0 && (c < COLUMNS || c > 0 )) {    //checks horizontal 
            for(int i = 0; i < 4 ; i++) {
                if(player == board[r][c+(1*colOffset)] && player == board[r][c+(2*colOffset)] &&player == board[r][c+(3*colOffset)]) { //checks for connect 4
                    return player;        //player is winner 
                }else {
                    player = NONE;        //no winner yet 
                }
            }
        }
        
        if(rowOffset != 0 && colOffset == 0 && (r < ROWS || r >0)) {        //checks vertical 
            for(int i = 0; i < 4 ; i++) {
                if(player == board[r+(1* rowOffset)][c] && player == board[r+(2*rowOffset)][c] &&player == board[r+(3*rowOffset)][c]) {
                    return player;
                }else {
                    player = NONE;
                }
            }
        if(rowOffset != 0 && colOffset != 0) {        //checks diagonal 
            for(int i = 0; i < 4 ; i++) {
                if(player == board[r+(1*rowOffset)][c+(1*colOffset)] && player == board[r+(2*rowOffset)][c+(2*colOffset)] &&player == board[r+(3*rowOffset)][c+(3*colOffset)]) {
                    return player;
                }else {
                    player = NONE;
                }
            }
        }
        }
            return player;
        }
    

    public static char findWinner(char[][] board) {
        // TODO You have to write this.
        // HINT: You should call the findLocalWinner method to help you

    char Winner = NONE;
    for(int row = 0; row < ROWS-3; row++) {  //loops over  rows
      for(int col = 0; col < COLUMNS-3; col++) {  //loops over  columns
    if(Winner  == NONE) {    //makes sure winner is NONE unless it finds human or comp
    Winner = findLocalWinner(board,row,col,0,1); //checks winner for horizontal
    }else if(Winner == NONE) {
    Winner = findLocalWinner(board,row,col,1,0); // checks winner for vertical 
    }else if(Winner == NONE) {
    Winner = findLocalWinner(board,row,col,1,1); // checks winner for diagonal 
    }else if(Winner == NONE) {
    Winner = findLocalWinner(board,row,col,-1,1); // checks winner for diagonal in downward direction
    }
    }
    }
        return Winner;
    }
    
    public static int bestMoveForComputer(char[][] board, int maxDepth) {
        // TODO You have to write this.
        // Hint: this will be similar to maxScoreForComputer
    int bestCol = -1;// (makes unbeatable AI)
    int bestResult = -20;
    for(int col= 0; col<COLUMNS; col++){
    if(isLegalMove(board,col)){
    dropPiece(board,COMPUTER,col);
    int result = minScoreForHuman(board,maxDepth,0);
        undoDrop(board,col);
    if(result >= bestResult){
    bestResult = result;
    bestCol = col;
    } 
    } 
    }
    return bestCol;
    }

    public static int maxScoreForComputer(char[][] board, int maxDepth, int depth) {
        // TODO You have to write this.
        // Hint: this will be similar to minScoreForHuman
    char winner = findWinner(board);
        if (winner == HUMAN) {
            
            return -10;
        } else if (winner == COMPUTER) {
           
            return 10;
        } else if (isFull(board) || (depth == maxDepth)) {
           
            return 0;
        } else {
            
            int bestResult = -20;

           
            for (int c = 0; c < COLUMNS; c++) {
                if (isLegalMove(board, c)) {
                    
                    dropPiece(board, COMPUTER, c);
                    
                    int result = maxScoreForComputer(board, maxDepth, depth +1);
                   
                    undoDrop(board, c);

                    if (result <= bestResult) {
                        
                        bestResult = result;
                    }
                }
            }
            return bestResult;
        }
    }
    public static int minScoreForHuman(char[][] board, int maxDepth, int depth) {
        char winner = findWinner(board);
        if (winner == COMPUTER) {
           
            return 10;
        } else if (winner == HUMAN) {
            
            return -10;
        } else if (isFull(board) || (depth == maxDepth)) {
            
            return 0;
        } else {
            
            int bestResult = 20;
            for (int c = 0; c < COLUMNS; c++) {
                if (isLegalMove(board, c)) {
                    
                    dropPiece(board, HUMAN, c);
                    
                    int result = maxScoreForComputer(board, maxDepth, depth + 1);
                    
                    undoDrop(board, c);

                    if (result <= bestResult) {
                       
                        bestResult = result;
                    }
                }
            }
            return bestResult;
        }
    }


    public static void undoDrop(char[][] board, int column) {
        // We'll start at the top and loop down the column until we
        // find a row with a piece in it. 
        int row = ROWS - 1;
        while(board[row][column] == NONE && row > 0) {
            row--;
        }

        // Set the top row that had a piece to empty again.
        board[row][column] = NONE;
    }

    /** Creates board array and starts game GUI. */
    public static void main(String[] args) {
        // create array for game board
        char[][] board = new char[ROWS][COLUMNS];
        // fill board with empty spaces
        for(int row = 0; row < ROWS; row++) {
            for (int col = 0; col < COLUMNS; col++) {
                board[row][col] = NONE;
            }
        }
      //ConnectFourGUI.showGUI(board, HUMAN, 5);
    }

}
0 0
Add a comment Improve this question Transcribed image text
Answer #1
        public static char findLocalWinner(char[][] board, int r, int c, int rowOffset, int colOffset) {
                // TODO You have to write this.
                char player = board[r][c]; // player at that index
                
// remove below condition completely
                // int counter = 0;
                // if (player == NONE || c >= (COLUMNS - 3)) { // if player at r, c is NONE, also checks if win is possible
                        // player = NONE;
                        // return player;
                }

                if (rowOffset == 0 && colOffset != 0 && (c < COLUMNS - 3 && c >= 0)) { // checks horizontal
                        for (int i = 0; i < 4; i++) {
                                if (player == board[r][c + (1 * colOffset)] && player == board[r][c + (2 * colOffset)]
                                                && player == board[r][c + (3 * colOffset)]) { // checks for connect 4
                                        return player; // player is winner
                                } else {
                                        player = NONE; // no winner yet
                                }
                        }
                }

                if (rowOffset != 0 && colOffset == 0 && (r < ROWS - 3 && r >= 0)) { // checks vertical
                        for (int i = 0; i < 4; i++) {
                                if (player == board[r + (1 * rowOffset)][c] && player == board[r + (2 * rowOffset)][c]
                                                && player == board[r + (3 * rowOffset)][c]) {
                                        return player;
                                } else {
                                        player = NONE;
                                }
                        }
                        if (rowOffset != 0 && colOffset != 0) { // checks diagonal
                                for (int i = 0; i < 4; i++) {
                                        if (player == board[r + (1 * rowOffset)][c + (1 * colOffset)]
                                                        && player == board[r + (2 * rowOffset)][c + (2 * colOffset)]
                                                        && player == board[r + (3 * rowOffset)][c + (3 * colOffset)]) {
                                                return player;
                                        } else {
                                                player = NONE;
                                        }
                                }
                        }
                }
                return player;
        }

highlighted my changes.. Code should now work fine for horizontal and vertical groups .

Add a comment
Know the answer?
Add Answer to:
Hello I am having trouble with a connectFour java program. this issue is in my findLocalWinner...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • This is my code for a TicTacToe game. However, I don't know how to write JUnit...

    This is my code for a TicTacToe game. However, I don't know how to write JUnit tests. Please help me with my JUnit Tests. I will post below what I have so far. package cs145TicTacToe; import java.util.Scanner; /** * A multiplayer Tic Tac Toe game */ public class TicTacToe {    private char currentPlayer;    private char[][] board;    private char winner;       /**    * Default constructor    * Initializes the board to be 3 by 3 and...

  • Hello, I am currently taking a Foundations of Programming course where we are learning the basics of Java. I am struggli...

    Hello, I am currently taking a Foundations of Programming course where we are learning the basics of Java. I am struggling with a part of a question assigned by the professor. He gave us this code to fill in: import java.util.Arrays; import java.util.Random; public class RobotGo {     public static Random r = new Random(58);     public static void main(String[] args) {         char[][] currentBoard = createRandomObstacle(createBoard(10, 20), 100);         displayBoard(startNavigation(currentBoard))     }     public static int[] getRandomCoordinate(int maxY, int maxX) {         int[] coor = new...

  • This is my code for my game called Reversi, I need to you to make the...

    This is my code for my game called Reversi, I need to you to make the Tester program that will run and complete the game. Below is my code, please add comments and Javadoc. Thank you. public class Cell { // Displays 'B' for the black disk player. public static final char BLACK = 'B'; // Displays 'W' for the white disk player. public static final char WHITE = 'W'; // Displays '*' for the possible moves available. public static...

  • Hi I need help with a java program that I need to create a Airline Reservation...

    Hi I need help with a java program that I need to create a Airline Reservation System I already finish it but it doesnt work can someone please help me I would be delighted it doesnt show the available seats when running the program and I need it to run until someone says no for booking a seat and if they want to cancel a seat it should ask the user to cancel a seat or continue booking also it...

  • Please I need your help I have the code below but I need to add one...

    Please I need your help I have the code below but I need to add one thing, after player choose "No" to not play the game again, Add a HELP button or page that displays your name, the rules of the game and the month/day/year when you finished the implementation. import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.swing.*; import javax.swing.event.*; import java.util.Random; public class TicTacToe extends JFrame implements ChangeListener, ActionListener { private JSlider slider; private JButton oButton, xButton; private Board...

  • I just need a help in replacing player 2 and to make it unbeatable here is my code: #include<i...

    I just need a help in replacing player 2 and to make it unbeatable here is my code: #include<iostream> using namespace std; const int ROWS=3; const int COLS=3; void fillBoard(char [][3]); void showBoard(char [][3]); void getChoice(char [][3],bool); bool gameOver(char [][3]); int main() { char board[ROWS][COLS]; bool playerToggle=false; fillBoard(board); showBoard(board); while(!gameOver(board)) { getChoice(board,playerToggle); showBoard(board); playerToggle=!playerToggle; } return 1; } void fillBoard(char board[][3]) { for(int i=0;i<ROWS;i++) for(int j=0;j<COLS;j++) board[i][j]='*'; } void showBoard(char board[][3]) { cout<<" 1 2 3"<<endl; for(int i=0;i<ROWS;i++) { cout<<(i+1)<<"...

  • JAVA TIC TAC TOE - please help me correct my code Write a program that will...

    JAVA TIC TAC TOE - please help me correct my code Write a program that will allow two players to play a game of TIC TAC TOE. When the program starts, it will display a tic tac toe board as below |    1       |   2        |   3 |    4       |   5        |   6                 |    7      |   8        |   9 The program will assign X to Player 1, and O to Player    The program will ask Player 1, to...

  • JAVA Only Help on the sections that say Student provide code. The student Provide code has...

    JAVA Only Help on the sections that say Student provide code. The student Provide code has comments that i put to state what i need help with. import java.util.Scanner; public class TicTacToe {     private final int BOARDSIZE = 3; // size of the board     private enum Status { WIN, DRAW, CONTINUE }; // game states     private char[][] board; // board representation     private boolean firstPlayer; // whether it's player 1's move     private boolean gameOver; // whether...

  • JAVA JAR HELP...ASAP I have the code that i need for my game Connect 4, but...

    JAVA JAR HELP...ASAP I have the code that i need for my game Connect 4, but i need to create a jar file . the instructions are below. It has to pass some parameters. I am really confused on doing so.l I dont know what to do next. Can someone help me and give detailed descritiopm opn how you ran the jar file in CMD import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Connect4 {               ...

  • I am having trouble figuring out why my program will not make any columns, just rows....

    I am having trouble figuring out why my program will not make any columns, just rows. I need to display a square. The instructions are provided below. (This for my C++ class) Write a program that displays a square. Ask the user for the square’s size. Only accept positive integer numbers (meaning choose a data type that holds positive integer values). The size the user gives you will determine the length and width of the square. The program should then...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT