All pastes #1217688 Raw Edit

client

public java v1 · immutable
#1217688 ·published 2008-10-03 06:07 UTC
rendered paste body
import java.io.*;import java.net.*;import java.awt.*;import java.awt.event.*;import javax.swing.event.*;import javax.swing.border.Border;//for bordersimport javax.swing.border.LineBorder;//for border linesimport java.awt.event.ActionEvent;//for action eventimport java.awt.event.ActionListener;//for action listenerimport javax.swing.*;import java.util.*;import java.util.Timer;// for timerimport java.util.TimerTask;//for timerpublic class client extends JFrame implements Runnable //implements ActionListener{  painter[] hey = new painter[4];    int forServer[] = new int[4];// to get the guess, then send to the server  int fromServer[] = new int[4];// to receive other player's guesses  boolean gameOn;  boolean isSingle = true;  boolean isFiveSec = false;  boolean show = false;   int order = 0, color, wOrB, sglOrMult, showOrNot, session = 0, guessCounter = 0, temp = 0, canSee = 0;  private boolean winner = false, running = false, notFirstGame = false;  // the panels  JPanel jtp = new JPanel();  private JPanel topsec = new JPanel();  private JPanel third = new JPanel();  private JPanel second = new JPanel();  private JPanel bottom = new JPanel();  private JPanel chatPn = new JPanel();  private JPanel gamePn = new JPanel();  private JPanel gDBS = new JPanel();  private JPanel btn = new JPanel();  private JPanel top = new JPanel();  private JPanel topright = new JPanel();  private JPanel radioBtn1 = new JPanel();  private JPanel radioBtn2 = new JPanel();  // the text areas  private JTextArea game = new JTextArea(35, 20);  private JTextArea chat = new JTextArea(35, 20);  private JTextArea msg = new JTextArea(5, 25);  // the Buttons  private JButton start = new JButton("Start New Game");  private JButton quit = new JButton("Quit The Game");  private JButton bSpace = new JButton("Backspace");  private JButton red = new JButton("Red-1");  private JButton orange = new JButton("Orange-2");  private JButton yellow = new JButton("Yellow-3");  private JButton green = new JButton("Green-4");  private JButton blue = new JButton("Blue-5");  private JButton purple = new JButton("Purple-6");  private JButton ok = new JButton("OK");  private JButton send = new JButton("Send");  //labels  private JLabel msgFromServer;     private JLabel gameType = new JLabel("          Game Type ",10);  private JLabel showOPIG = new JLabel("          Show other player's incorrect guesses ");  private JLabel dWinner = new JLabel("Game Status:  ");//  private JLabel mMind = new JLabel("     Mastermind - bla");   private JLabel cChat = new JLabel("     Chit-chat");   private JLabel blank = new JLabel("           ");   //  JLabel player;//  JLabel computer;  //text fields  private JTextArea winnerDisplay = new JTextArea(2,40);//  winnerDisplay.setEditable(false);  private JTextField guessDisplay = new JTextField(20);  //radio buttons  JRadioButton single = new JRadioButton("Single");  JRadioButton multi = new JRadioButton("Multiplayers");  JRadioButton on = new JRadioButton("On");  JRadioButton off = new JRadioButton("Off");   //radio button group  ButtonGroup type = new ButtonGroup();  ButtonGroup OPIG = new ButtonGroup();  // IO streams  private DataOutputStream outputToServer;  private DataInputStream inputFromServer;  public static void main(String[] args) {    new client();  }  // constructor begin  public client() {    Container c = getContentPane();    //set jpanel background color for the choices made    //disable editable for text areas    winnerDisplay.setEditable(false);    chat.setEditable(false);    game.setEditable(false);    // put radio buttons into groups    type.add(single);    type.add(multi);    OPIG.add(on);    OPIG.add(off);    // put radio buttons together in a panel    radioBtn1.setLayout(new GridLayout(2,1));    radioBtn1.add(single);    radioBtn1.add(multi);         radioBtn2.setLayout(new GridLayout(2,1));    radioBtn2.add(on);    radioBtn2.add(off);    // put the show option in a seperate panel    topright.setLayout(new FlowLayout());    topright.add(showOPIG);    topright.add(radioBtn2);    topright.setVisible(false); //set to invis at start until player selects multiplayer game    // arrange the top row of the window into one panel    top.setLayout(new FlowLayout());    top.add(gameType);    top.add(radioBtn1);    top.add(topright);    top.add(start);    start.setEnabled(false);    //arrange the second row of the window into one panel    second.setLayout(new FlowLayout());    second.add(dWinner);    second.add(winnerDisplay);    second.add(blank);    second.add(quit);    //put top panel and second panel together    topsec.setLayout(new GridLayout(2,1));    topsec.add(top);    topsec.add(second);    //use scrol pane for the text areas    JScrollPane scrollOne = new JScrollPane(game);    JScrollPane scrollTwo = new JScrollPane(chat);    //arrange the third row of the window into one panel    third.setLayout(new GridLayout(1,2));    third.add(scrollOne);    third.add(scrollTwo);    //set layout for the JTextPane    jtp.setLayout(new GridLayout(1, 4));    //jtp.setBackground(Color.lightGray);    //put the input display and backspace button into one panel    gDBS.setLayout(new GridLayout(2,2));    gDBS.add(jtp);    gDBS.add(bSpace);    gDBS.add(ok);    ok.setEnabled(false);    bSpace.setEnabled(false);    //put buttons together into one panel    btn.setLayout(new GridBagLayout());    btn.add(red);    btn.add(orange);    btn.add(yellow);    btn.add(green);    btn.add(blue);    btn.add(purple);    red.setEnabled(false);    orange.setEnabled(false);    yellow.setEnabled(false);    green.setEnabled(false);    blue.setEnabled(false);    purple.setEnabled(false);    //give the buttons corresponding colors    red.setBackground(Color.red);    orange.setBackground(Color.orange);    yellow.setBackground(Color.yellow);    green.setBackground(Color.green);    blue.setBackground(Color.blue);    purple.setBackground(Color.magenta);    send.setBackground(Color.cyan);    quit.setBackground(Color.pink);    start.setBackground(Color.green);    //put the chat msg display and send button into one panel    chatPn.setLayout(new FlowLayout());    chatPn.add(msg);    chatPn.add(send);    send.setEnabled(false);    //put the whole button area of gamePn together    gamePn.setLayout(new GridLayout(2,1));    gamePn.add(gDBS);    gamePn.add(btn);    //now put the whole bottom row together    bottom.setLayout(new GridLayout(1,3));    bottom.add(gamePn);    bottom.add(chatPn);      connectToServer();//starts connection to server    try{      session = inputFromServer.readInt();//Multi(1)receive sessionIDSystem.out.println("session = " + session);      if (session == 2) {//                  new DataInputStream(socket.getInputStream()).readInt();        canSee = inputFromServer.readInt();System.out.println("can see sess2 (1) = " + canSee);        if (canSee == 1){          show = true;        } else {          show = false;        }        start.setEnabled(true);      }    } catch (IOException ex) {      System.err.println(ex);    }    // =============add the action listeners ====================    // 2. quit the game    quit.addActionListener(      new ActionListener(){        public void actionPerformed(ActionEvent e){          int exitConfirmation = JOptionPane.showConfirmDialog(null, "Exit?", "Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);          if (exitConfirmation == JOptionPane.YES_OPTION)             System.exit(0);        }      }    );    // 3. add action listener to options(radio buttons)    // (1) single    single.addActionListener(      new ActionListener(){        public void actionPerformed(ActionEvent e){          start.setEnabled(true);          isSingle = true;          topright.setVisible(false);          gameOn = true;          send.setEnabled(false);        }      }    );    // (2)multiple    multi.addActionListener(      new ActionListener(){        public void actionPerformed(ActionEvent e){          isSingle = false;          if (session == 1)            topright.setVisible(true);          else{            if (notFirstGame)              show = true;//if multiplayer and player 1 left the game//            if(session == 2)            on.setEnabled(false);            off.setEnabled(false);            start.setEnabled(true);            gameOn = true;          }          send.setEnabled(true);        }      }    );    // if it's a multiplayer game then the program listens    // to the "show other player's incorrect guesses" option             // (3) on    on.addActionListener(      new ActionListener(){        public void actionPerformed(ActionEvent e){          start.setEnabled(true);          show = true;          gameOn = true;        }      }    );    //(4) off    off.addActionListener(      new ActionListener(){        public void actionPerformed(ActionEvent e){          start.setEnabled(true);          show = false;          gameOn = true;        }      }    );    // 1. start the game     start.addActionListener(      new ActionListener(){        public void actionPerformed(ActionEvent e){          if(gameOn){            if(isSingle)              running = true;            game.setText("");            ok.setEnabled(false);            quit.setEnabled(false);            start.setEnabled(false);            bSpace.setEnabled(false);            guessCounter = 1;//reset counter//            running = true;//we need to send info about the game to server,shouldn't start listening            // connect to server//            connectToServer();            createThread();            try{              if (notFirstGame){                connectToServer();//starts connection to server                session = inputFromServer.readInt();                setTitle("Mastermind - Client" + session);              }              if(isSingle){                multi.setEnabled(false);                red.setEnabled(true);                orange.setEnabled(true);                yellow.setEnabled(true);                green.setEnabled(true);                blue.setEnabled(true);                purple.setEnabled(true);                sglOrMult = 1;// let the server know it's gonna be a single player game                outputToServer.writeInt(sglOrMult);//singleGame!!!                outputToServer.flush();                // Get the message from the server                String message = inputFromServer.readUTF();                // Display the message in the game status(text field)                 // it should be like: "You can start the game now";                winnerDisplay.setText("");                winnerDisplay.append(message+"\n");               } else {                on.setEnabled(false);                off.setEnabled(false);                single.setEnabled(false);                sglOrMult = 2;// let the server know it's gonna be multiplayers game                outputToServer.writeInt(sglOrMult);//multigame!!!                outputToServer.flush();//                session = inputFromServer.readInt();//Multi(1)receive sessionID//                winnerDisplay.setText("");//                winnerDisplay.setText("You are Player "+session+"\n");                if (session == 1){                  if(show) {                    showOrNot = 1;//when user choose to see other player's guesses                  } else {                    showOrNot = 2;//when user didn't want to see other player's guesses                  }                  outputToServer.writeInt(showOrNot);                  outputToServer.flush();                }                outputToServer.writeInt(99);//multigame!!!outputToServer.flush();int sadsad = inputFromServer.readInt();System.out.println("testing la "+sadsad);//############################################################################################//problem starts here as message is not received or displayed//############################################################################################System.out.println("Test get message");    // Get the message from the server    String message = null;    try {//      while(message == null)        message = inputFromServer.readUTF();System.out.println(message);    } catch (IOException ex) {      System.err.println(ex);    }System.out.println("Test3");                // Display the message in the game status(text field)                 // it should be like: "You can start the game now";    winnerDisplay.setText("");    winnerDisplay.append(message+"\n");                red.setEnabled(true);                orange.setEnabled(true);                yellow.setEnabled(true);                green.setEnabled(true);                blue.setEnabled(true);                purple.setEnabled(true);              }            } catch (IOException ex) {              System.err.println(ex);            }            running = false;          } else {//            start.setEnabled(true);          }          notFirstGame = true;        }      }    );    //======== add action listeners to 6 types of color buttons ===================    // 1. red    red.addActionListener(      new ActionListener(){        public void actionPerformed(ActionEvent e){          bSpace.setEnabled(true);          color = 1;          if(orderCheck() == true){            forServer[order] = color;            jtp.add(hey[order] = new painter(color));            jtp.revalidate();            order++;          }          if (forServer[3] != 0) {            ok.setEnabled(true);          }        }      }    );    //2. orange    orange.addActionListener(      new ActionListener(){        public void actionPerformed(ActionEvent e){          bSpace.setEnabled(true);          color = 2;          if(orderCheck() == true){            forServer[order] = color;            jtp.add(hey[order] = new painter(color));            jtp.revalidate();            order++;          }          if (forServer[3] != 0) {            ok.setEnabled(true);          }        }      }    );    //3. yellow    yellow.addActionListener(      new ActionListener(){        public void actionPerformed(ActionEvent e){          bSpace.setEnabled(true);          color = 3;          if(orderCheck() == true){            forServer[order] = color;            jtp.add(hey[order] = new painter(color));            jtp.revalidate();            order++;          }          if (forServer[3] != 0) {            ok.setEnabled(true);          }        }      }    );    // 4. green    green.addActionListener(      new ActionListener(){        public void actionPerformed(ActionEvent e){          bSpace.setEnabled(true);          color = 4;          if(orderCheck() == true){            forServer[order] = color;            jtp.add(hey[order] = new painter(color));            jtp.revalidate();            order++;          }          if (forServer[3] != 0) {            ok.setEnabled(true);          }        }      }    );    // 5. blue    blue.addActionListener(      new ActionListener(){        public void actionPerformed(ActionEvent e){          bSpace.setEnabled(true);          color = 5;          if(orderCheck() == true){            forServer[order] = color;            jtp.add(hey[order] = new painter(color));            jtp.revalidate();            order++;          }          if (forServer[3] != 0) {            ok.setEnabled(true);          }        }      }    );    // 6. purple    purple.addActionListener(      new ActionListener(){        public void actionPerformed(ActionEvent e){          bSpace.setEnabled(true);          color = 6;          if(orderCheck() == true){            forServer[order] = color;            jtp.add(hey[order] = new painter(color));            jtp.revalidate();            order++;          }          if (forServer[3] != 0) {            ok.setEnabled(true);          }        }      }    );    // Backspace button    bSpace.addActionListener(      new ActionListener(){        public void actionPerformed(ActionEvent e){          if (forServer[1] == 0)            bSpace.setEnabled(false);          if(isOrderEmpty() == false){            order--;            forServer[order] = 0;            jtp.remove(hey[order]);            jtp.revalidate();          }          if(order == 0){            jtp.remove(hey[order]);//trial and error//            jtp.removeAll();            jtp.revalidate();            jtp.updateUI();            order = 0;          }        }      }    );        // OK button    ok.addActionListener(      new ActionListener(){        public void actionPerformed(ActionEvent e){          ok.setEnabled(false);          bSpace.setEnabled(false);          jtp.removeAll();          jtp.updateUI();          jtp.revalidate();          for(int i=0;i<4; i++){            System.out.println(i+ "  "+forServer[i]);          }          running = true;//the broadcast listener should stop listening,let ok to send the guesses          try {            // first int to be sent to server just for seperating it's from OK button action            /* or Send button action. because OK sends 4 integers, Send sends one string.  */            if(!(isSingle)){              int okOrSend = 1;               outputToServer.writeInt(okOrSend);              outputToServer.flush();              outputToServer.writeInt(session);              outputToServer.flush();            }            // Send the guesses to the server. it's same for both types of games            for (int i = 0; i < 4; i++)              outputToServer.writeInt(forServer[i]);              outputToServer.flush();            System.out.println("success"); //testing..testing..            outputToServer.flush();            // Get the message and info on correct color & correct order            //first receive the both color&order match to determine whether the player won or not            int bothOnC = inputFromServer.readInt();//broadcast(1)receiving bothMatch***//            System.out.println(bothOnC);//testing...*******testing**********            if(bothOnC == 4){              guessCounter = 0;//reset counter              String msgGame = inputFromServer.readUTF();              winnerDisplay.setText(msgGame);              winner = true;              quit.setEnabled(true);              start.setEnabled(true);              ok.setEnabled(false);              red.setEnabled(false);              orange.setEnabled(false);              yellow.setEnabled(false);              green.setEnabled(false);              blue.setEnabled(false);              purple.setEnabled(false);              multi.setEnabled(true);              single.setEnabled(true);              on.setEnabled(true);              off.setEnabled(true);            } else {              int cColor = inputFromServer.readInt();// just the color matches              guessCounter = inputFromServer.readInt();//to get the number of guess              if(isSingle){                //check if the guess limit is up                if(guessCounter == 8){//for single game only                  String looser = inputFromServer.readUTF();                  winnerDisplay.setText(looser);                  start.setEnabled(true);                  red.setEnabled(false);                  orange.setEnabled(false);                  yellow.setEnabled(false);                  green.setEnabled(false);                  blue.setEnabled(false);                  purple.setEnabled(false);                  ok.setEnabled(false);                  multi.setEnabled(true);                  single.setEnabled(true);                }                // Display the message in the text area                 game.append("Guess"+guessCounter+":  "+forServer[0]+forServer[1]+forServer[2]+forServer[3]+                            "  BothMatch:  "+bothOnC+"  ColorMatch:  "+cColor+"\n");              } else {                game.append("Guess"+guessCounter+":  "+forServer[0]+forServer[1]+forServer[2]+forServer[3]+                            "  BothMatch:  "+bothOnC+"  ColorMatch:  "+cColor+"\n");                running = false;//sending stops so that the broadcast listener listen                try { //makes player waits for 5 seconds                  Thread.currentThread().sleep(5000);                } catch (InterruptedException er) {                  er.printStackTrace();                }                run();              }            }            //to clear the array after the sending            for (int i = 0; i <4; i++) {              forServer[i] = 0;              if(isOrderEmpty() == false) {                order--;                jtp.remove(hey[order]);                jtp.revalidate();              }              if(order == 0) {                jtp.remove(hey[order]);//trial and error//                jtp.removeAll();                jtp.revalidate();                order = 0;              }            }            jtp.revalidate();          } catch (IOException ex) {            System.err.println(ex);          }        }      }    );    // send button works only if it's multiplayer game    send.addActionListener(      new ActionListener(){        public void actionPerformed(ActionEvent e){          running = true;//the broadcast listener should stop listening,let ok to send the message          try {            if(!(isSingle)){            // first int to be sent to server just for seperating it's from OK button action            // or Send button action. because OK sends 4 integers, Send sends one string.              int okOrSend = 2;              // Get the message entered by user              String chatMsg = msg.getText();              // Send the first one for recognition whether it's from chat or game to the server              // send the second one(the string) to send the message from user to server              outputToServer.writeInt(okOrSend);              outputToServer.flush();              outputToServer.writeInt(session);              outputToServer.flush();              outputToServer.writeUTF(chatMsg);              outputToServer.flush();              chat.setText("");              running = false;//sending message stops let the broadcastlistener listen              run();            }          } catch (IOException ex) {            System.err.println(ex);          }        }      }    );  winnerDisplay.setText("");  winnerDisplay.setText("You are Player "+session+"\n");    if(session > 1)      single.setEnabled(false);    if(session > 2){      send.setEnabled(true);      start.setEnabled(false);      isSingle = false;      running = false;      gameOn = true;      try{        String startedAlready = inputFromServer.readUTF();        winnerDisplay.setText(startedAlready);      } catch (IOException ex) {        System.err.println(ex);      }      createThread();    }    //form the whole window     c.add(topsec,BorderLayout.NORTH);    c.add(third,BorderLayout.CENTER);    c.add(bottom,BorderLayout.SOUTH);            setTitle("Mastermind - Client" + session);    setSize(1000, 500);    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    setVisible(true);  }// end of Constructor  private void getMessage() {  }  //================= connectToServer() ===========================  private void connectToServer() { //inner class    try {      // Create a socket to connect to the server      Socket socket = new Socket("localhost", 8000);      // Socket socket = new Socket("101.212.124.36", 8000);      // Create an input stream to receive data from the server      inputFromServer = new DataInputStream(socket.getInputStream());      // Create an output stream to send data to the server      outputToServer = new DataOutputStream(socket.getOutputStream());    } catch (IOException ex) {      System.err.println(ex);    }//    Thread thread = new Thread(this);//    thread.start();  }// end of connectToServer    //=============== create thread ===============================  private void createThread() {  	Thread thread = new Thread(this);    thread.start();  }  //=============== run =========================================  public void run() {    try {    //****client should be always open to receive broadcast****      while(!(running)) {//while not sending anything,        int chatOrGame = inputFromServer.readInt();//***receive an integer                                                    //to know it's for chat or game        if(chatOrGame == 1) {//(game)             whileWaiting();//to receive info on other players        } else {          // Get the message from the server(chat)          String mesage = inputFromServer.readUTF();          // Display the message in the text area           chat.append(mesage + "\n");        }      }    } catch (IOException ex) {      System.err.println(ex);    }  } // end of run() //========= check if there still have space guess=========  public boolean orderCheck(){    if(order < 4)      return true;    return false; //else  }  // ============== is empty or not =======================   public boolean isOrderEmpty(){    if(order > 0)      return false;    return true;  }  //===============hear about other players while waiting ====================  public void whileWaiting(){    try{      if(show || session > 2){        String showing = inputFromServer.readUTF();        for (int i = 0; i < 4; i++)          fromServer[i] = inputFromServer.readInt();        int bothOnC = inputFromServer.readInt();        if(bothOnC == 4){              guessCounter = 0;//reset counter              String msgGame = inputFromServer.readUTF();              winnerDisplay.setText(msgGame);              winner = true;              start.setEnabled(false);              ok.setEnabled(false);              red.setEnabled(false);              orange.setEnabled(false);              yellow.setEnabled(false);              green.setEnabled(false);              blue.setEnabled(false);              purple.setEnabled(false);              multi.setEnabled(true);              single.setEnabled(true);              on.setEnabled(true);              off.setEnabled(true);        }        int cColor = inputFromServer.readInt();        game.append(showing+fromServer[0]+fromServer[1]+fromServer[2]+                    fromServer[3]+"BothMatch: "+bothOnC+"ColorMatch: "+cColor+"\n");      } else {        String notShowing = inputFromServer.readUTF();        for (int i = 0; i < 4; i++)          fromServer[i] = inputFromServer.readInt();        int bothOnC = inputFromServer.readInt();        if(bothOnC == 4){              guessCounter = 0;//reset counter              String msgGame = inputFromServer.readUTF();              winnerDisplay.setText(msgGame);              winner = true;              start.setEnabled(false);              ok.setEnabled(false);              red.setEnabled(false);              orange.setEnabled(false);              yellow.setEnabled(false);              green.setEnabled(false);              blue.setEnabled(false);              purple.setEnabled(false);              multi.setEnabled(true);              single.setEnabled(true);              on.setEnabled(true);              off.setEnabled(true);        }        int cColor = inputFromServer.readInt();        game.append(notShowing);      }    } catch (IOException ex) {      System.err.println(ex);    }  }}