
/**************************************************************
** cspp51037^M
** lab#2
** ReversiClient.java
** Dan Rocco
** 04/28/02
***************************************************************/

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.util.*;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.NotBoundException;
import java.net.MalformedURLException;
import java.rmi.server.*;

public class ReversiClient1 extends JApplet
             implements  ActionListener, PlayerInter 
{
   private JTextField id;
   private JTextArea display;
   private JPanel boardPanel, panel2, panel3;
   private JButton b1, b2, b3;
   private Square board[][], currentSquare;
   private char s_board[][];
   private DataInputStream input;
   private DataOutputStream output;
   private char myMark;
   private boolean myTurn;
   private int playerID;
   private int numPlayers = 0;
   Reversi game;

   JFrame frame = new JFrame("Reversi");

   // Set up user-interface and board
   public void init()  
   {
       Container cp = getContentPane();
      // frame.getContentPane().add(cp);
      FlowLayout appletLayout = new FlowLayout(FlowLayout.CENTER, 10,10);
      cp.setLayout(appletLayout);
       
       frame.addWindowListener(new WindowAdapter() {            
                  public void windowClosed(WindowEvent e) {
                      System.out.println("-------Im dead------- ");
                      killed(); 
                  }                            
              });    

      boardPanel = new JPanel();
      GridLayout layout1 = new GridLayout( 8, 8, 0, 0 );
      boardPanel.setLayout( layout1 );

      board = new Square[ 8 ][ 8 ];

      frame.getContentPane().add(cp.add(boardPanel));

      id = new JTextField();
      id.setEditable( false );

      cp.add(id, BorderLayout.NORTH );

      panel2 = new JPanel();
      panel2.add( boardPanel, BorderLayout.NORTH );
      cp.add(panel2, BorderLayout.NORTH );

       for ( int row = 0; row < board.length; row++ )
        {
           for ( int col = 0;
              col < board[ row ].length; col++ ) {
              board[ row ][ col ] =
              new Square( ' ', row * 8 + col );
              board[ row ][ col ].addMouseListener(
                 new SquareListener(
                 this, board[ row ][ col ] ) );

              boardPanel.add( board[ row ][ col ] );
	           }
	        }
             board[ 3 ][ 3 ].setMark('X' );
             board[ 3 ][ 3 ].repaint();
             board[ 3 ][ 4 ].setMark('O' );
             board[ 3 ][ 4 ].repaint();
             board[ 4 ][ 3 ].setMark('O' );
             board[ 4 ][ 3 ].repaint();
             board[ 4 ][ 4 ].setMark('X' );
             board[ 4 ][ 4 ].repaint();


      panel3 = new JPanel();

      b1=new JButton("Concede");
      panel3.add(b1);
      b1.addActionListener(this);


      b2=new JButton("Skip Turn");
      panel3.add(b2);
      b2.addActionListener(this);

      b3=new JButton("New Game");
      panel3.add(b3);
      b3.addActionListener(this);
      cp.setSize(3,30);
      cp.add(panel3, BorderLayout.CENTER );

      display = new JTextArea( 6, 25 );
      display.setEditable( false );
      cp.add(new JScrollPane( display ),
                    BorderLayout.SOUTH);
      setBackground(Color.green);

try {                                                                      
     UnicastRemoteObject.exportObject( (PlayerInter) this );                   
     game = (Reversi) Naming.lookup                                            
           ("rmi://localhost:1884/reversi_game");                              
      playerID = game.register( (PlayerInter) this);                           
       if (playerID  <= 1 ){                                                  
       if (playerID == 0){
          myMark = 'X';
          display.append("connection established, valid player \n");           
          display.append("I'm player " +  myMark + "\n");                      
          } 
       if (playerID == 1){
          myMark = 'O';
                                                                        
           display.append("connection established, valid player \n");         
           display.append("I'm player " +                                    
                          myMark + "\n");      
           }         
        }                                                          
         else{                                                                 
             display.append("two people already playing, can only watch");     
        }                                                                      
        myTurn = (playerID == 0 ? true : false);                               
                                                                               
                                                                              
       } 
       catch(Exception e)                                                     
       {                                                                       
               System.out.println(e);                                          
       }                                              

System.out.println("--done gui--");

   }




public void actionPerformed(ActionEvent ae) {

	String label = ae.getActionCommand();
        Object source = ae.getSource();

	if(source == this.b1){
	    if (playerID < 2) 
             try{
             game.restartGame();
             s_board = game.getBoard();                                      
             this.drawBoard(s_board);
             game.tooglePlayer();
             s_board = game.getBoard();                                       
             this.drawBoard(s_board);  
             }                                                                
             catch(Exception e){                                               
             System.out.println(e);                                            
             }  
	    // myTurn = false;
         }

	if(source == this.b2){
	    if  (playerID < 2)
             try{
             game.tooglePlayer();
                                                   
             }
             catch(Exception e){                                               
             System.out.println(e);                                            
             } 
 	     myTurn = false;
        }

        if(source == this.b3){                                                 
        if (playerID < 2)  
             try{                                                          
             game.restartGame();  
             s_board = game.getBoard();                                       
             this.drawBoard(s_board);
             game.tooglePlayer();
             s_board = game.getBoard();                                       
             this.drawBoard(s_board);   
             }
             catch(Exception e){
             System.out.println(e);
             }                                             
       //      myTurn = false;                                                  
        }           
}

   public void otherPlayerMoved(){
        synchronized(this){
            try{                   
            s_board = game.getBoard();  
            }
            catch(Exception e){}                                        
            this.drawBoard(s_board);    
            notify();
            try{                                                                
            s_board = game.getBoard();                                          
            } 
             catch(Exception e){}  
             this.drawBoard(s_board);  
             display.append("Your move \n");   
        }
    }


   public void testit(int loc){
   boolean tested = false;
   try {  
       tested = game.validMove(loc,playerID); 
         if (!tested){ 
          s_board = game.getBoard();                                          
          this.drawBoard(s_board);
         }  
       }
       catch ( Exception ie ) {                                             
              ie.printStackTrace();                                            
       }                                                                                               
        if (tested){                                                         
            board[ loc/8 ][ loc%8 ].setMark('X' );                            
            board[ loc/8 ][ loc%8 ].repaint();
            try {
            s_board = game.getBoard();
            this.drawBoard(s_board);
            }
            catch(Exception eo)
            { 
               System.out.println(eo);
            }
              this.drawBoard(s_board); 
            try{
                game.tooglePlayer();
            }catch(Exception e){}                                       
            this.drawBoard(s_board);   

            try {
            game.tooglePlayer();
            s_board = game.getBoard();
            this.drawBoard(s_board); 
            myTurn=true;
            }
            catch(Exception eo)
            { 
               System.out.println(eo);
               System.out.println("exception in get board");
            }
             this.drawBoard(s_board);
            try {                                                               
            game.tooglePlayer();                                                
            s_board = game.getBoard();                                          
            this.drawBoard(s_board);
            countThem();
            display.append("Please wait for other player to move \n");
            myTurn=false;    
            }                                                                   
            catch(Exception eo)                                                 
            {                                                                   
               System.out.println(eo);                                          
               System.out.println("exception in get board");                    
            }                                                                   
             this.drawBoard(s_board); 
             if (playerID >1){           
              for(int p = 2; p <= numPlayers; p++){
               try {
                    s_board = game.getBoard();                                          
            this.drawBoard(s_board); 
            repaint();   
       //      myTurn=false;                                        
            }         
            catch(Exception eo)                                                 
            {                                                                   
               System.out.println(eo);                                          
               System.out.println("exception in get board");                    
            }     
             this.drawBoard(s_board); 
            } 
                
              }                     
          }                         
          else
          {
             if(( myTurn) && (playerID <=1))
              display.append("invalid move try again \n");
          }                                                                    
}

   public void drawBoard(char[][] s_board){

      for ( int i = 0; i < 8; i++ )
          for (int j = 0; j < 8; j++ ) {
              board[ i ][ j ].setMark(s_board[i][j]);
              board[ i ][ j ].repaint();
      }
}   

   public void sendClickedSquare( int loc )
   {   
        boolean tested = false;
        myTurn = true;
        testit(loc);
   }

   public void countThem(){
        int x_count = 0;
        int o_count = 0;

        for (int i = 0; i<8; i++)
          for (int j = 0; j<8; j++){
            
            if (s_board[i][j] == 'X')
              x_count ++;
               if (s_board[i][j] == 'O')                                       
                 o_count ++; 
        } 
    display.append( "X has " + x_count +  " O has " + o_count + "\n"); 

}


   public void killed(){
        try{
	game.endGame();
        }
        catch(Exception e){}

}

   public void setCurrentSquare( Square s )
   {
      currentSquare = s;
   }
private Reversi Reversigame;
}

// Maintains one square on the board
class Square extends JPanel {
   private char mark;
   private int location;

   public Square( char m, int loc)
   {
      mark = m;
      location = loc;
      setSize ( 30, 30 );

      setVisible(true);
   }

   public Dimension getPreferredSize() {
      return ( new Dimension( 30, 30 ) );
   }

   public Dimension getMinimumSize() {
      return ( getPreferredSize() );
   }

   public void setMark( char c ) { mark = c; }

   public int getSquareLocation() { return location; }

   public void paintComponent( Graphics g )
   {
      g.setColor(Color.blue);
      super.paintComponent( g );
      g.drawRect( 0, 0, 29, 29 );
      g.drawString( String.valueOf( mark ), 11, 20 );

   }
}

class SquareListener extends MouseAdapter {
   private ReversiClient1 applet;
   private Square square;

   public SquareListener( ReversiClient1 t, Square s )
   {
      applet = t;
      square = s;
   }
  public void mouseReleased (MouseEvent e)
  {
	applet.setCurrentSquare(square);
        applet.sendClickedSquare (square.getSquareLocation());
  }

}

















