/* 
  Filename: dice2.java
  Compile String: javac dice2.java
  Programmer: Adam Cecchetti
  Usage: appletviewer dice.html
  Purpose: Roll some dice

*/

import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class dice extends Applet implements ItemListener, ActionListener
 {
  CheckboxGroup radios;
  Checkbox d4, d6, d8, d10, d12, d20, d30, d50, d100, check1; 
  TextField text1, text2, text3;
  Button rollDice, clearDice, sendDice, recvDice, chartDice, aboutDice;
  int dx = 6;
  Label label1, label2, label3;
  dialogframe about_dialog, error_dialog, send_dialog, recv_dialog, chart_dialog;
  int rolls[] = new int[1025];  
  int numdice = 0;

 public void init() {
  
   setSize(200,200);
   setBackground(Color.white);
   setLayout(new GridLayout(7,3));
   radios = new CheckboxGroup();
   d4   = new Checkbox("d4", false, radios);
   d6   = new Checkbox("d6", true, radios);
   d8   = new Checkbox("d8", false, radios);
   d10  = new Checkbox("d10", false, radios);
   d12  = new Checkbox("d12", false, radios);
   d20  = new Checkbox("d20", false, radios);
   d30  = new Checkbox("d30", false, radios);
   d50  = new Checkbox("d50", false, radios);
   d100 = new Checkbox("d100", false, radios);
   label1 = new Label("Result");
   label2 = new Label("# of Dice");
   label3 = new Label("Plus");
   text1 = new TextField(10);
   text2 = new TextField(3);
   text3 = new TextField(3);
   rollDice  = new Button("Roll");
   clearDice = new Button("Clear");
   sendDice  = new Button("Send");
   recvDice  = new Button("Recv");
   chartDice = new Button("Chart");
   aboutDice = new Button("About");

   text1.setText("0");
   text2.setText("1");
   text3.setText("0");
 
   add(d4);
   add(d6);
   add(d8);
   add(d10);
   add(d12);
   add(d20);
   add(d30);
   add(d50);
   add(d100);
   add(label1);
   add(label2);
   add(label3);
   add(text1);
   add(text2);
   add(text3);
   add(rollDice);
   add(clearDice);
   add(chartDice);
   add(sendDice);
   add(recvDice);
   add(aboutDice);

   d4.addItemListener(this);
   d6.addItemListener(this);
   d8.addItemListener(this);
   d10.addItemListener(this);
   d12.addItemListener(this);
   d20.addItemListener(this);
   d30.addItemListener(this);
   d50.addItemListener(this);
   d100.addItemListener(this);
   rollDice.addActionListener(this);
   clearDice.addActionListener(this);
   sendDice.addActionListener(this);
   recvDice.addActionListener(this);
   chartDice.addActionListener(this);
   aboutDice.addActionListener(this);

  } /* End Init Class */ 

  public void itemStateChanged(ItemEvent e)
   { 
    String temp = "";
    //Some people say I have a sick mind this would be proof
    dx = Integer.parseInt( ((((Checkbox) e.getItemSelectable()).getLabel()).substring(1)));
   }

 public void actionPerformed (ActionEvent e) 
   {
    String temp = "";
    if(e.getSource() == rollDice){
      temp = temp.valueOf(rollDice());
      text1.setText(temp);
     }
    else if (e.getSource() == clearDice)
     {
       clearDice();
      }
    else if (e.getSource() == aboutDice)
     {
      aboutDice();
     }
    else if (e.getSource() == recvDice)
     {
      recvDice();
     }
    else if (e.getSource() == sendDice)
     {
      sendDice();
     }
    else if (e.getSource() == chartDice)
     {
      chartDice();
     }
    else
     {
       clearDice();
      }

    }

  public void aboutDice() { 
                      about_dialog = new dialogframe("About");
                      about_dialog.about();     
                      about_dialog.setVisible(true);
                      }
  public void recvDice() {
                      recv_dialog = new dialogframe("Send");
                      recv_dialog.recv();
                      recv_dialog.setVisible(true);
                      }
  public void sendDice() {
                      send_dialog = new dialogframe("Send");
                      send_dialog.send(rolls,numdice);
                      send_dialog.setVisible(true);
                      }
  public void chartDice() {
                      chart_dialog = new dialogframe("Send");
                      chart_dialog.chart(rolls,numdice);
                      chart_dialog.setVisible(true);
                      
                      }

 public int rollDice() 
   {
     int i = 0,roll = 0, plus = 0, total = 0;
     numdice = Integer.parseInt(text2.getText());
     plus = Integer.parseInt(text3.getText());
     

     if (numdice > 1024) {
      error_dialog = new dialogframe("Error");
      error_dialog.error("Too many dice 1024 Max");
      error_dialog.setVisible(true);
      return 0;
      }

     for(i =0; i < 1024; i++)
        rolls[i] = 0;

     for(i = 0; i < numdice; i++)
      {
       rolls[i] = roll = plus + (int) ((Math.random() * dx) + 1);
       total += roll;
      }
      if (numdice > 1)
      rolls[i++] = total; 
     return total;   

   } /* End rolldice */

public int getDice(int x)
{
 return rolls[x];
}

public void clearDice() 
  {
   text1.setText("0");
   text2.setText("1");
   text3.setText("0");
   for(int i = 0; i < 1024; i++)
      rolls[i] =0;
    
  }

 }/* End Dice Class */


class dialogframe extends Frame implements ActionListener
 {
  
Button Ok, SendBtn, RecvBtn;
Label text, text1, text2;
TextField host_text, port_text, name_text;
List List1;
int recv_dice[] = new int[1025];
int numrolls = 0;
  
  dialogframe(String title)
   {
    super(title);
    setSize(200,200);
    addWindowListener(new WindowAdapter() {public void 
      windowClosing(WindowEvent e) {setVisible(false);}});
   }

   void about() {   
       //about 
       setLayout(new GridLayout(4,1));
       text = new Label("Created By Adam 'X' Cecchetti");
       text1 = new Label("http://www.shaodwflux.com");
       text2 = new Label("      adam@cecchetti.com");
       add(text);
       add(text1);
       add(text2);
       Ok = new Button("Ok");
       add(Ok);
       Ok.addActionListener(this);
    }
 
    void error(String error) {
     
     setLayout(new GridLayout(2,1));
     text = new Label(error);
     Ok = new Button("Oops");
     add(text);
     add(Ok);
     Ok.addActionListener(this);
     }

    void send(int dice[], int numdice) {
       //send    
       setSize(200,300);
       setLayout(new GridLayout(7,1));
       text = new Label("Host:");
       text1 = new Label("Port:");
       text2 = new Label("Name:");
       host_text = new TextField(50);
       name_text = new TextField(25);
       port_text = new TextField(5);
       SendBtn = new Button("Send");
       host_text.setText("127.0.0.1");
       port_text.setText("2000");
       name_text.setText("Java Dice");
       add(text);
       add(host_text);
       add(text1);
       add(port_text);
       add(text2);
       add(name_text);
       add(SendBtn);
       SendBtn.addActionListener(this);
       numrolls = numdice;
       for(int i = 0; i < numrolls + 1; i++)
        recv_dice[i] = dice[i];
    }

    void recv() {
       //recv
       String temp = "";
       int i = 0;
       setLayout(new GridLayout(4,1));
       text = new Label("Port:");
       port_text = new TextField(25);
       List1 = new List(10);
       RecvBtn = new Button("Recv");
       port_text.setText("2000");
       add(text);
       add(port_text);
       add(List1);
       add(RecvBtn);
       RecvBtn.addActionListener(this); 
    }

    void chart(int rolls[],int numdice) {
       //chart
       String temp = "";
       int i = 0;
       setLayout(new GridLayout(3,1));
       text = new Label("The last value is the total");
       List1 = new List(10);
       Ok = new Button("Ok");
       if (numdice == 1)
         List1.add((temp = String.valueOf(rolls[i])));
       else {
        for (i = 0; i < (numdice + 1); i++) {
           List1.add((temp = String.valueOf(rolls[i])));
          }
        }
       add(List1);
       add(text);
       add(Ok);
       Ok.addActionListener(this);
     }
    


    
   public void actionPerformed(ActionEvent event) 
    {
     int port = 2000;

     if (event.getSource() == SendBtn)
       {
         port = Integer.parseInt(port_text.getText());
         OutputStreamWriter out = null;

        try {          
          Socket OurSocket = new Socket(host_text.getText(),port);
          OutputStream raw = OurSocket.getOutputStream();
          OutputStream buffered = new BufferedOutputStream(raw);
          out = new OutputStreamWriter(buffered, "ASCII"); 
          String tmp="";
          for(int i = 0; i < numrolls +1; i++)
	    { 
            out.write(tmp = tmp.valueOf(recv_dice[i]));
            out.write('\r');
            }
          out.flush();
          
         }
 
         catch (UnknownHostException e) { System.err.println(e); }

         catch (IOException e) { System.err.println(e); }

        finally {
           try {
             if (out != null) { out.close(); }
               }
           catch (IOException e) {} 
          } 
           


       } // End SendBtn 

     else if (event.getSource() == RecvBtn)
       {
        port = Integer.parseInt(port_text.getText());
       
         try {
         ServerSocket server = new ServerSocket(port);
         Socket connection = null; 
            try {
               connection = server.accept();
               InputStream in = new BufferedInputStream(connection.getInputStream());
               StringBuffer request = new StringBuffer(80);

               while(true)
                 {
                 int c = in.read();
                 if (c == '\r' || c == '\n') 
                     
                 if (c == -1) break;
                 request.append((char) c);
                 }
              } //end try 

            catch (IOException e) { }
 
            finally {
              if (connection != null) connection.close();
              }

          } //end try 

        catch (IOException e) {
          System.err.println("Port Occupied, Please Hang up and dial all 1 or 5 digits again");
         }
       }//End RecvBtn

     else {
       this.setVisible(false);
      }
    } //End actionPerformed 

}//End Frame Class
