服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

香港云服务器
服务器之家 - 编程语言 - Java教程 - Java Websocket Canvas实现井字棋网络游戏

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

2021-11-29 13:34allway2 Java教程

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

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

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

TicTacToeGame.java 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
// 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);

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

原文链接:https://blog.csdn.net/allway2/article/details/119830552

延伸 · 阅读

精彩推荐
  • Java教程xml与Java对象的转换详解

    xml与Java对象的转换详解

    这篇文章主要介绍了xml与Java对象的转换详解的相关资料,需要的朋友可以参考下...

    Java教程网2942020-09-17
  • Java教程升级IDEA后Lombok不能使用的解决方法

    升级IDEA后Lombok不能使用的解决方法

    最近看到提示IDEA提示升级,寻思已经有好久没有升过级了。升级完毕重启之后,突然发现好多错误,本文就来介绍一下如何解决,感兴趣的可以了解一下...

    程序猿DD9332021-10-08
  • Java教程Java8中Stream使用的一个注意事项

    Java8中Stream使用的一个注意事项

    最近在工作中发现了对于集合操作转换的神器,java8新特性 stream,但在使用中遇到了一个非常重要的注意点,所以这篇文章主要给大家介绍了关于Java8中S...

    阿杜7482021-02-04
  • Java教程Java BufferWriter写文件写不进去或缺失数据的解决

    Java BufferWriter写文件写不进去或缺失数据的解决

    这篇文章主要介绍了Java BufferWriter写文件写不进去或缺失数据的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望...

    spcoder14552021-10-18
  • Java教程Java使用SAX解析xml的示例

    Java使用SAX解析xml的示例

    这篇文章主要介绍了Java使用SAX解析xml的示例,帮助大家更好的理解和学习使用Java,感兴趣的朋友可以了解下...

    大行者10067412021-08-30
  • Java教程Java实现抢红包功能

    Java实现抢红包功能

    这篇文章主要为大家详细介绍了Java实现抢红包功能,采用多线程模拟多人同时抢红包,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙...

    littleschemer13532021-05-16
  • Java教程20个非常实用的Java程序代码片段

    20个非常实用的Java程序代码片段

    这篇文章主要为大家分享了20个非常实用的Java程序片段,对java开发项目有所帮助,感兴趣的小伙伴们可以参考一下 ...

    lijiao5352020-04-06
  • Java教程小米推送Java代码

    小米推送Java代码

    今天小编就为大家分享一篇关于小米推送Java代码,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧...

    富贵稳中求8032021-07-12
604