예제 #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 initGame(Pane gameRoot) {
    initNetworking();

    player1.setPosition(100, 100);
    player1.setGraphics(new Rectangle(40, 40));

    player2.setPosition(500, 500);
    player2.setGraphics(new Rectangle(40, 40));

    addEntities(player1, player2);
  }
예제 #3
0
  private void initPlayer() {
    player = new Entity(Type.PLAYER);
    player.setPosition(0, getHeight() / 3);
    player.setCollidable(true);

    playerSprite = buildSpriteSheet();
    playerSprite.getTransforms().setAll(new Scale(0.25, 0.25));

    player.setSceneView(playerSprite);

    getGameWorld().addEntity(player);
  }
예제 #4
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));
    }
  }