示例#1
0
 public static void release(int x, int y, int button) {
   int buttonModifiers = getButtonModifiers(button);
   Component target = getTarget();
   Client.getMouse()
       .sendEvent(
           new MouseEvent(
               target,
               MouseEvent.MOUSE_RELEASED,
               System.currentTimeMillis(),
               buttonModifiers,
               x,
               y,
               1,
               false,
               button));
   isPressed = false;
   Client.getMouse()
       .sendEvent(
           new MouseEvent(
               target,
               MouseEvent.MOUSE_CLICKED,
               System.currentTimeMillis(),
               buttonModifiers,
               x,
               y,
               1,
               false,
               button));
 }
  // calculate the coordinates of the startpoint (endpoint) if parameter is
  // true (false) of the arrow when drawing this link
  private Point calcCoord(boolean startpoint) {
    if (!startpoint && (end == null)) return openEnd;

    int deltaX;
    int deltaY;

    if (end == null) {
      deltaX = start.getX() - openEnd.x;
      deltaY = start.getY() - openEnd.y;
    } else {
      deltaX = start.getX() - end.getX();
      deltaY = start.getY() - end.getY();
    }

    double dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY);

    double prop = (Client.RADIUS) / dist;

    int offsetX = (int) Math.round(deltaX * prop);
    int offsetY = (int) Math.round(deltaY * prop);

    if (startpoint) {
      return new Point(start.getX() - offsetX, start.getY() - offsetY);
    } else return new Point(end.getX() + offsetX, end.getY() + offsetY);
  }
 public String toString() {
   if (end == null) {
     return new String("Open link starting in " + start.getName());
   } else {
     return new String("Link between " + start.getName() + " and " + end.getName());
   }
 }
示例#4
0
  /** The listener method. */
  public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();

    if (source == b1) // click button
    {
      try {
        String message = tf.getText();
        server.sendPrivateMessage(parent, selfIdentity, message);
        ta.append("<" + parent.getUserName() + ">: " + message + lineSeparator);
        ta.setCaretPosition(ta.getText().length());
        tf.setText("");
      } catch (RemoteException ex) {
        System.out.print("Exception encountered while sending" + " private message.");
      }
    }

    if (source == tf) // press return
    {
      try {
        String message = tf.getText();
        server.sendPrivateMessage(parent, selfIdentity, message);
        ta.append("<" + parent.getUserName() + ">: " + message + lineSeparator);
        ta.setCaretPosition(ta.getText().length());
        tf.setText("");
      } catch (RemoteException ex) {
        System.out.print("Exception encountered while sending" + " private message.");
      }
    }
    if (source == jMenuItem3) {
      JFileChooser fileChooser = new JFileChooser();

      fileChooser.setDialogTitle("Choose or create a new file to store the conversation");
      fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
      fileChooser.setDoubleBuffered(true);

      fileChooser.showOpenDialog(this);

      File file = fileChooser.getSelectedFile();

      try {
        if (file != null) {

          Writer writer = new BufferedWriter(new FileWriter(file));

          writer.write(ta.getText());
          writer.flush();
          writer.close();
        }
      } catch (IOException ex) {
        System.out.println("Can't write to file. " + ex);
      }
    }
    if (source == jMenuItem4) {
      selfRemove();
      this.dispose();
    }
  }
 /**
  * This method updates the relevant sections of the GUI when a new LookReply and RenderHint are
  * received from the server.
  */
 public void updateGUI(char[][] newCells, String[] newRenderHint, boolean ourTurn) {
   char[] playerDirections = processRenderHint(newRenderHint);
   boolean hasLantern = (newCells[0].length == 7); // the size of the lookreply determines whether
   // the player has a lantern
   dungeonPanel.updateCells(newCells, hasLantern, playerDirections); // updates the map panel
   int goldHeld = client.getGoldHeld();
   int goldNeeded = client.getGoldNeeded();
   dungeonPanelOverlay.updateOverlay(hasLantern, ourTurn, goldHeld, goldNeeded);
   // updates the overlay
 }
  // send a packet
  public int send(DatagramPacket p, Client sender, EmuSocket socket) {
    boolean sentSomething = false;

    Client receiver = getReceiver(sender);

    if (receiver == null) throw new RuntimeException("ERROR: send() called on wrong link");

    Vector receiverSockets = receiver.getSockets();

    if (!this.isNextPacketDeliverable()) {
      return Link.PACKET_LOST;
    }

    for (Iterator iter = receiverSockets.iterator(); iter.hasNext(); ) {
      EmuSocket curSocket = (EmuSocket) iter.next();

      if (curSocket.getGroups().contains(p.getAddress())) {
        // send the packet to the socket
        curSocket.receivePacket(p, this.getDelay());
        sentSomething = true;
      }
    }

    if (sentSomething) {
      if (Options.flashTime != 0) {
        // adjust color of arrow (-> flashing)
        if (receiver == this.start) {
          // change the color of the link
          if (flashThreadStart == null || !flashThreadStart.isAlive()) {
            flashThreadStart = new FlashLinkThread(true);
            flashThreadStart.start();
          } else {
            flashThreadStart.reset();
          }
        } else {
          // change the color of the link
          if (flashThreadEnd == null || !flashThreadEnd.isAlive()) {
            flashThreadEnd = new FlashLinkThread(false);
            flashThreadEnd.start();
          } else {
            flashThreadEnd.reset();
          }
        }
      }

      return Link.PACKET_SENT;
    } else {
      return Link.NO_GROUP_MEMBER;
    }
  }
  // returns the endpoint which is closer to (x,y) than the other one
  public Client getPointNear(int x, int y) {
    if (start == null || end == null)
      throw new RuntimeException("ERROR: getPointNear() not allowed on open links");

    int distToStart = (int) Math.pow(start.getX() - x, 2) + (int) Math.pow(start.getY() - y, 2);

    int distToEnd = (int) Math.pow(end.getX() - x, 2) + (int) Math.pow(end.getY() - y, 2);

    if (distToStart < distToEnd) {
      return start;
    } else {
      return end;
    }
  }
示例#8
0
文件: Chat.java 项目: brgj/Tales
 /**
  * Send a message to the client
  *
  * @return true if message is not empty
  */
 public boolean sendMessage() {
   if (messageToSend.length() == 0) return false;
   client.sendMessage(messageToSend.toString());
   addMessageToLog("You: " + messageToSend.toString());
   messageToSend.delete(0, messageToSend.length());
   return true;
 }
示例#9
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) {
   }
 }
示例#10
0
  public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_ESCAPE && gamerunner.running) {

      Graphics gr = this.getGraphics();
      gr.setFont(new Font("TimesRoman", Font.PLAIN, 40));
      gr.drawString("PAUSE", (int) this.getWidth() / 2, this.getHeight() / 2);
      if (!online) {
        gamerunner.running = false;
      }
      if (soundan) {} // end of if
      Menu menu = new Menu(this);
      // volume.setValue(vol);
    } else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
      gamerunner.running = true;
      if (soundan) {} // end of if
    } // end of if-else
    else if (e.getKeyCode() == KeyEvent.VK_R && !online) {
      restartGame();
    } else if (e.getKeyCode() == KeyEvent.VK_F11) {
      dispose();
      setUndecorated(true);
      String[] arguments = {"fullscreen"};
      new JavaGame(arguments);
    } else if (e.getKeyCode() == KeyEvent.VK_ENTER && online) {
      String message =
          JOptionPane.showInputDialog(null, "Chat", "Nachricht", JOptionPane.PLAIN_MESSAGE);
      try {
        if (!message.isEmpty()) {
          client.sendNewChatMessage(player[client.id].name, message);
        }
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
示例#11
0
文件: Chat.java 项目: brgj/Tales
  /** Poll the client for a message, add it to the log if not null */
  private void getMessageFromClient() {
    String rec = client.receiveMessage();

    if (rec != null) {
      addMessageToLog(rec);
    }
  }
示例#12
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();
 }
  // get the delay of the next packet
  public int getDelay() {
    switch (delayType) {
      case NO_DELAY:
        return 0;

      case CONST_DELAY:
        return constDelayMs;

      case DIST_DELAY:
        // calculate distance between start and end node
        int x = start.getX() - end.getX();
        int y = start.getY() - end.getY();
        float dist = (float) Math.sqrt(x * x + y * y);
        return (int) (dist * distDelayFactor);

      default:
        throw new RuntimeException("ERROR: Illegal delay type " + delayType);
    }
  }
示例#14
0
 public static void move(int x, int y) {
   Component target = getTarget();
   MouseEvent last = null;
   for (MouseEvent me : createPath(target, MousePathGenerator.generatePath(x, y))) {
     Client.getMouse().sendEvent(me);
     long lag = Math.max(0, mouseSpeed - 2 + new Random().nextInt(4));
     if (last != null) lag = me.getWhen() - last.getWhen();
     sleep(lag);
   }
   currentPath = new MouseEvent[] {};
 }
  // returns true if (x,y) is close to the link
  public boolean intersects(int x0, int y0) {

    if (end == null) throw new RuntimeException("ERROR: intersect() not allowed on open links");

    int x1, x2, y1, y2;

    x1 = start.getX();
    x2 = end.getX();
    y1 = start.getY();
    y2 = end.getY();

    // calculate the distance between the direct start-end connection and the point
    double o = Math.abs((x2 - x1) * (y1 - y0) - (x1 - x0) * (y2 - y1));
    double u = Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2));

    if ((o / u) < INTERSECTION_DISTANCE) {
      return true;
    }

    return false;
  }
示例#16
0
  public static void main(String argv[]) {

    if (argv.length != 1) {
      System.out.println("java Irc <name>");
      return;
    }
    myName = argv[0];

    // initialize the system
    Client.init();

    // look up the IRC object in the name server
    // if not found, create it, and register it in the name server
    Sentence_itf s = (Sentence_itf) Client.lookup("IRC");
    if (s == null) {
      s = (Sentence_itf) Client.create(new Sentence());
      Client.register("IRC", s);
    }
    // create the graphical part
    new Irc(s);
  }
示例#17
0
 public static void drag(int x, int y) {
   Component mouseTarget = Data.CLIENT_APPLET.getComponent(0);
   Component mouseMotionTarget = mouseTarget;
   MouseEvent[] me =
       createDragPath(
           mouseMotionTarget, mouseTarget, MousePathGenerator.generatePath(x, y), LEFT_BUTTON);
   isPressed = true;
   for (int i = 0; i < me.length; ++i) {
     Client.getMouse().sendEvent(me[i]);
     sleep(Math.max(0, mouseSpeed - 2 + new Random().nextInt(4)));
   }
   isPressed = false;
 }
  /**
   * @param friends the Client the Plugin belongs to
   * @param starter is true if the Clients started the plugin (start() will be called instead of
   *     follow()
   * @return a new instance of the Plugin.
   */
  public Plugin newInstance(ConnectInfo[] friends, boolean starter) {
    QuickLaunch self = new QuickLaunch();

    try {
      self.trayIcon =
          new TrayIcon(
              this.getImageIcon16(),
              Client.getInstance().getMyInfos().getName() + " - Lucane Groupware");
    } catch (Throwable t) {
      self.trayIcon = null;
    }

    return self;
  }
示例#19
0
 public static void enter(int x, int y) {
   Component target = getTarget();
   MouseEvent me =
       new MouseEvent(
           target,
           MouseEvent.MOUSE_ENTERED,
           System.currentTimeMillis(),
           0,
           x,
           y,
           0,
           false,
           MouseEvent.NOBUTTON);
   Client.getMouse().sendEvent(me);
 }
  /** Show a dialog asking for the friend name */
  public void start() {
    if (this.trayIcon == null) {
      // no user message if we aren't on windows
      if (System.getProperty("os.name").startsWith("Win")) DialogBox.error(tr("err.noTray"));
      else Logging.getLogger().info("Not on windows, running MainInterface instead of QuickLaunch");

      PluginManager.getInstance().run(MAIN_INTERFACE, new ConnectInfo[0]);
      Client.getInstance().setStartupPlugin(MAIN_INTERFACE);
      return;
    }

    addMenuToTray();

    this.trayIcon.addMouseListener(this);
    this.trayIcon.setVisible(true);
    this.trayIcon.showInfo(tr("lucane.is.ready"), "Lucane Groupware");
  }
示例#21
0
 public static void press(int x, int y, int button) {
   int buttonModifiers = getButtonModifiers(button);
   Component target = getTarget();
   Client.getMouse()
       .sendEvent(
           new MouseEvent(
               target,
               MouseEvent.MOUSE_PRESSED,
               System.currentTimeMillis(),
               buttonModifiers,
               x,
               y,
               1,
               false,
               button));
   isPressed = true;
 }
示例#22
0
  /** the constructor */
  public PrivateClient(Client parent, ClientInterface selfIdentity) throws RemoteException {
    super(parent.getUserName() + " in private session with " + selfIdentity.getUserName());

    this.parent = parent;
    this.selfIdentity = selfIdentity;

    this.server = this.parent.getClassServer();

    this.addWindowListener(
        new WindowAdapter() {
          public void windowClosing(WindowEvent ev) {
            selfRemove();
            ev.getWindow().dispose();
          }
        });

    initComponents();
    lineSeparator = System.getProperty("line.separator");
  }
示例#23
0
 /**
  * This method handles the client pressing the Connect button. It catches the possible errors if
  * there were any, and connects the player to the server if there were none.
  */
 public void connectToServer() {
   String hostname = serverSettings.hostnameField.getText();
   String portNum = serverSettings.portNumField.getText();
   String playerName = serverSettings.playerNameField.getText();
   try {
     client = new Client(hostname, portNum, this);
     if (!playerName.equals("")) {
       client.sendHello(playerName);
     } // if no name was entered, the server will pick a default so we don't send HELLO
     toggleGUIStates(true); // let the GUI know we're now connected
     dungeonPanel.requestFocusInWindow(); // set the focus on the DungeonPanel so its KeyListeners
     // work without a click from the user
   } catch (NumberFormatException e) {
     showErrorMessage("Could not connect", "Invalid port number.");
   } catch (IOException e) { // if the server isn't available, because eg it is currently offline
     // or a mistake in the hostname/port number was made
     String errorMessage = "The server at " + hostname + ":" + portNum + " could not be reached.";
     showErrorMessage("Could not connect", errorMessage);
   }
 }
  private void runPlugin(String pluginName) {
    ConnectInfo[] friends = null;
    Plugin plugin = PluginManager.getInstance().getPlugin(pluginName);

    // get users
    if (plugin.isStandalone()) friends = new ConnectInfo[0];
    else {
      ListBox userList =
          new ListBox(
              null, plugin.getTitle(), tr("msg.selectUsers"), Client.getInstance().getUserList());
      Object[] users = userList.selectItems();
      if (users != null) {
        friends = new ConnectInfo[users.length];
        for (int i = 0; i < friends.length; i++)
          friends[i] = Communicator.getInstance().getConnectInfo((String) users[i]);
      }
    }

    // run the plugin if the user didn't click on cancel
    if (friends != null) PluginManager.getInstance().run(pluginName, friends);
  }
 public String getBaseConfig(String username) {
   client.sendUDP("getBase~" + username);
   return client.receiveUDP();
 }
 public String getBaseConfig() {
   client.sendUDP("getBase~" + unameUDP);
   return client.receiveUDP();
 }
  public void actionPerformed(ActionEvent e) {
    Object o = e.getSource();

    for (JRadioButton u : ub) {
      if (o == u) {
        mapTM.setUnitType(u.getText());
        System.out.println("Set unit type - " + u.getText());
        return;
      }
    }

    if (o == timer) {

      /*
      mmLabel.setText("Main Menu ("+(cdTime--)+")");

      if(cdTime == 0){
      	timer.stop();
      	gsButton.setText("Game Start");
      	mmLabel.setText("Main Menu");

      	ArrayList<Building> bArr = new ArrayList<Building>();

      	String temp = "Elixir Collector-24,8-960|Elixir Collector-31,8-960|Gold Mine-17,10-960|Elixir Collector-25,21-960|Elixir Collector-11,22-960";
      	String[] bs = temp.split("\\|");
      	for(String b : bs){
      		String[] bParts = b.split("-");
      		String[] cParts = bParts[1].split(",");
      		int x = Integer.parseInt(cParts[0].trim());
      		int y = Integer.parseInt(cParts[1].trim());

      		Building tb = new Building(bParts[0], new Coordinate(x,y));
      		tb.setHp(Integer.parseInt(bParts[2].trim()));

      		bArr.add(tb);
      	}



      	mapTM.setBuildings(bArr);
      	switchCards("TM");
      }
      */

      return;
    }

    if (o == gsButton) {

      if (timer.isRunning()) {
        // timer.stop();
        gsButton.setText("Game Start");
        mmLabel.setText("Main Menu");
        // sends the leave command
        client.sendUDP("leave~" + unameUDP);
        return;
      }
      // sends the joinlobby command
      client.sendUDP("joinlobby~" + unameUDP);
      // gsButton.setText("Game Stop");
      String serverResp = client.receiveUDP();

      if (serverResp.trim().equals("false")) {

        // place false handler here

      } else {

        String[] enemies = serverResp.trim().split(",");
        ArrayList<Building> bArr = new ArrayList<Building>();
        String mapConfig = getBaseConfig(enemies[0]);
        String[] bs = mapConfig.split("\\|");
        for (String b : bs) {

          String[] bParts = b.split("-");
          String[] cParts = bParts[1].split(",");
          int x = Integer.parseInt(cParts[0].trim());
          int y = Integer.parseInt(cParts[1].trim());

          Building tb = new Building(bParts[0], new Coordinate(x, y));
          tb.setHp(Integer.parseInt(bParts[2].trim()));
          bArr.add(tb);
        }

        mapTM.setBuildings(bArr);
        switchCards("TM");
      }

      // System.out.println(serverResp);
      // cdTime = 10;
      // timer.start();
      return;
    }

    if (o == logout) {
      client.sendMessage(new ChatMessage(ChatMessage.LOGOUT, ""));
      chatArea.setText("");

      switchCards("Login");
      return;
    }

    if (o == cmButton) {
      String baseConfig = getBaseConfig();
      System.out.println("base config: " + baseConfig);

      for (int i = 0; i < mapSize; i++) {
        for (int j = 0; j < mapSize; j++) {
          tiles[i][j].setValue("");
        }
      }

      if (!baseConfig.equals("")) {

        String[] bs = baseConfig.split("\\|");
        for (String b : bs) {
          String[] bParts = b.split("-");
          String[] cParts = bParts[1].split(",");
          int x = Integer.parseInt(cParts[0].trim());
          int y = Integer.parseInt(cParts[1].trim());

          int index = 0;
          for (int i = 0; i < bb.size(); i++) {
            if (bb.get(i).getText().split("-")[0].trim().equals(bParts[0])) {
              index = i;
              break;
            }
          }
          insertBuilding(y, x, index);
        }
      }

      switchCards("CM");

      return;
    }

    if (o == tmButton) {

      ArrayList<Building> bArr = new ArrayList<Building>();

      for (int i = 0; i < 40; i++) {
        for (int j = 0; j < 40; j++) {
          if (tiles[i][j].getValue().equals("") || tiles[i][j].getValue().contains("-")) {
            continue;
          }
          // weird part here
          bArr.add(new Building(tiles[i][j].getValue(), new Coordinate(j, i)));
        }
      }

      mapTM.setBuildings(bArr);

      switchCards("TM");
      return;
    }

    // if it the who is in button
    if (o == whoIsIn) {
      client.sendMessage(new ChatMessage(ChatMessage.WHOISIN, ""));
      return;
    }

    if (o == cmBack) {
      ArrayList<Building> bArr = new ArrayList<Building>();
      for (int i = 0; i < 40; i++) {
        for (int j = 0; j < 40; j++) {
          if (tiles[i][j].getValue().equals("") || tiles[i][j].getValue().contains("-")) {
            continue;
          }
          // weird part here
          bArr.add(new Building(tiles[i][j].getValue(), new Coordinate(j, i)));
        }
      }

      String temp = "mapdata~" + unameUDP + "~";
      int tileCount = 40;
      int dim = 600;
      int tileDim = (int) (dim / tileCount);
      int counter = 0;
      for (Building b : bArr) {
        int x, y, hp;
        x = b.getPos().getX() / tileDim;
        y = b.getPos().getY() / tileDim;
        hp = b.getHp();
        temp += b.getName() + "-" + x + "," + y + "-" + hp + "|";
        counter += 1;
      }
      if (counter > 0) {
        temp = temp.substring(0, temp.length() - 1); // removes the last '|'
      } else {
        temp += "none";
      }

      client.sendUDP(temp); // allows saving of the current state of the map into the user's account

      switchCards("Menu");

      return;
    }
    if (o == tmBack) {
      switchCards("Menu");

      return;
    }

    for (int i = 0; i < 40; i++) {
      for (int j = 0; j < 40; j++) {
        if (o == tiles[i][j]) {
          for (int k = 0; k < bb.size(); k++) {
            if (bb.get(k).isSelected()) {
              if (bb.get(k).getText().equals("Remove Building")) {
                removeBuilding(i, j);
                return;
              }

              insertBuilding(i, j, k);
              // JOptionPane.showMessageDialog(null, bb.get(k).getText());
              return;
            }
          }

          // JOptionPane.showMessageDialog(null, "i-"+i+" j-"+j);
          return;
        }
      }
    }

    // ok it is coming from the JTextField
    if (connected) {
      // just have to send the message
      client.sendMessage(new ChatMessage(ChatMessage.MESSAGE, chatField.getText()));
      chatField.setText("");
      return;
    }

    if (o == login) {
      // ok it is a connection request
      String username = usernameField.getText().trim();
      String password = passwordField.getText().trim();
      // empty username ignore it
      if (username.length() == 0) return;
      // empty serverAddress ignore it
      String server = tfServer.getText().trim();
      if (server.length() == 0) return;
      // empty or invalid port numer, ignore it
      String portNumber = tfPort.getText().trim();
      if (portNumber.length() == 0) return;
      int port = 0;
      try {
        port = Integer.parseInt(portNumber);
      } catch (Exception en) {
        return; // nothing I can do if port number is not valid
      }

      // try creating a new Client with GUI
      client = new Client(server, port, username, password, this);
      // test if we can start the Client
      if (!client.start()) return;

      unameUDP = username;

      switchCards("Menu");
      // fetching of the base_config string from the database

      chatField.setText("");
      chatArea.setText("");
    }
  }
示例#28
0
 /**
  * This method sends the message typed into the chat box to the Client class to be sent to the
  * server as a SHOUT.
  */
 public void sendMessage() {
   String message = chatPanel.getMessage();
   if (!message.equals("")) {
     client.sendShout(message);
   }
 }
示例#29
0
 /**
  * This method makes the client send LOOK whenever the server sends the CHANGE message. This
  * allows the client to be able to see changes caused by other players in real time.
  */
 public void mapChanged() {
   client.sendLook();
 }
示例#30
0
 /**
  * This method interfaces between the key listener for the player pressing E and the client
  * sending the appropriate message.
  */
 public void sendPickup() {
   client.sendPickup();
 }