import java.util.Scanner; public class Connect4 { public static void main(String[] args) { Scanner reader = new Scanner(System.in); char board[][] = new char[6][7]; int spacesLeft[][] = new int[1][7]; int turn=1; int selection; char playerSymbol; String winner = ""; //Declares board and sets all values to a space (placeholder) for(int x=0;x 7 || selection < 0) System.out.println("Invalid column selection, try again."); else if(spacesLeft[0][selection-1] == -1) System.out.println("Column is full, try again."); } while(selection > 7 || selection < 0 || spacesLeft[0][selection-1] == -1); //Replace the space with the symbol & subtract an open space from that column. board[spacesLeft[0][selection-1]] [selection-1] = playerSymbol; spacesLeft[0][selection-1] = spacesLeft[0][selection-1]-1; //Check for a win if(getWinner(board)) winner = ""+turn; //Switch the turns if (turn == 1) {turn = 2;} else { turn = 1; } }while(winner.equals("")); } /** * Helper function to see if there are any winners. * Checks the / diagonal. */ private boolean checkDiag1(int x, int y, char grid[][]) { int i; if((x > 3) || (y > 2)) return false; int player = grid[x][y]; int count = 1; for(i = 1;i < 4;i++) { if(grid[x+i][y+i] == player) count++; else break; } return (count==4); } /* * Helper function to see if there are any winners. * Checks the \ diagonal. */ private boolean checkDiag2(int x, int y, char grid[][]) { int i; if((x < 3) || (y > 2)) return false; int player = grid[x][y]; int count = 1; for(i = 1;i < 4;i++) { if(grid[x-i][y+i] == player) count++; else break; } return (count==4); } /* * Helper function to see if there are any winners. * Checks horizontally. */ private boolean checkHorizontal( int x, int y, char grid[][]) { int i; if(x > 3) return false; int player = grid[x][y]; int count = 1; for(i = (x+1);i < (x+4);i++) { if( grid[i][y] == player ) count++; else break; } return (count==4); } /* * Helper function to see if there are any winners. * Checks vertically. */ private boolean checkVertical(int x, int y, char grid[][]) { int i; if(y > 2) return false; int player = grid[x][y]; int count = 1; for(i = (y+1);i < (y+4);i++) { if(grid[x][i] == player) count++; else break; } return (count==4); } /* * Determines if anyone has won the game in the Board's current state. */ public int getWinner(char grid[][]) { int x, y; int winner = 0; for(y = 0; y < 6;y++) { for(x = 0; x < 7;x++) { if(grid[x][y] != 0) { if(checkHorizontal(x,y,grid) || checkVertical(x,y,grid) || checkDiag1(x,y,grid) || checkDiag2(x,y,grid)) { winner = grid[x][y]; break; } } } if(winner != 0) break; } if(winner == 0) { for(x = 0; x < 7; x++) { if(grid[x][5] == 0) { winner = -1; break; } } } return winner; } }