java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java Websocket Canvas井字棋网络游戏

Java Websocket Canvas实现井字棋网络游戏

作者:allway2

这篇文章主要介绍了Java Websocket Canvas实现井字棋网络游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Java Websocket Canvas实现井字棋网络游戏的具体代码,供大家参考,具体内容如下

TicTacToeGame.java 

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
 
@ServerEndpoint("/tictactoe")
public class TicTacToeGame {
 private static final Set<TicTacToeGame> games = new CopyOnWriteArraySet<>();
 private Session session;
 private String player;
 private static String b1 = "";
 private static String b2 = "";
 private static String b3 = "";
 private static String b4 = "";
 private static String b5 = "";
 private static String b6 = "";
 private static String b7 = "";
 private static String b8 = "";
 private static String b9 = "";
 
 @OnOpen
 public void onOpen(Session session) throws IOException {
  System.out.println("Connection from" + session.getId());
  this.session = session;
 
  System.out.println(games.size());
  if (games.size() == 0) {
   this.player = "X";
  }
  if (games.size() == 1) {
   this.player = "O";
  }
  if (games.size() > 1) {
   System.out.println("房间人满");
   session.getBasicRemote().sendText("roomfull");
//            session.close();
  } else {
   games.add(this);
   session.getBasicRemote().sendText("player-" + player);
   if (games.size() == 1) {
    sendText("wait");
   }
   if (games.size() == 2) {
    sendText("start");
   }
   sendText("turn-" + "X");
  }
 }
 
 @OnMessage
 public void onMessage(String message) {
  System.out.println(player);
  System.out.println(message);
  System.out.println(message.indexOf("place"));
  if (message.indexOf("place") != -1) {
   String[] words = message.split("-");
   System.out.println("words[1]=" + words[1]);
   System.out.println("words[2]=" + words[2]);
   System.out.println("games.size()=" + games.size());
 
   if (games.size() > 1) {
    if ("".equals(getPlayer(words[1]))) {
     place3(words[1], words[2]);
     sendText(message);
     check();
     if ("X".equals(words[2])) {
      sendText("turn-" + "O");
     } else {
      sendText("turn-" + "X");
     }
    }
   }
   System.out.println("b1=" + b1);
   System.out.println("b2=" + b2);
   System.out.println("b3=" + b3);
   System.out.println("b4=" + b4);
   System.out.println("b5=" + b5);
   System.out.println("b6=" + b6);
   System.out.println("b7=" + b7);
   System.out.println("b8=" + b8);
   System.out.println("b9=" + b9);
 
  } else if ("reset".equals(message)) {
   if (player.equals("X") || player.equals("O")) {
    b1 = "";
    b2 = "";
    b3 = "";
    b4 = "";
    b5 = "";
    b6 = "";
    b7 = "";
    b8 = "";
    b9 = "";
    sendText(message);
   }
  } else {
   sendText(message);
  }
 
 }
 
 private static void sendText(String msg) {
  for (TicTacToeGame game : games) {
   try {
    synchronized (game) {
     game.session.getBasicRemote().sendText(msg);
    }
   } catch (IOException e) {
    games.remove(game);
    try {
     game.session.close();
    } catch (IOException e1) {
    }
    sendText("leave-" + game.player);
   }
  }
 }
 
 @OnClose
 public void onClose(Session session) {
  System.out.println(session.getId());
  System.out.println(this.player + "已下线");
  if (!"".equals(this.player)) {
   games.remove(this);
   sendText("leave-" + this.player);
  }
 }
 
 public void place3(String id, String player) {
  if ("b1".equals(id)) {
   b1 = player;
  }
  if ("b2".equals(id)) {
   b2 = player;
  }
  if ("b3".equals(id)) {
   b3 = player;
  }
  if ("b4".equals(id)) {
   b4 = player;
  }
  if ("b5".equals(id)) {
   b5 = player;
  }
  if ("b6".equals(id)) {
   b6 = player;
  }
  if ("b7".equals(id)) {
   b7 = player;
  }
  if ("b8".equals(id)) {
   b8 = player;
  }
  if ("b9".equals(id)) {
   b9 = player;
  }
 }
 
 public String getPlayer(String id) {
  String player = "";
  if ("b1".equals(id)) {
   player = b1;
  }
  if ("b2".equals(id)) {
   player = b2;
  }
  if ("b3".equals(id)) {
   player = b3;
  }
  if ("b4".equals(id)) {
   player = b4;
  }
  if ("b5".equals(id)) {
   player = b5;
  }
  if ("b6".equals(id)) {
   player = b6;
  }
  if ("b7".equals(id)) {
   player = b7;
  }
  if ("b8".equals(id)) {
   player = b8;
  }
  if ("b9".equals(id)) {
   player = b9;
  }
  return player;
 }
 
 public void check() {
 
  if (b1.equals("X") && b2.equals("X") && b3.equals("X")) {
   sendText("xwon");
   sendText("gameover-YES");
  } else if (b1.equals("X") && b4.equals("X") && b7.equals("X")) {
   sendText("xwon");
   sendText("gameover-YES");
  } else if (b7.equals("X") && b8.equals("X") && b9.equals("X")) {
   sendText("xwon");
   sendText("gameover-YES");
  } else if (b3.equals("X") && b6.equals("X") && b9.equals("X")) {
   sendText("xwon");
   sendText("gameover-YES");
  } else if (b1.equals("X") && b5.equals("X") && b9.equals("X")) {
   sendText("xwon");
   sendText("gameover-YES");
  } else if (b3.equals("X") && b5.equals("X") && b7.equals("X")) {
   sendText("xwon");
   sendText("gameover-YES");
  } else if (b2.equals("X") && b5.equals("X") && b8.equals("X")) {
   sendText("xwon");
   sendText("gameover-YES");
  } else if (b4.equals("X") && b5.equals("X") && b6.equals("X")) {
   sendText("xwon");
   sendText("gameover-YES");
  }
 
  else if (b1.equals("O") && b2.equals("O") && b3.equals("O")) {
   sendText("owon");
   sendText("gameover-YES");
  } else if (b1.equals("O") && b4.equals("O") && b7.equals("O")) {
   sendText("owon");
   sendText("gameover-YES");
  } else if (b7.equals("O") && b8.equals("O") && b9.equals("O")) {
   sendText("owon");
   sendText("gameover-YES");
  } else if (b3.equals("O") && b6.equals("O") && b9.equals("O")) {
   sendText("owon");
   sendText("gameover-YES");
  } else if (b1.equals("O") && b5.equals("O") && b9.equals("O")) {
   sendText("owon");
   sendText("gameover-YES");
  } else if (b3.equals("O") && b5.equals("O") && b7.equals("O")) {
   sendText("owon");
   sendText("gameover-YES");
  } else if (b2.equals("O") && b5.equals("O") && b8.equals("O")) {
   sendText("owon");
   sendText("gameover-YES");
  } else if (b4.equals("O") && b5.equals("O") && b6.equals("O")) {
   sendText("owon");
   sendText("gameover-YES");
  }
 
  // Checking of Player O finsh
  // Here, Checking about Tie
  else if ((b1.equals("X") || b1.equals("O")) && (b2.equals("X") || b2.equals("O"))
    && (b3.equals("X") || b3.equals("O")) && (b4.equals("X") || b4.equals("O"))
    && (b5.equals("X") || b5.equals("O")) && (b6.equals("X") || b6.equals("O"))
    && (b7.equals("X") || b7.equals("O")) && (b8.equals("X") || b8.equals("O"))
    && (b9.equals("X") || b9.equals("O"))) {
   sendText("tie");
   sendText("gameover-YES");
  } else {
 
  }
 }
}

index.html

<!DOCTYPE html>
 
<head>
 <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content=
          "width=device-width, initial-scale=1.0">
    <!-- JavaScript file included -->
    
</head>
 
<body>
    <div id="main">
        <h1>TIC TAC TOE</h1>
 
 
 
        <!-- Space to show player turn -->
        <p id="player"></p>
 
        <br>
       
        <div id="game">
            <canvas id="canvas" width="300" height="300"></canvas>
        </div>
 
        <!-- Grid end here -->
        <br>
 
        <!-- Button to reset game -->
        <button id="but" onclick="reset()">
            重新开始
        </button>
        
        <br>
        <!-- Space to show player turn -->
        <p id="print2"></p>        
 
        <br>
        <!-- Space to show player turn -->
        <p id="print"></p>
        
 
 
    </div>
    <script src="tic.js"></script>
</body>
 
</html>

tic.js

// Function called whenever user tab on any box
player = "";
turn = "";
gameover = "NO";
// Function to reset game
function reset() {
    message = "reset";
    websocket.send(message);
    message = "turn-X";
    websocket.send(message);
}
function reset2() {
    clear();
    drawboard();
    gameover = "NO";
    document.getElementById("print2")
            .innerHTML = "游戏开始, 请开始放置棋子";
}
 
// Here onwards, functions check turn of the player
// and put accordingly innerText X or O
flag = 1;
function place(id) {
    if (gameover === "NO") {
        if (flag === 1) {
            if (document.getElementById(id).innerText === "") {
                document.getElementById(id).innerText = "X";
                flag = 0;
            }
        } else {
            if (document.getElementById(id).innerText === "") {
                document.getElementById(id).innerText = "O";
                flag = 1;
            }
        }
    }
    check();
}
function place2(id) {
    if (gameover === "NO") {
        if (turn === player) {
            if (document.getElementById(id).innerText === "") {
                message = "place-" + id + "-" + player;
                websocket.send(message);
            }
        }
    }
}
 
//function place3(id, player) {
//    document.getElementById(id).innerText = player;
//check();
//}
 
function getRootUri() {
    return "ws://" + (document.location.hostname == "" ? "localhost" : document.location.hostname) + ":" +
            (document.location.port == "" ? "8080" : document.location.port);
}
 
function init() {
    output = document.getElementById("output");
    websocket = new WebSocket(getRootUri() + "/TicTacToeWebSocket/tictactoe");
    websocket.onopen = function (evt) {
        onOpen(evt)
    };
    websocket.onmessage = function (evt) {
        onMessage(evt)
    };
    websocket.onerror = function (evt) {
        onError(evt)
    };
}
 
function onMessage(evt) {
    console.log(evt.data);
    if (evt.data == "roomfull") {
        document.getElementById("print")
                .innerHTML = "游戏玩家已满";
        websocket.close(-1);
    }
    if (evt.data == "reset") {
        reset2();
    }
    if (evt.data == "wait") {
        //window.alert("Waiting for Second Player");
        document.getElementById("print2")
                .innerHTML = "等待第二个玩家";
 
    }
    if (evt.data == "start") {
        reset();
    }
    if (evt.data == "xwon") {
        document.getElementById("print2")
                .innerHTML = "玩家X赢了";
 
    }
    if (evt.data == "owon") {
        document.getElementById("print2")
                .innerHTML = "玩家O赢了";
 
    }
    if (evt.data == "tie") {
        document.getElementById("print2")
                .innerHTML = "平局";
 
    }
    if (evt.data.indexOf("leave") != -1) {
        //window.alert(evt.data);
        words = evt.data.split("-");
        //window.alert(words[1]);
        player = words[1];
        //window.alert(player);
        document.getElementById("print2")
                .innerHTML = "玩家" + player+"已离开游戏,请退出游戏";
    }
    if (evt.data.indexOf("player") != -1) {
        //window.alert(evt.data);
        words = evt.data.split("-");
        //window.alert(words[1]);
        player = words[1];
        //window.alert(player);
        document.getElementById("player")
                .innerHTML = "你是玩家" + player;
    }
    if (evt.data.indexOf("turn") != -1) {
        //window.alert(evt.data);
        words = evt.data.split("-");
        //window.alert(words[1]);
        turn = words[1];
        //window.alert(turn);
        document.getElementById("print")
                .innerHTML = "当前由玩家" + turn + "放置棋子";
    }
    if (evt.data.indexOf("place") != -1) {
        //window.alert(evt.data);
        words = evt.data.split("-");
        //window.alert(words[1]);
        place3(words[1], words[2]);
    }
    if (evt.data.indexOf("gameover") != -1) {
        //window.alert(evt.data);
        words = evt.data.split("-");
        //window.alert(words[1]);
        gameover = words[1];
        //window.alert(turn);
        document.getElementById("print")
                .innerHTML = "游戏结束!";
    }
}
 
function onOpen(evt) {
}
function onError(evt) {
}
 
 
 
players = 2;
cell_count = 3;
winCount = 3;
cell_size = 100;
size = cell_size * cell_count;
 
 
var canvas = document.getElementById('canvas');
canvas.width = size;
canvas.height = size;
 
canvas.addEventListener('click', click, false);
 
 
var ctx = canvas.getContext('2d');
 
ctx.imageSmoothingEnabled = false;
ctx.lineWidth = 3;
 
 
function clear() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
}
 
function line(x, y, w, h, color = '#ccc') {
    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.lineTo(x + w, y + h);
    ctx.strokeStyle = color;
    ctx.stroke();
    ctx.closePath();
}
 
function click(e) {
    if (gameover === "NO") {
        if (turn === player) {
            i = e.offsetX / cell_size | 0;
            j = e.offsetY / cell_size | 0;
            id = "";
            if (i == 0 && j == 0) {
                id = "b1";
            }
            if (i == 1 && j == 0) {
                id = "b2";
            }
            if (i == 2 && j == 0) {
                id = "b3";
                ;
            }
            if (i == 0 && j == 1) {
                id = "b4";
            }
            if (i == 1 && j == 1) {
                id = "b5";
            }
            if (i == 2 && j == 1) {
                id = "b6";
            }
            if (i == 0 && j == 2) {
                id = "b7";
            }
            if (i == 1 && j == 2) {
                id = "b8";
            }
            if (i == 2 && j == 2) {
                id = "b9";
            }
            message = "place-" + id + "-" + player;
            websocket.send(message);
        }
    }
}
function place3(id, player) {
    i = 0;
    j = 0;
    if (id === "b1") {
        i = 0;
        j = 0;
    }
    if (id === "b2") {
        i = 1;
        j = 0;
    }
    if (id === "b3") {
        i = 2;
        j = 0;
    }
    if (id === "b4") {
        i = 0;
        j = 1;
    }
    if (id === "b5") {
        i = 1;
        j = 1;
    }
    if (id === "b6") {
        i = 2;
        j = 1;
    }
    if (id === "b7") {
        i = 0;
        j = 2;
    }
    if (id === "b8") {
        i = 1;
        j = 2;
    }
    if (id === "b9") {
        i = 2;
        j = 2;
    }
 
    if (player === "X") {
//         window.alert("X");
        // draw X figure
        color = '#3F51B5';
 
        left = (i + 0.1) * cell_size;
        up = (j + 0.1) * cell_size;
        size = 0.8 * cell_size;
//        window.alert(left);
//        window.alert("up="+up);
//        window.alert(size);
 
        line(left, up, size, size, color);
        line(left + size, up, -size, size, color);
    }
    if (player === "O") {
        color = '#FF5722';
        left = (i + 0.1) * cell_size;
        up = (j + 0.1) * cell_size;
        size = 0.8 * cell_size;
        ctx.beginPath();
        ctx.arc((i + 0.5) * cell_size, (j + 0.5) * cell_size, 0.4 * cell_size, 0, Math.PI * 2, false);
        ctx.strokeStyle = color;
        ctx.stroke();
        ctx.closePath();
    }
}
 
function drawboard() {
    for (let i = 0; i < cell_count; i++) {
        for (let j = 0; j < cell_count; j++) {
            left = i * cell_size;
            up = j * cell_size;
            size = cell_size;
            ctx.beginPath();
            ctx.lineWidth = "6";
            ctx.strokeStyle = "gray";
            ctx.rect(left, up, size, size);
            ctx.stroke();
        }
 
    }
 
}
drawboard();
 
 
window.addEventListener("load", init, false);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文