import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.Frame; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; public class Connect4GameApp extends Frame implements MouseListener { Board board; Player[] player; String message="Turn No. 1 Red's Move"; String comment="No Comment"; String score="New Game"; int turn=1; private final int left=20; private final int top=80; private final int boxSize=60; public Connect4GameApp() { super("Connect 4"); setSize(500,500); player = new Player[2]; player[0]=new Player("Red", Color.RED); player[0].setRobot(false); player[1]= new Player("Black", Color.BLACK); player[1].setRobot(false); board= new Board(); board.setCellSize(boxSize); addMouseListener(this); this.addWindowListener(new WindowListener() { public void windowClosing(WindowEvent e) {System.exit(0);} public void windowClosed(WindowEvent e) {} public void windowOpened(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} }); } public void paint(Graphics g) { g.setColor(Color.white); g.fillRect(0, 0, 500, 500); g.setColor(Color.black); g.drawString("Connect 4 Game", 20, 20); g.setColor(Color.blue); g.drawString("click to see next turn", 20, 40); g.drawString(message , left, 65); g.drawString(comment , left, 490); g.drawString(score , left, 470); board.draw(g, left, top); } public boolean gameOver(){ return (board.legalMoves().size()==0 || board.hMax()>3 || board.vMax()>3 || board.dMax()>3); } public static void main(String[] args) { Connect4GameApp app= new Connect4GameApp(); app.setVisible(true); } public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { int click=e.getX(); click-=left; int selectedCol=click/boxSize; if (selectedCol>6) selectedCol=6; if (!gameOver()){ turn++; message="Turn No. "+turn+" "; Color c=player[turn%2].getColor(); if (player[turn%2].isRobot()){ selectedCol=player[turn%2].getMove(board.legalMoves()); board.add(new Piece(c, board.columnTop(selectedCol) ,selectedCol)); }else{ if(board.legalMoves().contains(selectedCol)){ board.add(new Piece(c, board.columnTop(selectedCol) ,selectedCol)); }else{ message+="Illegal move - still "; turn--; } } if (gameOver()) message=player[turn%2].getName()+" WON!"; else message+=player[(turn-1)%2].getName()+"'s move"; } else{ message="Game Over"; } comment="Last Selected Column: "+selectedCol+" (top is "+board.columnTop(selectedCol); comment+= ") legal Moves: "+board.legalMoves(); score="horiz Max="+board.hMax()+" vert max="+board.vMax()+" diag max="+board.dMax(); repaint(); } }