-1

I am writing the code for connect four game. I am using color as indicators for winners; however, "tie game" continously appears and no winners are identified even if there is a winner.

I am still learning java so I am not entirely confident with the language. Here is my code mainly.

 public static class MultiDraw extends JPanel  implements MouseListener {
        int startX = 10;
        int startY = 10;
        int cellWidth = 40;
        int turn = 2;
        int rows = 6;
        int cols = 7;
        boolean Go = true;
        Object winner;
        String playerOne = playernames(1);
        String playerTwo=playernames(2);
        Color c1 = new Color(255,0,0);
        Color c2 = new Color(0,255,0);
        Color[][] grid = new Color[rows][cols];
        Color winner_color;

        public MultiDraw(Dimension dimension) {
            setSize(dimension);
            setPreferredSize(dimension);
            addMouseListener(this);
            int x = 0;
            for (int row = 0; row < grid.length; row++) {
                for (int col = 0; col < grid[0].length; col++) {
                    grid[row][col] = new Color (255, 255, 255);
                }
            }

        }

        @Override
        public void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D)g;
            Dimension d = getSize();
            g2.setColor(new Color(0, 0, 0));
            g2.fillRect(0,0,d.width,d.height);
            startX = 0;
            startY = 0;

            for (int row = 0; row < grid.length; row++) {
                for (int col = 0; col < grid[0].length; col++) {
                    g2.setColor(grid[row][col]);
                    g2.fillOval(startX, startY, cellWidth, cellWidth);
                    startX = startX + cellWidth;

                }
                startX = 0;
                startY = startY +cellWidth;
            }
            g2.setColor(new Color(255, 255, 255));
            if (turn%2==0){
                g2.drawString(playerOne,400,20);

            }else{
                g2.drawString(playerTwo, 400, 20);
            }

        }

        public void mousePressed(MouseEvent e) {
            int x = e.getX();
            int y = e.getY();
            int xSpot = x/cellWidth;
            int ySpot = y/cellWidth;

            //play a turn
            //while (turn <= 42){
            ySpot= testForOpenSpot(xSpot);
            if(ySpot<0){
                System.out.println("Not a valid entry");
            }else{
                grid[ySpot][xSpot]= c2;

            if (turn%2==0){
                grid[ySpot][xSpot]= c1;
                checkWinner(c1, grid);
                checkWinner(c2, grid); 
            }else{
                grid[ySpot][xSpot]= c2;
                checkWinner(c1, grid);
                checkWinner(c2, grid);         
            }
            turn++;
            }
            repaint();
            print_player(winner_color, c1, c2);

        }

        public String playernames(int i){
                Scanner scan = new Scanner(System.in);
                System.out.println("Enter the name of the" + i + " player:");
                String playerOne = scan.nextLine();
                return playerOne;
        }
        public Color checkWinner(Color c, Color[][] grid){
               //check right and left 
                for(int row = 0; row<grid.length; row++){
                    for (int col = 0;col < grid[0].length - 3;col++){
                        if (grid[row][col].equals(c) && 
                            grid[row][col+1].equals(c)&&
                            grid[row][col+2].equals(c)&&
                            grid[row][col+3].equals(c)){
                                return c ;

                            }
                        }           
                }
                //check for 4 up and down
                for(int row = 0; row < grid.length - 3; row++){
                    for(int col = 0; col < grid[0].length; col++){
                        if (grid[row][col] == c &&
                            grid[row][col+1] == c &&
                            grid[row][col+2] == c &&
                            grid[row][col+3] == c){
                                return c;

                            }
                        }
                  }   
        //check upward diagonal
                for(int row = 3; row < grid.length; row++){
                    for(int col = 0; col < grid[0].length - 3; col++){
                        if (grid[row][col] == c   && 
                            grid[row-1][col+1] == c &&
                            grid[row-2][col+2] == c &&
                            grid[row-3][col+3] == c){
                                return c;
                            }
                        }
                    }
        //check downward diagonal
                for(int row = 0; row < grid.length - 3; row++){
                    for(int col = 0; col < grid[0].length - 3; col++){
                        if (grid[row][col].equals(c)   && 
                            grid[row+1][col+1].equals(c) &&
                            grid[row+2][col+2].equals(c) &&
                            grid[row+3][col+3].equals(c)){
                                return c;
                }
            }
        }
        return new Color(255,255,255);
        }

        public void print_player(Color winner_color, Color c1, Color c2){
              //determine if winner is color1(first player):
                winner_color = checkWinner(c1,grid);
                    //determine if winner is color2 (2nd player):
                winner_color = checkWinner(c2,grid);


                if (winner_color == c1){
                    System.out.println("Winner is first player");}       
                else if (winner_color == c2){
                    System.out.println("Winner is 2nd player");}
                else{
                    System.out.println("Tie game");
                    }
        }

        public int testForOpenSpot(int xSpot){
            int ySpot = rows-1;
            while (!(grid[ySpot][xSpot].equals(new Color(255,255,255))|| ySpot<0)){
                ySpot--;
            }
            return ySpot;
        }

I keep on getting this error while running the code: Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 6

1 Answers1

0

One of the loops for your array is going out of bounds. Step through your code and see where it is stepping out of bounds. This error can easily be fixed by stepping through your code and seeing when it happens.

Aiyuni
  • 780
  • 5
  • 15
  • I fixed one of the for loops that was stepping out of bounds. It fixed the problem of the outofbound error. However, the problem of not identifying a winner at the end is still present. Do you have any suggestions? – hend alzeer Aug 02 '19 at 00:22
  • Can you please post your updated code if you've made corrections? – caladeve Aug 02 '19 at 01:49
  • You may also want to read up on `equals()` vs `==` ([see here](https://stackoverflow.com/questions/7520432/what-is-the-difference-between-and-equals-in-java)) as you are comparing the `Color` differently for diagonal and left/right. – caladeve Aug 02 '19 at 01:53
  • I personally am not a fan of your logic for checking win, especially for the diagonal checks as there might be edge cases that you are not handling. You can see this code for an example for checking win: https://github.com/aiyuni/Connect-Four-AI/blob/master/src/connectFourAI/Game.java – Aiyuni Aug 02 '19 at 02:01
  • I agree with @Aiyuni here, there are better and easier solutions to this. Consider taking a look at [algorithm to check a connect four field](https://stackoverflow.com/questions/7033165/algorithm-to-check-a-connect-four-field?noredirect=1&lq=1) if changing the win algorithm is an option. – TilS Aug 02 '19 at 07:59