public static int rollbackGUIConfigurationTransaction(String sConfigurationFileName) {

    String sConfigurationLockFile;
    File fFile;

    sConfigurationLockFile = new String(sConfigurationFileName + ".lck");

    try {
      fFile = new File(URLDecoder.decode(sConfigurationLockFile, "UTF-8"));
    } catch (IOException e) {
      JOptionPane.showMessageDialog(
          null, "URLDecoder.decode failed", "ConfigurationTransaction", JOptionPane.ERROR_MESSAGE);

      return 1;
    }

    if (fFile.delete() == false) {
      JOptionPane.showMessageDialog(
          null,
          "fFile.delete on " + sConfigurationLockFile + " failed",
          "ConfigurationTransaction",
          JOptionPane.ERROR_MESSAGE);

      return 3;
    }

    return 0;
  }
Exemple #2
0
  public void JudgeWhoIsWinner() // 判断胜负
      {
    String winner = "";

    if (white == 0) {
      JOptionPane.showMessageDialog(null, "黑方胜!" + black + ":" + white);
      //			JOptionPane.showMessageDialog(null, "游戏结束!用时" + time + "秒");
      submit.setEnabled(false);
      winner = "黑";
    }
    if (black == 0) {
      JOptionPane.showMessageDialog(null, "白方胜!" + white + ":" + black);
      //			JOptionPane.showMessageDialog(null, "游戏结束!用时" + time + "秒");
      submit.setEnabled(false);
      winner = "白";
    }
    if (black + white == 64) {
      if (white > black) {
        JOptionPane.showMessageDialog(null, "白方胜!" + white + ":" + black);
        //				JOptionPane.showMessageDialog(null, "游戏结束!用时" + time + "秒");
        submit.setEnabled(false);
        winner = "白";
      } else if (black > white) {
        JOptionPane.showMessageDialog(null, "黑方胜!" + black + ":" + white);
        //				JOptionPane.showMessageDialog(null, "游戏结束!用时" + time + "秒");
        submit.setEnabled(false);
        winner = "白";
      } else if (black == white) {
        JOptionPane.showMessageDialog(null, "和局!");
        //				JOptionPane.showMessageDialog(null, "游戏结束!用时" + time + "秒");
        winner = "";
      }
    }
  }
 @Override
 public void run() {
   try {
     receive();
   } catch (IOException ioException) {
     JOptionPane.showMessageDialog(null, "Problems with a server");
   } catch (InterruptedException interruptedException) {
     JOptionPane.showMessageDialog(null, "Interrupted exception thrown");
   } catch (ParserConfigurationException parserException) {
     parserException.printStackTrace();
   } catch (SAXException saxException) {
     saxException.printStackTrace();
   }
 }
Exemple #4
0
  /** execute method之后,取返回的inputstream */
  private static ByteArrayInputStream execute4InputStream(HttpClient client) throws Exception {
    int statusCode = client.getResponseCode();
    if (statusCode != HttpURLConnection.HTTP_OK) {
      throw new EnvException("Method failed: " + statusCode);
    }
    InputStream in = client.getResponseStream();
    if (in == null) {
      return null;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
      Utils.copyBinaryTo(in, out);

      // 看一下传过来的byte[]是不是DesignProcessor.INVALID,如果是的话,就抛Exception
      byte[] bytes = out.toByteArray();
      // carl:格式一致传中文
      String message = new String(bytes, EncodeConstants.ENCODING_UTF_8);
      if (ComparatorUtils.equals(message, RemoteDeziConstants.NO_SUCH_RESOURCE)) {
        return null;
      } else if (ComparatorUtils.equals(message, RemoteDeziConstants.INVALID_USER)) {
        throw new EnvException(RemoteDeziConstants.INVALID_USER);
      } else if (ComparatorUtils.equals(message, RemoteDeziConstants.FILE_LOCKED)) {
        JOptionPane.showMessageDialog(null, Inter.getLocText("FR-Designer_file-is-locked"));
        return null;
      } else if (message.startsWith(RemoteDeziConstants.RUNTIME_ERROR_PREFIX)) {
      }
      return new ByteArrayInputStream(bytes);
    } finally {
      in.close();
      out.close();
      client.release();
    }
  }
Exemple #5
0
    @Override
    public void actionPerformed(ActionEvent e) {
      Frame frame = getFrame();
      JFileChooser chooser = new JFileChooser();
      int ret = chooser.showOpenDialog(frame);

      if (ret != JFileChooser.APPROVE_OPTION) {
        return;
      }

      File f = chooser.getSelectedFile();
      if (f.isFile() && f.canRead()) {
        Document oldDoc = getEditor().getDocument();
        if (oldDoc != null) {
          oldDoc.removeUndoableEditListener(undoHandler);
        }
        if (elementTreePanel != null) {
          elementTreePanel.setEditor(null);
        }
        getEditor().setDocument(new PlainDocument());
        frame.setTitle(f.getName());
        Thread loader = new FileLoader(f, editor.getDocument());
        loader.start();
      } else {
        JOptionPane.showMessageDialog(
            getFrame(),
            "Could not open file: " + f,
            "Error opening file",
            JOptionPane.ERROR_MESSAGE);
      }
    }
Exemple #6
0
 /** close_notification */
 public synchronized void close_notification() throws RemoteException {
   JOptionPane.showMessageDialog(
       null,
       "Le serveur est injoignable pour le moment",
       "Erreur distante",
       JOptionPane.INFORMATION_MESSAGE);
   srv_state = false;
   C.initialiser();
 }
 private void actionAdd() {
   URL verifiedUrl = verifyUrl(addTextField.getText());
   if (verifiedUrl != null) {
     tableModel.addDownload(new DownloadFile(verifiedUrl));
     addTextField.setText("");
   } else {
     JOptionPane.showMessageDialog(
         this, "Invalid Download URL", "Error", JOptionPane.ERROR_MESSAGE);
   }
 }
 // constructor
 public GameClient_(JFrame oldWindow, MultiPlayerMenuWindow multiPlayerMenu) {
   m_MultiPlayerMenu = multiPlayerMenu;
   m_OldWindow = oldWindow;
   try {
     m_IP = InetAddress.getLocalHost().getHostAddress();
     JOptionPane.showMessageDialog(oldWindow, "Server's IP: " + m_IP);
   } catch (UnknownHostException e) {
     System.err.println(e);
   }
   m_Port = 8000;
 }
Exemple #9
0
 void lookupByXPath(String xpath) {
   NodeList nl = DOMInfoExtractor.locateNodes(document, xpath);
   System.out.println("lookupByXPath: " + xpath);
   if (nl == null) {
     JOptionPane.showMessageDialog(this, "error xpath: " + xpath);
   }
   System.out.println("find " + nl.getLength() + " items");
   FoundItem[] fis = new FoundItem[nl.getLength()];
   for (int i = 0; i < nl.getLength(); i++) {
     fis[i] = getFoundItem(nl.item(i), null);
   }
   foundList.setListData(fis);
 }
  public void displayPage(JEditorPane pane, String text) {
    try {
      File helpFile = new File((String) locations.get(text));
      String loc = "file:" + helpFile.getAbsolutePath();
      URL page = new URL(loc);

      pane.setPage(page);

    } catch (IOException ioe) {
      JOptionPane.showMessageDialog(null, "Help Topic Unavailable");
      pane.getParent().repaint();
    }
  }
Exemple #11
0
  public static void finalresult(String check) {
    if (check.equals("tie")) {
      try {
        func(socket, "tie");
      } catch (IOException e) {
        System.out.println("exception has been raised");
      }
      JOptionPane.showMessageDialog(null, "It is a tie between the two");
      System.exit(0);
    } else {
      if (check.equals("winserver")) {
        try {
          func(socket, "winserver");
        } catch (IOException e) {
          System.out.println("exception has been raised");
        }
        JOptionPane.showMessageDialog(null, "The Server Has Won The Game");
        System.exit(0);
        // JOptionPane.showMessageDialog(network.this,"The server has won the
        // game","result",JOptionPane.INFORMATION_MESSAGE);
      } else {
        if (check.equals("winclient")) {
          try {
            func(socket, "winclient");
          } catch (IOException e) {
            System.out.println("exception has been raised");
          }

          JOptionPane.showMessageDialog(null, "the client has won the game");
          System.exit(0);
          // JOptionPane.showMessageDialog(network.this,"The server has won the
          // game","result",JOptionPane.INFORMATION_MESSAGE);
        }
      }
    }
  }
Exemple #12
0
  public void CheckAtTheEnd() // 当无子可落时判断胜负
      {
    ShowChessNumber();
    gameStart = false;

    for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) cell[i][j].taken = true;

    String winner = "";

    if (white > black) {
      controlThread = false;
      JOptionPane.showMessageDialog(null, "白方胜!" + white + ":" + black);
      winner = "白";
    } else if (white < black) {
      controlThread = false;
      JOptionPane.showMessageDialog(null, "黑方胜!" + black + ":" + white);
      winner = "黑";
    } else if (white == black) {
      controlThread = false;
      JOptionPane.showMessageDialog(null, "和局!");
      winner = "";
    }
    //	JOptionPane.showMessageDialog(null, "游戏结束!用时" + time + "秒");
  }
Exemple #13
0
  public void setBrowserLocation(String locale, boolean cacheLocation) {
    // push old location if one exists AND its specified behavior
    if (cacheLocation && location != null) {
      locationStack.push(location);
      toolBar.getBackButton().setEnabled(true);
    }

    location = locale;
    try {
      browserPane.setPage(location);
    } catch (IOException ioex) {
      String message = "Error loading from location:\n" + ioex.getMessage();
      JOptionPane.showMessageDialog(this, message, "Browser Error", JOptionPane.ERROR_MESSAGE);
      return;
    }
  }
Exemple #14
0
 /** start_notification */
 public synchronized void start_notification() throws RemoteException {
   JOptionPane.showMessageDialog(
       null,
       "Le serveur est connecté de nouveau",
       "Notification du client",
       JOptionPane.INFORMATION_MESSAGE);
   srv_state = true;
   try {
     for (int i = 0; i < J.getnbrcon(); i++) {
       if (J.list_con()[i].compareTo(C.get_nom()) != 0) {
         C.ajout(J.list_con()[i]);
       }
     }
   } catch (RemoteException ex) {
   }
 }
 public boolean establishConnection() {
   try {
     clientSocket = new Socket(hostName, portNr);
     responseFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
     requestToServer = new PrintWriter(clientSocket.getOutputStream(), true);
     requestToServer.println("requestGameData");
     return true;
   } catch (Exception e) {
     JOptionPane.showMessageDialog(
         new JFrame(),
         "Host or port do not exist.",
         "Connection error",
         JOptionPane.ERROR_MESSAGE);
     return false;
   }
 }
Exemple #16
0
  public void restartApplication() {

    try {

      final String javaBin =
          System.getProperty("java.home") + File.separator + "bin" + File.separator + "javaw";
      final File currentJar =
          new File(network.class.getProtectionDomain().getCodeSource().getLocation().toURI());

      System.out.println("javaBin " + javaBin);
      System.out.println("currentJar " + currentJar);
      System.out.println("currentJar.getPath() " + currentJar.getPath());

      /* is it a jar file? */
      // if(!currentJar.getName().endsWith(".jar")){return;}

      try {

        // xmining = 0;
        // systemx.shutdown();

      } catch (Exception e) {
        e.printStackTrace();
      }

      /* Build command: java -jar application.jar */
      final ArrayList<String> command = new ArrayList<String>();
      command.add(javaBin);
      command.add("-jar");
      command.add("-Xms256m");
      command.add("-Xmx1024m");
      command.add(currentJar.getPath());

      final ProcessBuilder builder = new ProcessBuilder(command);
      builder.start();

      // try{Thread.sleep(10000);} catch (InterruptedException e){}

      // close and exit
      SystemTray.getSystemTray().remove(network.icon);
      System.exit(0);

    } // try
    catch (Exception e) {
      JOptionPane.showMessageDialog(null, e.getCause());
    }
  } // ******************************
Exemple #17
0
  public void run() {
    Socket socket = null;
    try {
      host = InetAddress.getLocalHost().getHostAddress();
      l.setText("Adres servera : " + host);
      serverSocket = new ServerSocket(port);
      JOptionPane.showMessageDialog(null, "Serwer dzia³a na adresie " + host);
      while (true) {
        socket = serverSocket.accept();
        if (socket != null) {
          sList.add(new ServerThread(socket, clientList, this));
        }
      }
    } catch (Exception e) {

    }
  }
Exemple #18
0
 void reloadJTree(String url) {
   System.out.println("reload " + url);
   Document dom;
   try {
     URL uurl = new URL(url);
     HTMLWrapper hw = new HTMLWrapper(url);
     dom = hw.getDOM();
   } catch (IOException e) {
     e.printStackTrace();
     try {
       dom = HTML2DOM.getDOM(new FileInputStream(url));
     } catch (IOException ie) {
       JOptionPane.showMessageDialog(this, "can't get document of the url: " + url);
       ie.printStackTrace();
       return;
     }
   }
   document = dom;
   jtree.setRootNode(dom);
 }
Exemple #19
0
  public void mouseClicked(MouseEvent e) {
    /*can = false;
    boolean f = true;
    for (int i = 0; i < 8; i++)
    {
    	for (int j = 0; j < 8; j++)
    	if (cell[i][j] == e.getSource())
    	{
    		int judege = Clicked(cell[i][j]);
    		f = false;
    		break;
    	}
    	if (!f) break;
    }*/

    boolean flage = CheckAll();
    if (flage) {
      can = false;
      if (kind.equals("" + turn)) {
        ChessBoard cel = (ChessBoard) (e.getSource());
        int judge = Clicked(cel);
        if (judge == 1) {
          try {
            System.out.println("发送前:" + cell[3][5].taken);
            out66.writeObject("落子" + turn);
            out66.flush();
            out66.writeObject(stateList.get(stateList.size() - 1));
            out66.flush();
            out66.writeObject(takenList.get(takenList.size() - 1));
            out66.flush();
          } catch (IOException e1) {
            e1.printStackTrace();
          }
        }
      } else {
        JOptionPane.showMessageDialog(null, "请确定您的身份,您此时不能落子");
      }
    } else CheckAtTheEnd();
  }
  /**
   * run will be exicuted when the thread is called, and will connect to the server and start
   * communicating with it.
   */
  public void run() {
    WaitForConnection wfc = new WaitForConnection("Waiting For Connection");
    m_OldWindow.setEnabled(false);
    try {
      m_Socket = new Socket(m_IP, m_Port);

      // System.out.println("Connecting to ChatService...");
      m_ChatSocket = new Socket(m_IP, m_Port);
      // System.out.println("\nConnected to ChatService...");

      wfc.updateMessage("Waiting For Other Players");

      // System.out.println("Getting OutputStream Stream From server...");
      toServer = new ObjectOutputStream(m_Socket.getOutputStream());
      toChatServer = new ObjectOutputStream(m_ChatSocket.getOutputStream());
      toChatServer.flush();

      // System.out.println("Getting Input Stream From server...");
      fromServer = new ObjectInputStream(m_Socket.getInputStream());
      fromChatServer = new ObjectInputStream(m_ChatSocket.getInputStream());

      m_ChatService = new ChatService();
      m_ChatServiceThread = new Thread(m_ChatService);
      m_ChatServiceThread.start();

      m_MultiPlayerMenu.startGame();
      wfc.dispose();
      m_OldWindow.dispose();
    } catch (java.net.ConnectException e) {
      wfc.dispose();
      MenuWindow menu = new MenuWindow(new JFrame(""));
      JOptionPane.showMessageDialog(menu.getMainFrame(), "Error Connection refused");
      m_OldWindow.setEnabled(true);
    } catch (IOException ex) {
      System.err.print(ex);
    }
  }
Exemple #21
0
  public void RegretChess() {
    for (int i = 0; i < 8; i++)
      for (int j = 0; j < 8; j++)
        if (cell[i][j].changed == true) {
          cell[i][j].ChangeBack();
        }
    turn = TakeTurn();
    try {
      stateList.remove(stateList.size() - 1);
      takenList.remove(takenList.size() - 1);

      char[][] states = stateList.get(stateList.size() - 1);
      boolean[][] takens = takenList.get(takenList.size() - 1);
      for (int i = 0; i < 8; i++)
        for (int j = 0; j < 8; j++) {
          cell[i][j].state = states[i][j];
          cell[i][j].taken = takens[i][j];
          cell[i][j].repaint();
        }

      for (int i = 0; i < 8; i++)
        for (int j = 0; j < 8; j++)
          if (cell[i][j].taken == false) {
            CheckPlace(cell[i][j]);
            if (canPut) {
              cell[i][j].ChangeBackground();
              canPut = false;
            }
          }

    } catch (ArrayIndexOutOfBoundsException e1) {
      JOptionPane.showMessageDialog(null, "无法悔棋");
    }
    if (stateList.size() == 0) {
      RememberState();
    }
  }
Exemple #22
0
  // implemented for HyperlinkListener
  public void hyperlinkUpdate(HyperlinkEvent e) {
    if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
      JEditorPane ep = (JEditorPane) (e.getSource());

      // handle frame events properly
      if (e instanceof HTMLFrameHyperlinkEvent) {
        HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent) e;
        HTMLDocument doc = (HTMLDocument) (ep.getDocument());
        doc.processHTMLFrameHyperlinkEvent(evt);
      } else // handle normal links
      {
        try {
          URL currentLoc = new URL(location);
          URL newLoc = new URL(currentLoc, e.getDescription());

          setBrowserLocation(newLoc.toString());
        } catch (MalformedURLException malUrl) {
          JOptionPane.showMessageDialog(
              this, "Malformed URL", "Browser Error", JOptionPane.ERROR_MESSAGE);
          return;
        }
      }
    }
  }
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == ld.st) // 0.로딩화면에서 Enter버튼 클릭
    {
      System.out.println("할리갈리 온라인 안쪽으로 접근중...");
      card.show(getContentPane(), "LOG");
    } else if (e.getSource() == login.bt1) // 1.팝업창으로 회원가입창 띄우기
    {
      mID.setBounds(470, 310, 340, 420);
      mID.setVisible(true);
    } else if (e.getSource() == login.bt2) // 2.로그인버튼 누르기
    {
      ld.clip.stop();
      wr.clip.play();
      id = login.tf.getText().trim(); // ID입력안했을때
      if (id.length() < 1) {
        JOptionPane.showMessageDialog(this, "ID를 입력하세요");
        login.tf.requestFocus();
        return;
      }
      String pass = new String(login.pf.getPassword()); // PWD입력안했을때
      if (pass.length() < 1) {
        JOptionPane.showMessageDialog(this, "Password를 입력하세요");
        login.pf.requestFocus();
        return;
      }

      connection(); // 모두 정확히 처리했으면, connection()메소드로 이동!!

      try {
        out.write(
            (Function.LOGIN
                    + "|"
                    + id
                    + "|" // 로그인버튼 눌러서 server에게 요청
                    + pass
                    + "\n")
                .getBytes());
      } catch (Exception ex) {
      }
    } else if (e.getSource() == wr.tf || e.getSource() == wr.b1) // 3.waitroom에서 채팅입력할 때
    {
      String data = wr.tf.getText(); // 입력한 값 가져오기
      if (data.length() < 1) return;
      try {
        out.write((Function.WAITCHAT1 + "|" + data + "\n").getBytes()); // 채팅전송을 server에게 요청
      } catch (Exception ex) {
      }
      wr.tf.setText("");
    } else if (e.getSource() == gw.tf || e.getSource() == gw.b1) // 4.gameWindow에서 채팅입력할 때
    {
      String data = gw.tf.getText(); // 입력한 값 가져오기
      if (data.length() < 1) return;
      try {
        out.write((Function.ROOMCHAT + "|" + data + "\n").getBytes()); // 채팅전송을 server에게
      } catch (Exception ex) {
      }
      gw.tf.setText("");
    } else if (e.getSource() == wr.b2) // 5.방만들기창
    {
      mr.tf.setText(""); // 방만들기 초기화
      mr.pf.setText("");
      mr.rb1.setSelected(true);
      mr.setBounds(500, 300, 260, 290);
      mr.setVisible(true);
    } else if (e.getSource() == wr.b3) // 6.방들어가기 버튼처리 /////////////////////////////////
    {
      wr.clip.stop();
      gw.clip.play();
      System.out.println("방유저리스트수: " + gw.model1.getRowCount());
      for (int i = 0; i < gw.model1.getRowCount(); i++) {
        System.out.println("방유저리스트삭제");
        gw.model1.removeRow(i); // 추가
      }
      // gw.model1.removeRow(0); //추가
      if (rowNum >= 0) {
        try {
          gw.ta.setText("");
          out.write((Function.JOINROOM + "|" + rowNum + "\n").getBytes());
        } catch (Exception e2) {
        }
      }
    } else if (e.getSource() == mr.b1) // 6.방만들기창에서 확인 눌렀을때//////////////////////////////
    {
      wr.clip.stop();
      gw.clip.play();
      gw.clip.loop();

      String subject = mr.tf.getText().trim(); // 방이름 입력 안했을때
      if (subject.length() < 1) {
        JOptionPane.showMessageDialog(this, "방이름을 입력하세요");
        mr.tf.requestFocus();
        return;
      }

      if (mr.rb2.isSelected()) { // 비공개 버튼 눌렀을 때
        String pw = new String(mr.pf.getPassword());
        if (pw.length() < 1) {
          JOptionPane.showMessageDialog(this, "비밀번호를 입력하세요");
          mr.pf.requestFocus();
          return;
        }
      }

      mr.dispose();
      /*System.out.println("방유저리스트수: "+gw.model1.getRowCount());
          for(int i=0;i<gw.model1.getRowCount();i++)
      {
          	  System.out.println("방유저리스트삭제");
       gw.model1.removeRow(i); //추가
      }*/
      try {
        String roomType = ""; // 1.공개or비공개 저장
        if (mr.rb1.isSelected()) {
          roomType = mr.rb1.getText();
        } // 공개
        else if (mr.rb2.isSelected()) {
          roomType = mr.rb2.getText();
        } // 비공개
        String roomName = mr.tf.getText(); // 2.방이름
        String capaNum = mr.box.getSelectedItem().toString(); // 3.최대인원수
        out.write(
            (Function.MAKEROOM + "|" + roomType + "|" + roomName + "|" + capaNum + "\n")
                .getBytes());
        // 공개여부,방이름,최대인원 넘겨줌

      } catch (Exception ex) {
      }

    } else if (e.getSource() == wr.b8) // 도움말 버튼처리
    {
      help.setVisible(true);
      repaint();
    } else if (e.getSource() == wr.b9) // 게임종료 버튼처리
    {
      /*서버로 종료 메시지 전송후 프로그램 종료*/
      try {
        out.write((Function.CLIENTEXIT + "|\n").getBytes());

      } catch (Exception e2) {
      }

      try {
        s.close(); // 소켓해제
      } catch (IOException e1) {
        e1.printStackTrace();
      }
      System.exit(0);
    } else if (e.getSource() == mID.b1) // 가입완료버튼
    {
      String name = mID.tf1.getText().trim();
      String id = mID.tf2.getText().trim();
      String pass1 = new String(mID.pf1.getPassword());
      String pass2 = new String(mID.pf2.getPassword());
      if (name.length() < 1) {
        JOptionPane.showMessageDialog(this, "이름을 입력하세요");
        mID.tf1.requestFocus();
        return;
      } else if (id.length() < 1) {
        JOptionPane.showMessageDialog(this, "ID를 입력하세요");
        mID.tf2.requestFocus();
        return;
      } else if (mID.ck == false) {
        JOptionPane.showMessageDialog(this, "ID 중복체크 하시오");
        mID.tf2.requestFocus();
        return;
      } else if (pass1.length() < 1) {
        JOptionPane.showMessageDialog(this, "비밀번호를 입력하세요");
        mID.pf1.requestFocus();
        return;
      } else if (pass2.length() < 1) {
        JOptionPane.showMessageDialog(this, "비밀번호 확인을 입력하세요");
        mID.pf2.requestFocus();
        return;
      } else if (!(pass1.equals(pass2))) {
        JOptionPane.showMessageDialog(this, "비밀번호가 동일하지 않습니다");
        mID.pf1.requestFocus();
        return;
      }
      try {
        out.write((Function.SUCCESSJOIN + "|" + name + "|" + id + "|" + pass1 + "\n").getBytes());
      } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }
      JOptionPane.showMessageDialog(this, "회원가입완료");
      mID.dispose();
    } else if (e.getSource() == mID.b2) {
      mID.tf1.setText("");
      mID.tf2.setText("");
      mID.pf1.setText("");
      mID.pf2.setText("");
      mID.dispose();
    } else if (e.getSource() == mID.b3) // ID중복체크
    {
      String id = mID.tf2.getText().trim();
      if (id.length() < 1) {
        JOptionPane.showMessageDialog(this, "ID를 입력하세요");
        mID.tf2.requestFocus();
        return;
      }

      if (mID.num == 0) // 한번도 소켓을 연결하지 않았다면
      {
        System.out.println("연결시도");
        connection();
        mID.num++;
      }

      System.out.println("ID중복체크");
      try {
        System.out.println(id);
        out.write((Function.IDCHECK + "|" + id + "\n").getBytes()); // ID중복체크를 server에게 요청
      } catch (Exception ex) {
      }
    } else if (e.getSource() == gw.b4) { // GameWindow에서 준비버튼 눌렀을 때

      gw.clip.stop();
      gw.clip3.play();
      try {
        out.write((Function.ROOMREADY + "|" + "\n").getBytes());
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    } else if (e.getSource() == gw.b5) { // GameWindow에서 시작버튼 눌렀을 때
      try {
        out.write((Function.ROOMSTART + "|" + "\n").getBytes());
        gw.b5.setEnabled(false);
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    } else if (e.getSource() == gw.b6) // GameWindow에서 나가기 눌렀을 때
    {
      gw.clip.stop();
      gw.clip2.play();
      wr.clip.play();
      System.out.println("방나가기 버튼 Click");
      System.out.println("방유저리스트수: " + gw.model1.getRowCount());
      // int tmp=gw.model1.getRowCount();
      /*for(int i=0;i<gw.model1.getRowCount();i++)
      {
      	  gw.model1.removeRow(i); //추가
      }*/
      // gw.model1.
      wr.ta.setText(""); // 수정
      gw.b4.setEnabled(true);
      try {
        out.write((Function.EXITROOM + "|" + "\n").getBytes());
      } catch (Exception ex) {
      }
    } else if (e.getSource() == gw.cardOpen) // 카드뒤집기 눌렀을 때!!!
    {
      gw.clip4.play(); // 카드 넘기는 소리
      gw.cardOpen.setBorderPainted(false);
      gw.cardOpen.setContentAreaFilled(false);
      gw.cardOpen.setEnabled(false);
      try {
        out.write((Function.CARDOPEN + "|" + id + "\n").getBytes());
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    } else if (e.getSource() == gw.bell) // 종치기 버튼
    {
      gw.clip1.play(); // 종치는소리
      try {
        out.write((Function.BELL + "|" + id + "\n").getBytes());
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
Exemple #24
0
  public static void main(String[] args) throws IOException {
    ServerSocket s = new ServerSocket(PORT);
    System.out.println("Started: " + s);
    frame.setPreferredSize(new Dimension(400, 400));
    frame.addWindowListener(
        new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
          }
        });
    JMenuBar one = new JMenuBar();
    JMenu second = new JMenu("OPTIONS");
    //	JMenuItem third = new JMenuItem("NEW GAME");
    JMenuItem fourth = new JMenuItem("EXIT");
    fourth.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
            try {
              exit(evt);
            } catch (IOException e) {
            }
          }
        });
    // second.add(third);
    second.add(fourth);
    one.add(second);
    frame.setJMenuBar(one);
    frame.setLayout(new java.awt.GridLayout(3, 3));
    button = new JButton[10];
    for (int i = 1; i < 10; i++) {
      button[i] = new JButton();
      button[i].setBackground(Color.lightGray);
      button[i].setActionCommand(Integer.toString(i));
      button[i].addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
              print(evt.getActionCommand());
              try {
                func(socket, evt.getActionCommand());
                String check = win();
                finalresult(check);
                if (check != "") {
                  func(socket, check);
                } else {
                  func(socket, evt.getActionCommand());
                }
                ;
              } catch (IOException e) {
              }
            }
          });
      frame.add(button[i]);
    }

    try {
      socket = s.accept();
      frame.pack();
      frame.setVisible(true);
      try {
        System.out.println("Connection accepted: " + socket);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        /*  while(true)
        {
        String str=in.readLine();
        print2(str);
        }*/
        while (true) {
          String str = in.readLine();
          if (str.equals("exit")) {
            System.exit(0);
          }
          if (str.equals("tie")) {
            JOptionPane.showMessageDialog(null, "It is a tie between the two");
            System.exit(0);
          } else {

            if (str.equals("winserver")) {
              System.out.println("server has won");
              JOptionPane.showMessageDialog(null, "the server has won the game");
              System.exit(0);
            } else {
              if (str.equals("winclient")) {
                JOptionPane.showMessageDialog(null, "the client has won the game");
                System.exit(0);
              } else {
                System.out.println(str);
                print2(str);
              }
            }
          }
        }
      } catch (Exception e) {
      } // finally {socket.close();
      // }
    } catch (Exception e) {
    } // finally {s.close();
    // }
  }
Exemple #25
0
 public static void message(int message) {
   JOptionPane.showMessageDialog(null, message);
 }
Exemple #26
0
  // manejo de eventos de turno y los mapas
  public void actionPerformed(ActionEvent e) {
    if (estad == e.getSource()) {
      efectos.reproducirEfectoSonido("Klick");
      // IUpanel02.mainAE();   -----------------------------------------------
      /// setVisible(false);
    }
    if (registrar == e.getSource()) {
      efectos.reproducirEfectoSonido("Klick");
      OpcionesPerfiles.perfiles.mainAE();
      setVisible(false);
    }
    if (facil == e.getSource()) {
      efectos.reproducirEfectoSonido("Klick");
      String nomb = "";
      PerfilesBD coleccion = new PerfilesBD();
      int numPer = 0;
      numPer = coleccion.numeroDePerfiles();
      Perfil perfilesMostrar[] = null;

      if (numPer == 0) {
        perfilesMostrar = new Perfil[4];

        for (int idx = 0; idx < 4; idx++) {
          perfilesMostrar[idx] =
              new Perfil("Asesinator" + (idx + 1), "predt" + (idx + 1) + ".jpg", "123" + idx);
          coleccion.agregarPerfil(perfilesMostrar[idx]);
        }
      }

      try {
        do {
          nomb =
              JOptionPane.showInputDialog(null, "Ingrese Nombre de Jugador Humano", "Asesinator1");

        } while (nomb.length() == 0);

        if (nomb.equals("Asesinator1")
            || nomb.equals("Asesinator2")
            || nomb.equals("Asesinator3")
            || nomb.equals("Asesinator4")) {
          MenuCrearJuego.menu.mainAE(1, nomb, "PC");
          setVisible(false);
          return;
        }

        JLabel jPassword = new JLabel("porfavor ingrese la contraseña ");
        JTextField password = new JPasswordField();
        Object[] ob = {jPassword, password};

        int result =
            JOptionPane.showConfirmDialog(null, ob, "Contraseña", JOptionPane.OK_CANCEL_OPTION);

        String contraseNa = "";
        if (result == JOptionPane.OK_OPTION) {
          contraseNa = password.getText();
        }
        if (result == JOptionPane.CANCEL_OPTION) {
          return;
        }

        if (coleccion.estaRegistrado(contraseNa)) {
          MenuCrearJuego.menu.mainAE(1, nomb, "PC");
          setVisible(false);
        } else {
          JOptionPane.showMessageDialog(
              this,
              "No esta Registrado, usted debe registrarse previamente!",
              "ERROR",
              JOptionPane.ERROR_MESSAGE);
        }
      } catch (Exception exp) {
      }
      return;
    }
    if (dific == e.getSource()) {
      efectos.reproducirEfectoSonido("Klick");
      String nomb = "";
      PerfilesBD coleccion = new PerfilesBD();
      int numPer = 0;
      numPer = coleccion.numeroDePerfiles();
      Perfil perfilesMostrar[] = null;

      if (numPer == 0) {
        perfilesMostrar = new Perfil[4];

        for (int idx = 0; idx < 4; idx++) {
          perfilesMostrar[idx] =
              new Perfil("Asesinator" + (idx + 1), "predt" + (idx + 1) + ".jpg", "123" + idx);
          coleccion.agregarPerfil(perfilesMostrar[idx]);
        }
      }

      try {
        do {
          nomb =
              JOptionPane.showInputDialog(null, "Ingrese Nombre de Jugador Humano", "Asesinator1");

        } while (nomb.length() == 0);

        if (nomb.equals("Asesinator1")
            || nomb.equals("Asesinator2")
            || nomb.equals("Asesinator3")
            || nomb.equals("Asesinator4")) {
          MenuCrearJuego.menu.mainAE(2, nomb, "PC");
          setVisible(false);
          return;
        }

        JLabel jPassword = new JLabel("porfavor ingrese la contraseña ");
        JTextField password = new JPasswordField();
        Object[] ob = {jPassword, password};

        int result =
            JOptionPane.showConfirmDialog(null, ob, "Contraseña", JOptionPane.OK_CANCEL_OPTION);

        String contraseNa = "";
        if (result == JOptionPane.OK_OPTION) {
          contraseNa = password.getText();
        }
        if (result == JOptionPane.CANCEL_OPTION) {
          return;
        }

        if (coleccion.estaRegistrado(contraseNa)) {
          MenuCrearJuego.menu.mainAE(2, nomb, "PC");
          setVisible(false);
        } else {
          JOptionPane.showMessageDialog(
              this,
              "No esta Registrado, usted debe registrarse previamente!",
              "ERROR",
              JOptionPane.ERROR_MESSAGE);
        }
      } catch (Exception exp) {
      }
      return;
    }

    if (red == e.getSource()) {
      efectos.reproducirEfectoSonido("Klick");
      String nomb = "";
      PerfilesBD coleccion = new PerfilesBD();
      final PerfilesBD perfilesDB = coleccion;
      int numPer = 0;
      numPer = coleccion.numeroDePerfiles();
      Perfil perfilesMostrar[] = null;

      if (numPer == 0) {
        perfilesMostrar = new Perfil[4];

        for (int idx = 0; idx < 4; idx++) {
          perfilesMostrar[idx] =
              new Perfil("Asesinator" + (idx + 1), "predt" + (idx + 1) + ".jpg", "123" + idx);
          coleccion.agregarPerfil(perfilesMostrar[idx]);
        }
      }

      try {
        do {
          nomb =
              JOptionPane.showInputDialog(null, "Ingrese Nombre de Jugador Humano", "Asesinator1");

        } while (nomb.length() == 0);
        final String nomb2 = nomb;
        Perfil perfil = null;
        if (nomb.equals("Asesinator1")
            || nomb.equals("Asesinator2")
            || nomb.equals("Asesinator3")
            || nomb.equals("Asesinator4")) {
          if (nomb.equals("Asesinator1")) {
            if (coleccion.estaConectado("1230")) {
              JOptionPane.showMessageDialog(
                  this, "El perfil ya se encuentra en uso!", "ERROR", JOptionPane.ERROR_MESSAGE);
              return;
            }
          }
          if (nomb.equals("Asesinator2")) {
            if (coleccion.estaConectado("1231")) {
              JOptionPane.showMessageDialog(
                  this, "El perfil ya se encuentra en uso!", "ERROR", JOptionPane.ERROR_MESSAGE);
              return;
            }
          }
          if (nomb.equals("Asesinator3")) {
            if (coleccion.estaConectado("1232")) {
              JOptionPane.showMessageDialog(
                  this, "El perfil ya se encuentra en uso!", "ERROR", JOptionPane.ERROR_MESSAGE);
              return;
            }
          }
          if (nomb.equals("Asesinator4")) {
            if (coleccion.estaConectado("1233")) {
              JOptionPane.showMessageDialog(
                  this, "El perfil ya se encuentra en uso!", "ERROR", JOptionPane.ERROR_MESSAGE);
              return;
            }
          }

          if (nomb.equals("Asesinator1")) {
            coleccion.agregarConectado("1230");
          }
          if (nomb.equals("Asesinator2")) {
            coleccion.agregarConectado("1231");
          }
          if (nomb.equals("Asesinator3")) {
            coleccion.agregarConectado("1232");
          }
          if (nomb.equals("Asesinator4")) {
            coleccion.agregarConectado("1233");
          }

          if (!coleccion.estaMontadoServidor()) {

            int numJugadores = 2;
            boolean siga = false;
            do {
              try {
                numJugadores =
                    Integer.parseInt(
                        JOptionPane.showInputDialog(
                            this,
                            "señor jugador, por ser el primero en elegir juego en red,\n"
                                + " ha sido elegido como administrador de la partida,\n"
                                + " `por favor ingrese el numero de jugadores [2,50]"));
              } catch (Exception exp) {
                continue;
              }
              if ((numJugadores >= 2) && (numJugadores < 50)) {
                siga = true;
              }

            } while (!siga);

            cliente.enviarAdmi(numJugadores);
            coleccion.conectar_desconectarServidor(true, ipServer);
            JOptionPane.showMessageDialog(
                this,
                "se modifica el numero de jugadores de la clase Administrador : " + numJugadores);
          }
          MenuCrearJuego.menu.mainAE(1, nomb, "Red");
          MenuCrearJuego.menu.setCliente(cliente);
          setVisible(false);

          return;
        }

        JLabel jPassword = new JLabel("porfavor ingrese la contraseña ");
        JTextField password = new JPasswordField();
        Object[] ob = {jPassword, password};

        int result =
            JOptionPane.showConfirmDialog(null, ob, "Contraseña", JOptionPane.OK_CANCEL_OPTION);

        String contraseNa = "";
        if (result == JOptionPane.OK_OPTION) {
          contraseNa = password.getText();
        }
        if (result == JOptionPane.CANCEL_OPTION) {
          return;
        }

        if (coleccion.estaRegistrado(contraseNa)) {
          if (coleccion.estaConectado(contraseNa)) {
            JOptionPane.showMessageDialog(
                this, "El perfil ya se encuentra en uso!", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
          }

          coleccion.agregarConectado(contraseNa);

          if (!coleccion.estaMontadoServidor()) {

            int numJugadores = 2;
            boolean siga = false;
            do {
              try {
                numJugadores =
                    Integer.parseInt(
                        JOptionPane.showInputDialog(
                            this,
                            "señor jugador, por ser el primero en elegir juego en red,\n"
                                + " ha sido elegido como administrador de la partida,\n"
                                + " `por favor ingrese el numero de jugadores [2,50]"));
              } catch (Exception exp) {
                JOptionPane.showMessageDialog(
                    this, "Error de datos ", "Error", JOptionPane.ERROR_MESSAGE);
                continue;
              }
              if ((numJugadores >= 2) && (numJugadores < 50)) {
                siga = true;
              } else
                JOptionPane.showMessageDialog(
                    this, "Error de datos ", "Error", JOptionPane.ERROR_MESSAGE);

            } while (!siga);
            cliente.enviarAdmi(numJugadores);
            coleccion.conectar_desconectarServidor(true, ipServer);
          }
          MenuCrearJuego.menu.mainAE(1, nomb, "Red");
          MenuCrearJuego.menu.setCliente(cliente);
          setVisible(false);
        } else {
          JOptionPane.showMessageDialog(
              this,
              "No esta Registrado, usted debe registrarse previamente!",
              "ERROR",
              JOptionPane.ERROR_MESSAGE);
        }
      } catch (Exception exp) {
      }
      return;
    }

    if (salir == e.getSource()) {
      efectos.reproducirEfectoSonido("Klick");
      PerfilesBD coleccion = new PerfilesBD();
      // pregunta si de verdad se desea salir del juego
      int n =
          JOptionPane.showConfirmDialog(
              null,
              "Seguro que deseas SALIR?",
              "END GAME",
              JOptionPane.YES_NO_OPTION,
              JOptionPane.QUESTION_MESSAGE);

      if (n == JOptionPane.YES_OPTION) {
        System.exit(12);
      }
    }
  }
  public static int beginGUIConfigurationTransaction(String sConfigurationFileName, String sUser) {

    String sConfigurationLockFile;
    BufferedWriter bwBufferedWriter;
    File fFile;

    sConfigurationLockFile = new String(sConfigurationFileName + ".lck");

    System.out.println("beginGUIConfigurationTransaction: " + sConfigurationFileName);

    try {
      fFile = new File(URLDecoder.decode(sConfigurationLockFile, "UTF-8"));
    } catch (IOException e) {
      JOptionPane.showMessageDialog(
          null, "URLDecoder.decode failed", "ConfigurationTransaction", JOptionPane.ERROR_MESSAGE);

      return 1;
    }

    if (fFile.exists()) {
      BufferedReader brBufferedReader;
      char cLastConfigurationUser[];

      cLastConfigurationUser = new char[((int) fFile.length())];

      try {
        brBufferedReader =
            new BufferedReader(new FileReader(URLDecoder.decode(sConfigurationLockFile, "UTF-8")));
        brBufferedReader.read(cLastConfigurationUser, 0, (int) (fFile.length()));
        brBufferedReader.close();

        System.out.println(
            "Last configuration user: "******"Operation on BufferedWriter failed (1)",
            "ConfigurationTransaction",
            JOptionPane.ERROR_MESSAGE);

        return 1;
      }

      if (String.copyValueOf(cLastConfigurationUser).compareTo(sUser) == 0) {
        System.out.println("File. delete: " + sConfigurationFileName);

        if (fFile.delete() == false) {
          JOptionPane.showMessageDialog(
              null, "fFile.delete failed", "ConfigurationTransaction", JOptionPane.ERROR_MESSAGE);

          return 2;
        }
      } else {
        JOptionPane.showMessageDialog(
            null,
            "The configuration is locked by "
                + String.copyValueOf(cLastConfigurationUser)
                + ".\nYou cannot change the configuration.",
            "ConfigurationTransaction",
            JOptionPane.PLAIN_MESSAGE);

        return 3;
      }
    }

    try {
      bwBufferedWriter =
          new BufferedWriter(new FileWriter(URLDecoder.decode(sConfigurationLockFile, "UTF-8")));
      bwBufferedWriter.write(sUser, 0, sUser.length());
      bwBufferedWriter.close();

      System.out.println("Configuration user written: " + sUser);
    } catch (IOException e) {
      JOptionPane.showMessageDialog(
          null,
          "Operation on BufferedWriter failed (" + e + ")",
          "ConfigurationTransaction",
          JOptionPane.ERROR_MESSAGE);

      return 4;
    }

    return 0;
  }
  @Override
  public void run() { // client와 server간의 통신

    while (true) {
      try {
        String msg = in.readLine();
        System.out.println("Server=>" + msg);
        StringTokenizer st = new StringTokenizer(msg, "|");
        int protocol = Integer.parseInt(st.nextToken());
        switch (protocol) {
          case Function.YOURTURN: // 0.자기차례일 때 카드뒤집기 버튼활성화
            {
              gw.cardOpen.setBorderPainted(false);
              gw.cardOpen.setContentAreaFilled(false);
              gw.cardOpen.setEnabled(true);
            }
            break;
          case Function.DELROW: // 1.게임종료한 client 정보 접속자 List 에서 삭제
            {
              int rowIndex = (Integer.parseInt(st.nextToken())); // rowIndex=delIndex
              System.out.println("삭제 줄: " + rowIndex);
              wr.model2.removeRow(rowIndex); // 접속자리스트에서 삭제
            }
            break;
          case Function.CLIENTEXIT: // 2.waitRoom 채팅방에 00님이 나가셨습니다 전송
            {
              wr.ta.append(st.nextToken() + "\n");
              wr.bar.setValue(wr.bar.getMaximum());
            }
            break;
          case Function.MYLOG: // 1.window타이틀에 사용자이름 업데이트
            {
              String id = st.nextToken();
              setTitle(id);
              card.show(getContentPane(), "WR"); // waitingroom으로 창 전환
            }
            break;

          case Function.LOGIN: // 2.접속자테이블에 사용자 업데이트
            {
              String[] data = {st.nextToken(), st.nextToken()};

              wr.model2.addRow(data);
            }
            break;

          case Function.ROOMUSER: // 2.게임룸 유저테이블에 유저업데이트
            {
              System.out.println("In-ROOMUSER");
              String[] data = {st.nextToken()};
              gw.model1.addRow(data);
            }
            break;
          case Function.OUTUSER:
            {
              int rowIndex = (Integer.parseInt(st.nextToken())); // rowIndex=delIndex
              System.out.println("삭제 줄: " + rowIndex);
              gw.model1.removeRow(rowIndex);
            }

          case Function.WAITCHAT1: // 3.채팅할 때(waitroom)
            {
              wr.ta.append(st.nextToken() + "\n");
              wr.bar.setValue(wr.bar.getMaximum());
            }
            break;

          case Function.ROOMCHAT: // 3.채팅할 때(gameWindow)
            {
              gw.ta.append(st.nextToken() + "\n");
              gw.bar.setValue(gw.bar.getMaximum());
              validate();
            }
            break;

          case Function.NOTOVERLAP: // 4.ID가 중복되지 않을 때
            {
              JOptionPane.showMessageDialog(this, "ID가 중복되지 않습니다");
              mID.ck = true;
              mID.pf1.requestFocus();
            }
            break;

          case Function.OVERLAP: // 4.ID가 중복될 때
            {
              JOptionPane.showMessageDialog(this, "ID가 중복됩니다. 다시 입력하세요.");
              mID.ck = false;
              mID.pf1.requestFocus();
            }
            break;

          case Function.MAKEROOM: // 5.client가 방만들기 확인 버튼을 눌렀을 때(게임창 전환)
            {
              String roomId = st.nextToken(); // 게임룸 만든 사람 	id
              String roomName = st.nextToken(); // 새로 만든 게임룸의 	이름
              String humanNum = st.nextToken(); // 현재인원수	//아직 안쓰임
              String capaNum = st.nextToken(); // 최대인원수	//아직 안쓰임
              setTitle("방장_" + roomId + "    " + "방제_" + roomName);
              gw.b5.setEnabled(false); // 시작버튼 비활성화
              gw.ta.setText("");
              card.show(getContentPane(), "GW"); // 게임창으로 전환
            }
            break;

          case Function.ROOMINFORM: // 5.client가 방만들기 확인 버튼을 눌렀을 때(waitRoom의 리스트에 방 추가)
            {
              String roomType = st.nextToken(); // 공개비공개
              String roomName = st.nextToken(); // 게임룸의 이름
              String nnum = st.nextToken(); // 현재인원
              String num = st.nextToken(); // 최대인원
              String pos = st.nextToken(); // 방상태(게임대기중)
              String[] data = {roomType, roomName, nnum, num, pos};
              wr.model1.addRow(data); // waitRoom의 리스트에 방 추가						
              wr.repaint();
            }
            break;

          case Function.JOINROOM: // 6.방에 들어가기 했을 때(인원 수에따라 입장 가능 여부)
            {
              String result = st.nextToken();
              if (result.equals("TRUE")) {
                String roomMaker = st.nextToken();
                String roomName = st.nextToken();
                setTitle("방장_" + roomMaker + "    " + "방제_" + roomName);
                gw.b5.setEnabled(false); // 시작버튼 비활성화
                gw.tf.setText("");
                card.show(getContentPane(), "GW");
                // 준비버튼 활성화
                gw.b4.setEnabled(true);
                validate();
              } else {
                JOptionPane.showMessageDialog(this, "방이 꽉찼습니다.");
              }
            }
            break;

          case Function.ROOMREADY: // 6.준비버튼 눌렀을 때 버튼 비활성화
            {
              System.out.println("최종적으로 준비전달받음");
              gw.b4.setEnabled(false); // 준비버튼비활성화
            }
            break;

          case Function.ROOMREADYBUTTON: // 7.모두준비했을 때 방장만 시작 활성화
            {
              System.out.println("방장의 권한으로 시작버튼 활성화");
              gw.b5.setEnabled(true); // 준비버튼비활성화
            }
            break;
            //					  case Function.GAMESTART:			//7.모두준비했을 때 방장만 시작 활성화
            //					  {
            //						  System.out.println("방장의 권한으로 시작버튼 활성화");
            //						  gw.cardOpen.setBorderPainted(false);
            //							gw.cardOpen.setContentAreaFilled(false);
            //							gw.cardOpen.setEnabled(false);
            //
            //					  }
            //					  break;
            /*[방인원변경 ] ->*/
          case Function.CHGROOMUSER:
            {
              // 대기실 방 List table 의 특정 Row 의 방인원이 변경됨
              int row = Integer.parseInt(st.nextToken());
              String userNum = st.nextToken();
              wr.model1.setValueAt(userNum, row, 2);
              wr.repaint();
            }
            break;

            /*[유저상태변경] ->*/
          case Function.CHGUSERPOS:
            {
              int row = Integer.parseInt(st.nextToken()); // 방번호
              System.out.println("\\\\\\--->" + row);
              String pos = st.nextToken(); // 현재인원수
              wr.model2.setValueAt(pos, row, 1);
              wr.repaint();
            }
            break;

            /*[방상태변경 ] ->*/
          case Function.CHGROOMSTATE:
            {
              // 대기실 방 List table 의 특정 Row 의 방인원이 변경됨
              int row = Integer.parseInt(st.nextToken()); // 방번호
              String roomState = st.nextToken(); // 방상태
              wr.model1.setValueAt(roomState, row, 4);
              wr.repaint();
            }
            break;

            /*[방나가기] ->*/
          case Function.DELROOM: // 방에 사용자가 없에 방삭제 메시지 받음
            {
              gw.tf.setText("");
              int roomRow = Integer.parseInt(st.nextToken());
              System.out.println(roomRow + "방 삭제");
              wr.model1.removeRow(roomRow);
              wr.repaint();
            }
            break;
          case Function.REPAINT:
            {
              String tmpName = st.nextToken();
              int b = Integer.parseInt(st.nextToken());
              System.out.println("InREPAIT-ID:" + tmpName + "Number:" + b);
              gw.UpdateDraw(tmpName, b);
            }
            break;
          case Function.CARDNUM:
            {
              String tmpName = st.nextToken(); // id
              int b = Integer.parseInt(st.nextToken()); // 카드수
              System.out.println("InCARDNUM-ID:" + tmpName + "Number:" + b);
              gw.UpdateCardNum(tmpName, b);
            }
            break;
          case Function.DEAD:
            {
              gw.ta.append("당신은 죽었습니다.\n");
              gw.bell.setEnabled(false);
              gw.cardOpen.setEnabled(false);
            }
            break;
          case Function.UPDATEDEAD:
            {
              String tmpName = st.nextToken();
              gw.ta.append(tmpName + " 님이 죽었습니다.\n");
              gw.UpdateDead(tmpName);
              validate();
            }
            break;
          case Function.BELLSUCCESS:
            {
              String tmpName = st.nextToken();
              gw.ta.append(tmpName + " 님이 종치기 성공했습니다.\n");
              gw.bell.setEnabled(true);
              gw.CardInit();
            }
            break;

          case Function.BELLFAIL:
            {
              String tmpName = st.nextToken();
              gw.ta.append(tmpName + "님이 종치기 실패하였습니다.\n");
              gw.bell.setEnabled(true);
              validate();
            }
            break;

          case Function.BELL:
            {
              gw.bell.setEnabled(false);
            }
            break;

          case Function.TURNINFO:
            {
              gw.userName[0] = st.nextToken();
              gw.userName[1] = st.nextToken();
              gw.userName[2] = st.nextToken();
              gw.userName[3] = st.nextToken();
            }
            break;
          case Function.EXITFALSE: // 게임시작시 나가기비활성화
            {
              gw.b6.setEnabled(false);
            }
            break;

          case Function.IDLABEL: // 게임시작시 id라벨 입력
            {
              String ID = st.nextToken(); // id
              for (int i = 0; i < 4; i++) {
                if (ID.equals(gw.userName[i])) {
                  gw.laPlayer[i].setText("Player" + (i + 1) + ": " + ID);
                }
              }
            }
            break;
          case Function.GAMEEXIT:
            {
              System.out.println("zzzzz");
              String tmpId = st.nextToken();
              String tmpMsg = st.nextToken();
              gw.ta.append("게임종료=====>" + tmpId + tmpMsg);
              gw.b4.setEnabled(true);
              gw.b6.setEnabled(true);
              gw.CardInit();
            }
            break;
        }
      } catch (Exception ex) {
        validate();
      }
      validate();
    }
  }
Exemple #29
0
  public int Clicked(ChessBoard cel) {
    int judge = 0;
    int r = cel.getRow();
    int c = cel.getColumn();
    System.out.println("落子前:" + cell[3][5].taken);

    if (gameStart) {
      if (cel.taken == false) {
        Check(cel);
      }
      System.out.println(cell[3][5].taken);
      System.out.println(can);
      if (can && cel.taken == false) {
        /*for (int i = 0; i < 8; i++)
        for (int j = 0; j < 8; j++)
        if (cell[i][j].changed == true)
        {
        	cell[i][j].ChangeBack();
        }*/
        RememberState();
        ShowChessNumber();
        list.add(cel);
        JudgeWhoIsWinner();
        turn = TakeTurn();
        cel.taken = true;
        System.out.println("落子后:" + cell[3][5].taken);
        can = false;
        judge = 1;
        for (int i = 0; i < 8; i++)
          for (int j = 0; j < 8; j++)
            if (cell[i][j].changed) {
              cell[i][j].ChangeBack();
            }

        boolean flag = CheckAll();
        if (!flag && white + black < 64) CheckAtTheEnd();
        /*else
        {
        	for (int i = 0; i < 8; i++)
        	for (int j = 0; j < 8; j++)
        	if (cell[i][j].taken == false)
        	{
        		CheckPlace(cell[i][j]);
        		if (canPut)
        		{
        			cell[i][j].ChangeBackground();
        			canPut = false;
        		}
        	}
        }*/
      } else {
        JOptionPane.showMessageDialog(null, "无法在该位置落子");
        judge = 0;
        System.out.println(cell[3][5].taken);
      }
      return judge;
    } else {
      JOptionPane.showMessageDialog(null, "游戏还未开始或已结束");
      return 0;
    }
  }
Exemple #30
0
 @Override
 public void actionPerformed(ActionEvent e) {
   if (e.getActionCommand().equals("下棋")) {
     audience.setEnabled(false);
     fighter.setEnabled(false);
     begin.setEnabled(true);
     //			JOptionPane.showMessageDialog(null, "下棋");
     System.out.println("下棋");
     try {
       System.out.println("客户端发送下棋指令");
       out66.writeObject("对手");
       out66.flush();
       out66.writeObject(new char[0][0]);
       out66.flush();
       out66.writeObject(new boolean[0][0]);
       out66.flush();
     } catch (IOException e1) {
       e1.printStackTrace();
     }
   }
   if (e.getActionCommand().equals("观看")) {
     submit.setEnabled(false);
     regret.setEnabled(false);
     audience.setEnabled(false);
     fighter.setEnabled(false);
     //			JOptionPane.showMessageDialog(null, "观看");
     System.out.println("观看");
     try {
       out66.writeObject("观众");
       out66.flush();
       out66.writeObject(stateList.get(stateList.size() - 1));
       out66.flush();
       out66.writeObject(takenList.get(takenList.size() - 1));
       out66.flush();
     } catch (IOException e1) {
       e1.printStackTrace();
     }
   }
   /*if (e.getActionCommand().equals("人机对弈"))
   {
   	audience.setEnabled(false);
   	fighter.setEnabled(false);
   	AIPlayer.setEnabled(false);
   	begin.setEnabled(true);
   	JOptionPane.showMessageDialog(null, "人机对弈");
   }*/
   if (e.getActionCommand().equals("发送")) {
     //			JOptionPane.showMessageDialog(null, "发送");
     System.out.println("发送");
     String str = myRole + ": " + " " + jt1.getText() + "\n";
     try {
       out99.writeObject(" " + str);
       out99.flush();
       out99.writeObject(new char[8][8]);
       out99.flush();
       out99.writeObject(new boolean[8][8]);
       out99.flush();
     } catch (IOException e1) {
       e1.printStackTrace();
     }
     jt2.append(str);
     jt1.setText("");
   }
   if (e.getActionCommand().equals("取消")) {
     //			JOptionPane.showMessageDialog(null, "取消");
     System.out.println("取消");
     jt1.setText("");
   }
   if (e.getActionCommand().equals("悔棋")) {
     //			JOptionPane.showMessageDialog(null, "悔棋");
     System.out.println("悔棋");
     try {
       out66.writeObject("请求悔棋");
       out66.flush();
       out66.writeObject(new char[8][8]);
       out66.flush();
       out66.writeObject(new boolean[8][8]);
       out66.flush();
     } catch (IOException e1) {
       e1.printStackTrace();
     }
     // RegretChess();
     // ShowChessNumber();
   }
   if (e.getActionCommand().equals("退出")) {
     int quit =
         JOptionPane.showConfirmDialog(null, "您确定要强制退出吗?", "请确认您的选择", JOptionPane.YES_NO_OPTION);
     if (quit == JOptionPane.YES_OPTION) {
       JOptionPane.showMessageDialog(null, "已强制退出");
       System.exit(0);
     } else return;
   }
   if (e.getActionCommand().equals("开始")) {
     begin.setEnabled(false);
     System.out.println("客户端发送开始指令");
     //			JOptionPane.showMessageDialog(null, "开始");
     try {
       out66.writeObject("请求开始");
       out66.flush();
       out66.writeObject(stateList.get(stateList.size() - 1));
       out66.flush();
       out66.writeObject(takenList.get(takenList.size() - 1));
       out66.flush();
     } catch (IOException e1) {
       e1.printStackTrace();
     }
     Begin();
     if (kind == "黑") {
       for (int i = 0; i < 8; i++)
         for (int j = 0; j < 8; j++)
           if (cell[i][j].taken == false) {
             CheckPlace(cell[i][j]);
             if (canPut) {
               cell[i][j].ChangeBackground();
               canPut = false;
             }
           }
     }
   }
   if (e.getActionCommand().equals("存盘")) {
     //			JOptionPane.showMessageDialog(null, "存盘");
     System.out.println("存盘");
     try {
       System.out.println();
       out.writeObject(stateList);
       out.flush();
       out.close();
     } catch (IOException e1) {
       e1.printStackTrace();
     }
   }
 }