コード例 #1
0
 @Override
 protected void initInput() {
   if (isHost) {
     addKeyPressBinding(
         KeyCode.W,
         () -> {
           player1.translate(0, -5);
         });
     addKeyPressBinding(
         KeyCode.S,
         () -> {
           player1.translate(0, 5);
         });
     addKeyPressBinding(
         KeyCode.A,
         () -> {
           player1.translate(-5, 0);
         });
     addKeyPressBinding(
         KeyCode.D,
         () -> {
           player1.translate(5, 0);
         });
   } else {
     initKeys(KeyCode.W, KeyCode.S, KeyCode.A, KeyCode.D, KeyCode.ESCAPE);
   }
 }
コード例 #2
0
  @Override
  protected void onUpdate(long now) {
    if (isHost) {
      if (!isConnected) return;

      RequestMessage data = requestQueue.poll();
      if (data != null) {
        for (KeyCode key : data.keys) {
          if (key == KeyCode.W) {
            player2.translate(0, -5);
          } else if (key == KeyCode.S) {
            player2.translate(0, 5);
          } else if (key == KeyCode.A) {
            player2.translate(-5, 0);
          } else if (key == KeyCode.D) {
            player2.translate(5, 0);
          } else if (key == KeyCode.ESCAPE) {
            exit();
          }
        }
      }

      try {
        server.send(
            new DataMessage(
                player1.getTranslateX(),
                player1.getTranslateY(),
                player2.getTranslateX(),
                player2.getTranslateY()));
      } catch (Exception e) {
        log.warning("Failed to send message: " + e.getMessage());
        exit();
      }
    } else {
      DataMessage data = updateQueue.poll();
      if (data != null) {
        player1.setPosition(data.x1, data.y1);
        player2.setPosition(data.x2, data.y2);
      }

      KeyCode[] codes =
          keys.keySet()
              .stream()
              .filter(k -> keys.get(k))
              .collect(Collectors.toList())
              .toArray(new KeyCode[0]);

      try {
        client.send(new RequestMessage(codes));

        if (keys.get(KeyCode.ESCAPE)) {
          exit();
        }
      } catch (Exception e) {
        log.warning("Failed to send messsage: " + e.getMessage());
        exit();
      }

      keys.forEach((key, value) -> keys.put(key, false));
    }
  }