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);

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

(0)

相关推荐

  • Java实现简单井字棋小游戏代码实例

    Java第一次实验,老师让做一个井字棋,电脑随机下棋. 然后就想能不能聪明一点,可以判断出走哪一步棋:然后只能做到不会输,还是不够聪明,只能呆板地堵住用户,smartRobot的第三个判断逻辑找不到最佳位置,赢得概率比较小:而且我没事干时,想玩玩这个小游戏找找成就感,但每次都会赢了机器人,所以删删改改了四五次,最后才成. 可以选择谁先开始,但startGame里的代码更加冗余了.看着就很乱,但没想到好的办法. smartRobot里的代码全部重写了,比原来更聪明一点了:下在四个角的位置时,能优先

  • 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.ServerEndpoin

  • JavaScript Canvas实现井字棋游戏

    本文实例为大家分享了JavaScript Canvas实现井字棋游戏的具体代码,供大家参考,具体内容如下 index.html <!DOCTYPE html> <html> <head> <title>Tic Tac Toe</title> <style> * { padding: 0; margin: 0; } body, html, #game { height: 100%; background: #FCFCFC; } #gam

  • python入门之井字棋小游戏

    引言: 刚学python好几天了,从java到python,基础学起来确实比较容易,语法掌握,基本概念上都比较容易入脑. 唯一比较郁闷的是老想着用java的语法去学python代码,这点还需要后面慢慢掌握吧,相信学多种语言的你们也有这种经历吧. start:开始上代码了,希望有更好的逻辑思维来写,自己也是用最笨拙的思路去写的,如果有可以优化的代码请各位大神指教 #!/user/bin/python # -*- coding: utf-8 -*- import os import sys #棋盘模

  • JavaScript通过极大极小值算法实现AI井字棋游戏

    话不多说直接上运行截图: 黑棋是玩家的位置,红色方是电脑.电脑会根据当前棋盘的情况选择一个对自己有利却对玩家不利的情况. 算法可以实现电脑胜利,或者电脑和玩家平局. 代码如下: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>井字棋AI</title> <style> .title { text-align: center; } .

  • python实现井字棋游戏

    本文实例介绍了python实现井字棋游戏的方法,分享给大家,具体内容如下 windows7下python3.4.0编译运行通过.由于采用了cmd调用,所以与Linux不兼容,无法在Linux下运行. 游戏就是井字棋,小键盘上的数字位置对应棋盘位置. #本游戏python3.4.0下编写调试,只能在windows下运行. import random import subprocess import time #定义函数 def draw_board(the_board): subprocess.c

  • Python实现的井字棋(Tic Tac Toe)游戏示例

    本文实例讲述了Python实现的井字棋(Tic Tac Toe)游戏.分享给大家供大家参考,具体如下: 说明 用python实现了井字棋,整个框架是本人自己构思的,自认为比较满意.另外,90%+的代码也是本人逐字逐句敲的. minimax算法还没完全理解,所以参考了这里的代码,并作了修改. 特点 可以选择人人.人机.机人.机机四种对战模式之一 电脑玩家的AI使用了minimax算法,带apha-beta剪枝 电脑玩家在思考时,时时刻刻都有一个"假想敌".以便使得minimax算法运转起

  • JavaScript实现一个带AI的井字棋游戏源码

    最近有一门课结束了,需要做一个井字棋的游戏,我用JavaScript写了一个.首先界面应该问题不大,用html稍微写一下就可以.主要是人机对弈时的ai算法,如何使电脑方聪明起来,是值得思考一下的.开始游戏后,由玩家先行.那么站在计算机的角度,可以对多种情况进行分析,并按照重要程度赋予权值. 情况如下: 1.同一排(行.列.对角线)有且只有两个棋子,并且都是自己的,只要再进一步就能获胜,那么剩下的那个位置权值最高,优先级最大.赋予一级权值. 2.同一排(行.列.对角线)有且只有两个棋子,并且都是对

  • python实现简单井字棋游戏

    井字棋,英文名叫Tic-Tac-Toe,是一种在3*3格子上进行的连珠游戏,和五子棋类似,由于棋盘一般不画边框,格线排成井字故得名.游戏需要的工具仅为纸和笔,然后由分别代表O和X的两个游戏者轮流在格子里留下标记(一般来说先手者为X),任意三个标记形成一条直线,则为获胜. 游戏的难点在于,如何判断连接成了一条线:横.竖.斜三个方向: 游戏的代码: #!/usr/bin/env python3 # -*- coding:utf-8 -*- u''' Created on 2019年4月13日 @au

  • python实现井字棋小游戏

    本文为大家分享了python实现井字棋小游戏,供大家参考,具体内容如下 周五晚上上了python的选修课,本来以为老师是从python的基础语法开始的,没想到是从turtle画图开始,正好补上了我以前一些不懂的地方,有人讲一下还是比啃书好一点. 之前从图书馆借了一本python游戏编程,看了前面几章后就没怎么看了,晚上突然想看看,然后跟着教程写个游戏的.最后就有了这个井字棋的诞生,其实代码并不是很长,主要是思路,需要考虑的周全一点.代码写完后就和电脑下了好久的井字棋,一局都没赢,真的是很无奈了,

随机推荐