簡體   English   中英

如何在Java服務器中發送點(x,y)?

[英]How can i send a point (x,y) in a server in java?

我正在嘗試將Skor4游戲(最多兩名玩家)更改為井字游戲。 問題在於,在我嘗試更改的源代碼中,僅將球的x維度發送到服務器,然后其他玩家采用該x維度並找到y維度。 就我而言,我想同時發送x和y維。 我怎樣才能做到這一點??

玩家玩時:

else if (myMove) {
  Point pos = gameEngine.makeMove(0, x/160, y/162);//
  if (pos.y >= 0) {
    if (!gameEngine.isWinner(0))
      if (!gameEngine.isTie()) {
        redSnd.play();
        status = new String("Their turn.");
        connection.sendMove(pos.x);  //
        myMove = false;

這是sendMove:

public void sendMove(int col) {
  String s = (new Integer(col)).toString();
  send(s);
}

發送給:

public void send(String s) {
  outStream.println(s);
}

此后,其他玩家收到此舉:

int istatus = connection.getTheirMove();

這是getTheirMove:

public int getTheirMove() {
  // Make sure we're still connected
  if (!isConnected()) 
    throw new NullPointerException("Attempted to read closed socket!");
  try {
    String s = receive();
    System.out.println("Received: " + s);
    if (s == null)
      return GAMEOVER;
    s = s.trim();

    try {
      return (new Integer(s)).intValue();
    } catch (NumberFormatException e) {
        // It was probably a status report error
        return getStatus(s);
    }
  } catch (IOException e) {
      System.out.println("I/O Error: " + e);
      System.exit(1);
      return 0;
    }
  }

這里收到:

public String receive() throws IOException {
    return inStream.readLine();
}

那為什么不發送

  String coord =  x + "," + y; 

並使用String.split()拆分x和y坐標? 這將為您提供兩個字符串的數組-x和y。

更進一步,您可能想要發送(說)一些信息以識別您的消息,然后是數據。 然后使用類似的方法明確地拆分數據。 例如,消息可能看起來像:

COORD:x,y
STATUS: message

等等

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM