Java+Swing实现经典五子棋游戏
五子棋是世界智力运动会竞技项目之一,是一种两人对弈的纯策略型棋类游戏,是世界智力运动会竞技项目之一。本文将采用Java Swing实现这一经典游戏,需要的可以参考一下
目录
前言
主要需求
主要设计
功能截图
代码实现
总结
前言
五子棋是世界智力运动会竞技项目之一,是一种两人对弈的纯策略型棋类游戏,是世界智力运动会竞技项目之一,通常双方分别使用黑白两色的棋子,下在棋盘直线与横线的交叉点上,先形成5子连线者获胜。
棋具与围棋通用,起源于中国上古时代的传统黑白棋种之一。主要流行于华人和汉字文化圈的国家以及欧美一些地区,是世界上最古老的棋。
容易上手,老少皆宜,而且趣味横生,引人入胜;不仅能增强思维能力,提高智力,而且富含哲理,有助于修身养性。
用java语言实现,采用了swing技术进行了界面化处理,设计思路用了面向对象思想。
主要需求
1、对局双方各执一色棋子。
2、空棋盘开局。
3、黑先、白后,交替下子,每次只能下一子。
4、棋子下在棋盘的空白点上,棋子下定后,不得向其它点移动,不得从棋盘上拿掉或拿起另落别处。
5、黑方的第一枚棋子可下在棋盘任意交叉点上。
6、轮流下子是双方的权利,但允许任何一方放弃下子权,先形成5子连线者获胜。
主要设计
1、由于是两人的游戏,非单机版,所以要有多个客户端相互通信,这时就要用到socket 技术
2、设计socket服务端,用来维护socket客户端连接
3、设计socket客户端,用来实现五子棋逻辑和效果
4、客户端要能设置连接服务端的IP,用来连接服务端
5、客户端1创建游戏后,客户端2可以选择客户端1进行联机对战
6、游戏规则:
对局双方各执一色棋子。
空棋盘开局。
黑先、白后,交替下子,每次只能下一子。
棋子下在棋盘的空白点上,棋子下定后,不得向其它点移动,不得从棋盘上拿掉或拿起另落别处。
黑方的第一枚棋子可下在棋盘任意交叉点上。
轮流下子是双方的权利,但允许任何一方放弃下子权,先形成5子连线者获胜。
功能截图
服务端启动
客户端1启动
客户端2启动
对战效果
代码实现
服务端启动类
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 | public class ServerRunner extends Frame implements ActionListener { JButton clearMsgButton = new JButton( "清空" ); JButton serverStatusButton = new JButton( "状态" ); JButton closeServerButton = new JButton( "关闭" ); Panel buttonPanel = new Panel(); ServerMsgPanel serverMsgPanel = new ServerMsgPanel(); ServerSocket serverSocket; int clientAccessNumber = 1 ; /** * 将客户端套接口和输出流绑定 */ Hashtable clientDataHash = new Hashtable( 50 ); /** * 将客户端套接口和客户名绑定 */ Hashtable clientNameHash = new Hashtable( 50 ); /** * 将游戏创建者和游戏加入者绑定 */ Hashtable chessPeerHash = new Hashtable( 50 ); public ServerRunner() { super ( "网络游戏对战平台服务器控制平台" ); setBackground(Color.PINK); buttonPanel.setLayout( new FlowLayout()); clearMsgButton.setSize( 50 , 30 ); buttonPanel.add(clearMsgButton); clearMsgButton.addActionListener( this ); serverStatusButton.setSize( 50 , 30 ); buttonPanel.add(serverStatusButton); serverStatusButton.addActionListener( this ); closeServerButton.setSize( 50 , 30 ); buttonPanel.add(closeServerButton); closeServerButton.addActionListener( this ); add(serverMsgPanel, BorderLayout.CENTER); add(buttonPanel, BorderLayout.SOUTH); addWindowListener( new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit( 0 ); } }); pack(); setVisible( true ); setSize( 600 , 440 ); setResizable( false ); validate(); try { createServer( 1234 , serverMsgPanel); } catch (Exception e) { e.printStackTrace(); } } /** * 用指定端口和面板创建服务器 * @param port * @param serverMsgPanel * @throws IOException */ public void createServer( int port, ServerMsgPanel serverMsgPanel) throws IOException { // 客户端套接口 Socket clientSocket; // 设定当前主机 this .serverMsgPanel = serverMsgPanel; try { serverSocket = new ServerSocket(port); serverMsgPanel.msgTextArea.setText( "服务器启动:" + InetAddress.getLocalHost() + ":" + serverSocket.getLocalPort() + "\n" ); while ( true ) { // 监听客户端套接口的信息 clientSocket = serverSocket.accept(); serverMsgPanel.msgTextArea.append( "已连接用户:" + "毅慎" + clientAccessNumber + "\n" + clientSocket + "\n" ); // 建立客户端输出流 DataOutputStream outputData = new DataOutputStream(clientSocket.getOutputStream()); // 将客户端套接口和输出流绑定 clientDataHash.put(clientSocket, outputData); // 将客户端套接口和客户名绑定 clientNameHash.put(clientSocket, ( "毅慎" + clientAccessNumber++)); // 创建并运行服务器端线程 ServerThread thread = new ServerThread(clientSocket, clientDataHash, clientNameHash, chessPeerHash, serverMsgPanel); thread.start(); } } catch (IOException ex) { ex.printStackTrace(); } } @Override public void actionPerformed(ActionEvent e) { // 清空服务器信息 if (e.getSource() == clearMsgButton) { serverMsgPanel.msgTextArea.setText( "" ); } // 显示服务器信息 if (e.getSource() == serverStatusButton) { try { serverMsgPanel.msgTextArea.append( "用户信息:" + "毅慎" + (clientAccessNumber - 1 ) + "\n服务器信息:" + InetAddress.getLocalHost() + ":" + serverSocket.getLocalPort() + "\n" ); } catch (Exception ee) { ee.printStackTrace(); } } } public static void main(String[] args) { new ServerRunner(); } } |
客户端启动类
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 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 | /** * @Author: Mr_OO * @Date: 2019/12/22 9:05 * 客户端 */ public class ClientChess extends Frame implements ActionListener, KeyListener { /** * 客户端套接口 */ public Socket clientSocket; /** * 数据输入流 */ public DataInputStream inputStream; /** * 数据输出流 */ public DataOutputStream outputStream; /** * 用户名 */ public String chessClientName = null ; /** * 主机地址 */ public String host = null ; /** * 主机端口 */ public int port = 1234 ; /** * 是否在聊天 */ public boolean isOnChat = false ; /** * 是否在下棋 */ public boolean isOnChess = false ; /** * 游戏是否进行中 */ public boolean isGameConnected = false ; /** * 是否为游戏创建者 */ public boolean isCreator = false ; /** * 是否为游戏加入者 */ public boolean isParticipant = false ; /** * 用户列表区 */ public UserList userListPad = new UserList(); /** * 用户聊天区 */ protected UserChat userChatPad = new UserChat(); /** * 用户操作区 */ public UserController userControlPad = new UserController(); /** * 用户输入区 */ protected UserInput userInputPad = new UserInput(); /** * 下棋区 */ ChessBoard chessBoard = new ChessBoard(); /** * 面板区 */ private Panel southPanel = new Panel(); private Panel centerPanel = new Panel(); private Panel eastPanel = new Panel(); /** * 构造方法,创建界面 */ public ClientChess() { super ( "五子棋客户端" ); setLayout( new BorderLayout()); host = userControlPad.ipInputted.getText(); eastPanel.setLayout( new BorderLayout()); eastPanel.add(userListPad, BorderLayout.NORTH); eastPanel.add(userChatPad, BorderLayout.CENTER); eastPanel.setBackground( new Color( 238 , 154 , 73 )); userInputPad.contentInputted.addKeyListener( this ); chessBoard.host = (userControlPad.ipInputted.getText()); centerPanel.add(chessBoard, BorderLayout.CENTER); centerPanel.add(userInputPad, BorderLayout.SOUTH); centerPanel.setBackground( new Color( 238 , 154 , 73 )); userControlPad.connectButton.addActionListener( this ); userControlPad.createButton.addActionListener( this ); userControlPad.joinButton.addActionListener( this ); userControlPad.cancelButton.addActionListener( this ); userControlPad.exitButton.addActionListener( this ); userControlPad.createButton.setEnabled( false ); userControlPad.joinButton.setEnabled( false ); userControlPad.cancelButton.setEnabled( false ); southPanel.add(userControlPad, BorderLayout.CENTER); southPanel.setBackground(PINK); addWindowListener( new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // 聊天中 if (isOnChat) { // 关闭客户端套接口 try { clientSocket.close(); } catch (Exception ed){} } if (isOnChess || isGameConnected) { // 下棋中 try { // 关闭下棋端口 chessBoard.chessSocket.close(); } catch (Exception ee){} } System.exit( 0 ); } }); add(eastPanel, BorderLayout.EAST); add(centerPanel, BorderLayout.CENTER); add(southPanel, BorderLayout.SOUTH); pack(); setSize( 1000 , 700 ); setVisible( true ); setResizable( false ); this .validate(); } /** * 按指定的IP地址和端口连接到服务器 * @param serverIP * @param serverPort * @return * @throws Exception */ public boolean connectToServer(String serverIP, int serverPort) throws Exception { try { // 创建客户端套接口 clientSocket = new Socket(serverIP, serverPort); // 创建输入流 inputStream = new DataInputStream(clientSocket.getInputStream()); // 创建输出流 outputStream = new DataOutputStream(clientSocket.getOutputStream()); // 创建客户端线程 ClientThread clientThread = new ClientThread( this ); // 启动线程,等待聊天信息 clientThread.start(); isOnChat = true ; return true ; } catch (IOException ex) { userChatPad.chatTextArea.setText( "Sorry,无法连接!!!\n" ); } return false ; } /** * 客户端事件处理 * @param e */ @Override public void actionPerformed(ActionEvent e) { // 连接到主机按钮单击事件 if (e.getSource() == userControlPad.connectButton) { // 取得主机地址 host = chessBoard.host = userControlPad.ipInputted.getText(); try { // 成功连接到主机时,设置客户端相应的界面状态 if (connectToServer(host, port)) { userChatPad.chatTextArea.setText( "" ); userControlPad.connectButton.setEnabled( false ); userControlPad.createButton.setEnabled( true ); userControlPad.joinButton.setEnabled( true ); chessBoard.statusText.setText( "连接成功,请等待!!!" ); } } catch (Exception ei) { userChatPad.chatTextArea.setText( "Sorry,不能连接!!!\n" ); } } // 离开游戏按钮单击事件 if (e.getSource() == userControlPad.exitButton) { // 若用户处于聊天状态中 if (isOnChat) { try { // 关闭客户端套接口 clientSocket.close(); } catch (Exception ed){} } // 若用户处于游戏状态中 if (isOnChess || isGameConnected) { try { // 关闭游戏端口 chessBoard.chessSocket.close(); } catch (Exception ee){} } System.exit( 0 ); } // 加入游戏按钮单击事件 if (e.getSource() == userControlPad.joinButton) { // 取得要加入的游戏 String selectedUser = userListPad.userList.getSelectedItem(); // 若未选中要加入的用户,或选中的用户已经在游戏,则给出提示信息 if (selectedUser == null || selectedUser.startsWith( "[inchess]" ) || selectedUser.equals(chessClientName)) { chessBoard.statusText.setText( "必须选择一个用户!" ); } else { // 执行加入游戏的操作 try { // 若游戏套接口未连接 if (!isGameConnected) { // 若连接到主机成功 if (chessBoard.connectServer(chessBoard.host, chessBoard.port)) { isGameConnected = true ; isOnChess = true ; isParticipant = true ; userControlPad.createButton.setEnabled( false ); userControlPad.joinButton.setEnabled( false ); userControlPad.cancelButton.setEnabled( true ); chessBoard.chessThread.sendMessage( "/joingame " + userListPad.userList.getSelectedItem() + " " + chessClientName); } } else { // 若游戏端口连接中 isOnChess = true ; isParticipant = true ; userControlPad.createButton.setEnabled( false ); userControlPad.joinButton.setEnabled( false ); userControlPad.cancelButton.setEnabled( true ); chessBoard.chessThread.sendMessage( "/joingame " + userListPad.userList.getSelectedItem() + " " + chessClientName); } } catch (Exception ee) { isGameConnected = false ; isOnChess = false ; isParticipant = false ; userControlPad.createButton.setEnabled( true ); userControlPad.joinButton.setEnabled( true ); userControlPad.cancelButton.setEnabled( false ); userChatPad.chatTextArea.setText( "不能连接: \n" + ee); } } } // 创建游戏按钮单击事件 if (e.getSource() == userControlPad.createButton) { try { // 若游戏端口未连接 if (!isGameConnected) { if (chessBoard.connectServer(chessBoard.host, chessBoard.port)) { // 若连接到主机成功 isGameConnected = true ; isOnChess = true ; isCreator = true ; userControlPad.createButton.setEnabled( false ); userControlPad.joinButton.setEnabled( false ); userControlPad.cancelButton.setEnabled( true ); chessBoard.chessThread.sendMessage( "/creatgame " + "[inchess]" + chessClientName); } } else { // 若游戏端口连接中 isOnChess = true ; isCreator = true ; userControlPad.createButton.setEnabled( false ); userControlPad.joinButton.setEnabled( false ); userControlPad.cancelButton.setEnabled( true ); chessBoard.chessThread.sendMessage( "/creatgame " + "[inchess]" + chessClientName); } } catch (Exception ec) { isGameConnected = false ; isOnChess = false ; isCreator = false ; userControlPad.createButton.setEnabled( true ); userControlPad.joinButton.setEnabled( true ); userControlPad.cancelButton.setEnabled( false ); ec.printStackTrace(); userChatPad.chatTextArea.setText( "Sorry,不能连接: \n" + ec); } } // 退出游戏按钮单击事件 if (e.getSource() == userControlPad.cancelButton) { // 游戏中 if (isOnChess) { chessBoard.chessThread.sendMessage( "/giveup " + chessClientName); chessBoard.setVicStatus(- 1 * chessBoard.chessColor); userControlPad.createButton.setEnabled( true ); userControlPad.joinButton.setEnabled( true ); userControlPad.cancelButton.setEnabled( false ); chessBoard.statusText.setText( "请选择创建房间或加入游戏!!!" ); } if (!isOnChess) { // 非游戏中 userControlPad.createButton.setEnabled( true ); userControlPad.joinButton.setEnabled( true ); userControlPad.cancelButton.setEnabled( false ); chessBoard.statusText.setText( "请选择创建房间或加入游戏!!!" ); } isParticipant = isCreator = false ; } } @Override public void keyPressed(KeyEvent e) { TextField inputwords = (TextField) e.getSource(); // 处理回车按键事件 if (e.getKeyCode() == KeyEvent.VK_ENTER) { // 给所有人发信息 if (userInputPad.userChoice.getSelectedItem().equals( "所有用户" )) { try { // 发送信息 outputStream.writeUTF(inputwords.getText()); inputwords.setText( "" ); } catch (Exception ea) { userChatPad.chatTextArea.setText( "Sorry,不能连接到服务器!\n" ); userListPad.userList.removeAll(); userInputPad.userChoice.removeAll(); inputwords.setText( "" ); userControlPad.connectButton.setEnabled( true ); } } else { // 给指定人发信息 try { outputStream.writeUTF( "/" + userInputPad.userChoice.getSelectedItem() + " " + inputwords.getText()); inputwords.setText( "" ); } catch (Exception ea) { userChatPad.chatTextArea.setText( "Sorry,不能连接到服务器!\n" ); userListPad.userList.removeAll(); userInputPad.userChoice.removeAll(); inputwords.setText( "" ); userControlPad.connectButton.setEnabled( true ); } } } } @Override public void keyTyped(KeyEvent e) {} @Override public void keyReleased(KeyEvent e) {} public static void main(String[] args) { new ClientChess(); } } |
棋盘五子棋核心算法类
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 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 | public class ChessBoard extends Panel implements MouseListener, ActionListener { public int dis = 30 ; // 鼠标是否能使用 public boolean isMouseEnabled = false ; // 是否胜利 public boolean isWon = false ; // 棋子的x轴坐标位 public int chessX_POS = - 1 ; // 棋子的y轴坐标位 public int chessY_POS = - 1 ; // 棋子的颜色 public int chessColor = 1 ; // 黑棋x轴坐标位数组 public int chessBlack_XPOS[] = new int [ 200 ]; // 黑棋y轴坐标位数组 public int chessBlack_YPOS[] = new int [ 200 ]; // 白棋x轴坐标位数组 public int chessWhite_XPOS[] = new int [ 200 ]; // 白棋y轴坐标位数组 public int chessWhite_YPOS[] = new int [ 200 ]; // 黑棋数量 public int chessBlackCount = 0 ; // 白棋数量 public int chessWhiteCount = 0 ; // 黑棋获胜次数 public int chessBlackVicTimes = 0 ; // 白棋获胜次数 public int chessWhiteVicTimes = 0 ; // 套接口 public Socket chessSocket; protected DataInputStream inputData; protected DataOutputStream outputData; public String chessSelfName = null ; public String chessPeerName = null ; public String host = null ; public int port = 1234 ; public TextField statusText = new TextField( "请先连接服务器!!!" ); public ChessThread chessThread = new ChessThread( this ); public ChessBoard() { setSize( 600 , 600 ); setLayout( null ); setBackground( new Color( 205 , 133 , 63 )); addMouseListener( this ); add(statusText); statusText.setBounds( new Rectangle( 80 , 5 , 440 , 24 )); statusText.setEditable( false ); } /** * 连接到主机 * @param ServerIP * @param ServerPort * @return * @throws Exception */ public boolean connectServer(String ServerIP, int ServerPort) throws Exception { try { // 取得主机端口 chessSocket = new Socket(ServerIP, ServerPort); // 取得输入流 inputData = new DataInputStream(chessSocket.getInputStream()); // 取得输出流 outputData = new DataOutputStream(chessSocket.getOutputStream()); chessThread.start(); return true ; } catch (IOException ex) { statusText.setText( "sorry,连接失败!!! \n" ); } return false ; } /** * 设定胜利时的棋盘状态 * @param vicChessColor */ public void setVicStatus( int vicChessColor) { // 清空棋盘 this .removeAll(); // 将黑棋的位置设置到零点 for ( int i = 0 ; i <= chessBlackCount; i++) { chessBlack_XPOS[i] = 0 ; chessBlack_YPOS[i] = 0 ; } // 将白棋的位置设置到零点 for ( int i = 0 ; i <= chessWhiteCount; i++) { chessWhite_XPOS[i] = 0 ; chessWhite_YPOS[i] = 0 ; } // 清空棋盘上的黑棋数 chessBlackCount = 0 ; // 清空棋盘上的白棋数 chessWhiteCount = 0 ; add(statusText); statusText.setBounds( 40 , 5 , 200 , 24 ); // 黑棋胜 if (vicChessColor == 1 ) { chessBlackVicTimes++; statusText.setText( "恭喜黑方胜!!!黑VS白 " + chessBlackVicTimes + ":" + chessWhiteVicTimes + ".游戏重启,等待白方..." ); // 白棋胜 } else if (vicChessColor == - 1 ) { chessWhiteVicTimes++; statusText.setText( "恭喜白方胜!!!黑VS白 " + chessBlackVicTimes + ":" + chessWhiteVicTimes + ".游戏重启,等待黑方..." ); } } /** * 取得指定棋子的位置 * @param xPos * @param yPos * @param chessColor */ public void setLocation( int xPos, int yPos, int chessColor) { // 棋子为黑棋时 if (chessColor == 1 ) { chessBlack_XPOS[chessBlackCount] = xPos * dis; chessBlack_YPOS[chessBlackCount] = yPos * dis; chessBlackCount++; // 棋子为白棋时 } else if (chessColor == - 1 ) { chessWhite_XPOS[chessWhiteCount] = xPos * dis; chessWhite_YPOS[chessWhiteCount] = yPos * dis; chessWhiteCount++; } } /** * 五子棋核心算法 * @param xPos * @param yPos * @param chessColor * @return */ public boolean checkVicStatus( int xPos, int yPos, int chessColor) { // 连接棋子数 int chessLinkedCount = 1 ; // 用于比较是否要继续遍历一个棋子的相邻网格 int chessLinkedCompare = 1 ; // 要比较的棋子在数组中的索引位置 int chessToCompareIndex = 0 ; // 相邻网格的位置 int closeGrid = 1 ; // 黑棋时 if (chessColor == 1 ) { // 将该棋子自身算入的话,初始连接数为1 chessLinkedCount = 1 ; //以下每对for循环语句为一组,因为下棋的位置能位于中间而非两端 // 遍历相邻4个网格 // 判断当前下的棋子的右边4个棋子是否都为黑棋 for (closeGrid = 1 ; closeGrid <= 4 ; closeGrid++) { // 遍历棋盘上所有黑棋子 for (chessToCompareIndex = 0 ; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if (((xPos + closeGrid) * dis == chessBlack_XPOS[chessToCompareIndex]) && ((yPos * dis) == chessBlack_YPOS[chessToCompareIndex])) { // 连接数加1 chessLinkedCount = chessLinkedCount + 1 ; // 五子相连时,胜利 if (chessLinkedCount == 5 ) { return true ; } } } if (chessLinkedCount == (chessLinkedCompare + 1 )) { chessLinkedCompare++; // 若中间有一个棋子非黑棋,则会进入此分支,此时无需再遍历 } else { break ; } } // 判断当前下的棋子的左边4个棋子是否都为黑棋 for (closeGrid = 1 ; closeGrid <= 4 ; closeGrid++) { for (chessToCompareIndex = 0 ; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if (((xPos - closeGrid) * dis == chessBlack_XPOS[chessToCompareIndex]) && (yPos * dis == chessBlack_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5 ) { return true ; } } } if (chessLinkedCount == (chessLinkedCompare + 1 )) { chessLinkedCompare++; } else { break ; } } // 进入新的一组for循环时要将连接数等重置 chessLinkedCount = 1 ; chessLinkedCompare = 1 ; // 判断当前下的棋子的上边4个棋子是否都为黑棋 for (closeGrid = 1 ; closeGrid <= 4 ; closeGrid++) { for (chessToCompareIndex = 0 ; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if ((xPos * dis == chessBlack_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * dis == chessBlack_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5 ) { return true ; } } } if (chessLinkedCount == (chessLinkedCompare + 1 )) { chessLinkedCompare++; } else { break ; } } // 判断当前下的棋子的下边4个棋子是否都为黑棋 for (closeGrid = 1 ; closeGrid <= 4 ; closeGrid++) { for (chessToCompareIndex = 0 ; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if ((xPos * dis == chessBlack_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * dis == chessBlack_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5 ) { return true ; } } } if (chessLinkedCount == (chessLinkedCompare + 1 )) { chessLinkedCompare++; } else { break ; } } chessLinkedCount = 1 ; chessLinkedCompare = 1 ; for (closeGrid = 1 ; closeGrid <= 4 ; closeGrid++) { for (chessToCompareIndex = 0 ; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { // 判断当前下的棋子的左上方向4个棋子是否都为黑棋 if (((xPos - closeGrid) * dis == chessBlack_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * dis == chessBlack_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5 ) { return true ; } } } if (chessLinkedCount == (chessLinkedCompare + 1 )) { chessLinkedCompare++; } else { break ; } } for (closeGrid = 1 ; closeGrid <= 4 ; closeGrid++) { for (chessToCompareIndex = 0 ; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { // 判断当前下的棋子的右下方向4个棋子是否都为黑棋 if (((xPos + closeGrid) * dis == chessBlack_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * dis == chessBlack_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5 ) { return true ; } } } if (chessLinkedCount == (chessLinkedCompare + 1 )) { chessLinkedCompare++; } else { break ; } } chessLinkedCount = 1 ; chessLinkedCompare = 1 ; // 判断当前下的棋子的右上方向4个棋子是否都为黑棋 for (closeGrid = 1 ; closeGrid <= 4 ; closeGrid++) { for (chessToCompareIndex = 0 ; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if (((xPos + closeGrid) * dis == chessBlack_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * dis == chessBlack_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5 ) { return true ; } } } if (chessLinkedCount == (chessLinkedCompare + 1 )) { chessLinkedCompare++; } else { break ; } } // 判断当前下的棋子的左下方向4个棋子是否都为黑棋 for (closeGrid = 1 ; closeGrid <= 4 ; closeGrid++) { for (chessToCompareIndex = 0 ; chessToCompareIndex <= chessBlackCount; chessToCompareIndex++) { if (((xPos - closeGrid) * dis == chessBlack_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * dis == chessBlack_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5 ) { return true ; } } } if (chessLinkedCount == (chessLinkedCompare + 1 )) { chessLinkedCompare++; } else { break ; } } // 白棋的情况 } else if (chessColor == - 1 ) { chessLinkedCount = 1 ; // 判断当前下的棋子的右边4个棋子是否都为白棋 for (closeGrid = 1 ; closeGrid <= 4 ; closeGrid++) { for (chessToCompareIndex = 0 ; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos + closeGrid) * dis == chessWhite_XPOS[chessToCompareIndex]) && (yPos * dis == chessWhite_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5 ) { return true ; } } } if (chessLinkedCount == (chessLinkedCompare + 1 )) { chessLinkedCompare++; } else { break ; } } // 判断当前下的棋子的左边4个棋子是否都为白棋 for (closeGrid = 1 ; closeGrid <= 4 ; closeGrid++) { for (chessToCompareIndex = 0 ; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos - closeGrid) * dis == chessWhite_XPOS[chessToCompareIndex]) && (yPos * dis == chessWhite_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5 ) { return true ; } } } if (chessLinkedCount == (chessLinkedCompare + 1 )) { chessLinkedCompare++; } else { break ; } } chessLinkedCount = 1 ; chessLinkedCompare = 1 ; // 判断当前下的棋子的上边4个棋子是否都为白棋 for (closeGrid = 1 ; closeGrid <= 4 ; closeGrid++) { for (chessToCompareIndex = 0 ; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if ((xPos * dis == chessWhite_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * dis == chessWhite_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5 ) { return true ; } } } if (chessLinkedCount == (chessLinkedCompare + 1 )) { chessLinkedCompare++; } else { break ; } } // 判断当前下的棋子的下边4个棋子是否都为白棋 for (closeGrid = 1 ; closeGrid <= 4 ; closeGrid++) { for (chessToCompareIndex = 0 ; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if ((xPos * dis == chessWhite_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * dis == chessWhite_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5 ) { return true ; } } } if (chessLinkedCount == (chessLinkedCompare + 1 )) { chessLinkedCompare++; } else { break ; } } chessLinkedCount = 1 ; chessLinkedCompare = 1 ; // 判断当前下的棋子的左上方向4个棋子是否都为白棋 for (closeGrid = 1 ; closeGrid <= 4 ; closeGrid++) { for (chessToCompareIndex = 0 ; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos - closeGrid) * dis == chessWhite_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * dis == chessWhite_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5 ) { return true ; } } } if (chessLinkedCount == (chessLinkedCompare + 1 )) { chessLinkedCompare++; } else { break ; } } // 判断当前下的棋子的右下方向4个棋子是否都为白棋 for (closeGrid = 1 ; closeGrid <= 4 ; closeGrid++) { for (chessToCompareIndex = 0 ; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos + closeGrid) * dis == chessWhite_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * dis == chessWhite_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5 ) { return true ; } } } if (chessLinkedCount == (chessLinkedCompare + 1 )) { chessLinkedCompare++; } else { break ; } } chessLinkedCount = 1 ; chessLinkedCompare = 1 ; // 判断当前下的棋子的右上方向4个棋子是否都为白棋 for (closeGrid = 1 ; closeGrid <= 4 ; closeGrid++) { for (chessToCompareIndex = 0 ; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos + closeGrid) * dis == chessWhite_XPOS[chessToCompareIndex]) && ((yPos + closeGrid) * dis == chessWhite_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5 ) { return true ; } } } if (chessLinkedCount == (chessLinkedCompare + 1 )) { chessLinkedCompare++; } else { break ; } } // 判断当前下的棋子的左下方向4个棋子是否都为白棋 for (closeGrid = 1 ; closeGrid <= 4 ; closeGrid++) { for (chessToCompareIndex = 0 ; chessToCompareIndex <= chessWhiteCount; chessToCompareIndex++) { if (((xPos - closeGrid) * dis == chessWhite_XPOS[chessToCompareIndex]) && ((yPos - closeGrid) * dis == chessWhite_YPOS[chessToCompareIndex])) { chessLinkedCount++; if (chessLinkedCount == 5 ) { return ( true ); } } } if (chessLinkedCount == (chessLinkedCompare + 1 )) { chessLinkedCompare++; } else { break ; } } } return false ; } /** * 画棋盘 */ @Override public void paint(Graphics g) { for ( int i = 40 ; i <= 580 ; i = i + 30 ) { g.drawLine( 40 , i, 580 , i); } for ( int j = 40 ; j <= 580 ; j = j + 30 ) { g.drawLine(j, 40 , j, 580 ); } g.fillOval( 127 , 127 , 8 , 8 ); g.fillOval( 487 , 127 , 8 , 8 ); g.fillOval( 127 , 487 , 8 , 8 ); g.fillOval( 487 , 487 , 8 , 8 ); g.fillOval( 307 , 307 , 8 , 8 ); } /** * 画棋子 * @param xPos * @param yPos * @param chessColor */ public void paintChessPoint( int xPos, int yPos, int chessColor) { ChessBlack chessBlack = new ChessBlack( this ); ChessWhite chessWhite = new ChessWhite( this ); // 黑棋 if (chessColor == 1 && isMouseEnabled) { // 设置棋子的位置 setLocation(xPos, yPos, chessColor); // 取得当前局面状态 isWon = checkVicStatus(xPos, yPos, chessColor); // 非胜利状态 if (isWon == false ) { chessThread.sendMessage( "/" + chessPeerName + " /chess " + xPos + " " + yPos + " " + chessColor); // 将棋子添加到棋盘中 this .add(chessBlack); // 设置棋子边界 chessBlack.setBounds(xPos * dis - 4 , yPos * dis - 3 , 30 , 30 ); statusText.setText( "黑(第" + chessBlackCount + "步)" + xPos + " " + yPos + ",轮到白方." ); // 将鼠标设为不可用 isMouseEnabled = false ; // 胜利状态 } else { chessThread.sendMessage( "/" + chessPeerName + " /chess " + xPos + " " + yPos + " " + chessColor); this .add(chessBlack); chessBlack.setBounds(xPos * dis - 4 , yPos * dis - 3 , 30 , 30 ); // 调用胜利方法,传入参数为黑棋胜利 setVicStatus( 1 ); isMouseEnabled = false ; } // 白棋 } else if (chessColor == - 1 && isMouseEnabled) { setLocation(xPos, yPos, chessColor); isWon = checkVicStatus(xPos, yPos, chessColor); if (isWon == false ) { chessThread.sendMessage( "/" + chessPeerName + " /chess " + xPos + " " + yPos + " " + chessColor); this .add(chessWhite); chessWhite.setBounds(xPos * dis - 4 , yPos * dis- 3 , 30 , 30 ); statusText.setText( "白(第" + chessWhiteCount + "步)" + xPos + " " + yPos + ",轮到黑方." ); isMouseEnabled = false ; } else { chessThread.sendMessage( "/" + chessPeerName + " /chess " + xPos + " " + yPos + " " + chessColor); this .add(chessWhite); chessWhite.setBounds(xPos * dis- 4 , yPos * dis - 3 , 30 , 30 ); // 调用胜利方法,传入参数为白棋 setVicStatus(- 1 ); isMouseEnabled = false ; } } } /** * 画网络棋盘 * @param xPos * @param yPos * @param chessColor */ public void paintNetChessPoint( int xPos, int yPos, int chessColor) { ChessBlack chessBlack = new ChessBlack( this ); ChessWhite chessWhite = new ChessWhite( this ); setLocation(xPos, yPos, chessColor); if (chessColor == 1 ) { isWon = checkVicStatus(xPos, yPos, chessColor); if (isWon == false ) { this .add(chessBlack); chessBlack.setBounds(xPos * dis- 4 , yPos * dis - 3 , 30 , 30 ); statusText.setText( "黑(第" + chessBlackCount + "步)" + xPos + " " + yPos + ",轮到白方." ); isMouseEnabled = true ; } else { chessThread.sendMessage( "/" + chessPeerName + " /victory " + chessColor); this .add(chessBlack); chessBlack.setBounds(xPos * dis - 4 , yPos * dis- 3 , 30 , 30 ); setVicStatus( 1 ); isMouseEnabled = true ; } } else if (chessColor == - 1 ) { isWon = checkVicStatus(xPos, yPos, chessColor); if (isWon == false ) { this .add(chessWhite); chessWhite.setBounds(xPos * dis- 4 , yPos * dis- 3 , 30 , 30 ); statusText.setText( "白(第" + chessWhiteCount + "步)" + xPos + " " + yPos + ",轮到黑方." ); isMouseEnabled = true ; } else { chessThread.sendMessage( "/" + chessPeerName + " /victory " + chessColor); this .add(chessWhite); chessWhite.setBounds(xPos * dis- 4 , yPos * dis- 3 , 30 , 30 ); setVicStatus(- 1 ); isMouseEnabled = true ; } } } /** * 捕获下棋事件 * @param e */ @Override public void mousePressed(MouseEvent e) { if (e.getModifiers() == InputEvent.BUTTON1_MASK) { chessX_POS = e.getX(); System.out.println(chessX_POS); chessY_POS = e.getY(); System.out.println(chessY_POS); int a = (chessX_POS) / dis, b = (chessY_POS) / dis; System.out.println( "a=" +a); System.out.println( "b=" +b); // 下棋位置不正确时,不执行任何操作 if (chessX_POS / dis < 2 || chessY_POS / dis < 2 || chessX_POS / dis > 19 || chessY_POS / dis > 19 ) { } else { // 画棋子 paintChessPoint(a, b, chessColor); } } } @Override public void actionPerformed(ActionEvent e) {} @Override public void mouseClicked(MouseEvent e) {} @Override public void mouseReleased(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} } |
总结
通过此次的《五子棋》游戏实现,让我对swing的相关知识有了进一步的了解,对java这门语言也有了比以前更深刻的认识。
java的一些基本语法,比如数据类型、运算符、程序流程控制和数组等,理解更加透彻。java最核心的核心就是面向对象思想,对于这一个概念,终于悟到了一些。
以上就是Java+Swing实现经典五子棋游戏的详细内容
原文链接:https://juejin.cn/post/7057149264723443726