五子棋(圍棋) canvas node html5 js

client端

<html>
<head>
<script src="http://res.yiwugou.com/res/ywgo/js/ywgo.js"></script>
<script src="js/socket.io.js"></script>
</head>


<style>
</style>

<body style="background: #D5D5D5;">
    <div style="text-align: center; padding: 20px; height: 100%;">
        <div style="background: #FF8C00; margin: 10px 0; padding: 10px;">
            <h1 id="msg">msg</h1>
        </div>
        <canvas id="fiveChess"></canvas>

    </div>
</body>



<script type="text/javascript">
    var CommonUtils = {
        /**
         * 畫圓
         */
        drawCircle : function(ctx, x, y, r, color) {
            ctx.beginPath();
            ctx.fillStyle = color;
            ctx.lineWidth = 2;
            ctx.strokeStyle = '#000';
            //ctx.shadowOffsetX = 3; // 陰影Y軸偏移
            //ctx.shadowOffsetY = 3; // 陰影X軸偏移
            //ctx.shadowBlur = 14; // 模糊尺寸
            //ctx.shadowColor = 'rgba(0, 0, 0, 0.5)'; // 顏色
            ctx.arc(x, y, r, 0, 2 * Math.PI);
            ctx.stroke();
            ctx.fill();
        },
        /**
         * 畫圓角矩形邊框
         */
        drawRoundLine : function(ctx, x, y, w, h, r, lineWidth, strokeStyle) {
            ctx.beginPath();
            ctx.lineWidth = lineWidth || 5;
            ctx.strokeStyle = strokeStyle || '#000';//線條顏色
            ctx.moveTo(x + r, y);
            ctx.lineTo(x + w - r, y);
            ctx.arc(x + w - r, y + r, r, 3 * Math.PI / 2, 2 * Math.PI, false);
            ctx.lineTo(x + w, y + h - r);
            ctx.arc(x + w - r, y + h - r, r, 0, Math.PI / 2, false);
            ctx.lineTo(x + r, y + h);
            ctx.arc(x + r, y + h - r, r, Math.PI / 2, Math.PI, false);
            ctx.lineTo(x, y + r);
            ctx.arc(x + r, y + r, r, Math.PI, 3 * Math.PI / 2, false);
            ctx.stroke();//畫線框
        },
        /**
         * 畫圓角矩形
         */
        drawRoundRect : function(ctx, x, y, w, h, r, lineWidth, strokeStyle, fillStyle) {
            CommonUtils.drawRoundLine(ctx, x, y, w, h, r, lineWidth, strokeStyle);
            ctx.fillStyle = fillStyle || '#eee';//填充顏色
            ctx.fill();//填充顏色
        }
    };

    function ChessInfo(chess, ctx, x, y, width, height) {
        this.chess = chess;
        this.ctx = ctx;
        this.x = x;
        this.y = y;
        this.width = width || 300;
        this.height = height;
        this.padding = 20;
        this.lineWidth = 10;
        this.itemHeight = 100;
        this.itemRadius = 20;
        this.oneX = this.x + this.padding;
        this.oneY = this.y + this.padding;
        this.twoX = this.x + this.padding;
        this.twoY = this.y + this.padding * 2 + this.itemHeight;
        this.msgX = this.x + this.padding;
        this.msgY = this.y + this.padding * 3 + this.itemHeight * 2;
    }
    ChessInfo.prototype = {
        drawOne : function(strokeStyle) {
            CommonUtils.drawRoundRect(this.ctx, this.oneX, this.oneY, this.width - this.padding * 2, this.itemHeight, this.itemRadius, this.lineWidth, strokeStyle, "#B5B5B5");
            CommonUtils.drawCircle(this.ctx, this.oneX + 40, this.oneY + 50, this.itemRadius, FiveChess.USER_ONE);
        },
        drawOneName : function(name) {
            this.ctx.beginPath();
            this.ctx.font = "bold 20px Courier New";
            this.ctx.fillStyle = "#000";
            this.ctx.fillText(name, this.oneX + 70, this.oneY + 55);
        },
        drawTwo : function(strokeStyle) {
            CommonUtils.drawRoundRect(this.ctx, this.twoX, this.twoY, this.width - this.padding * 2, this.itemHeight, this.itemRadius, this.lineWidth, strokeStyle, "#B5B5B5");
            CommonUtils.drawCircle(this.ctx, this.twoX + 40, this.twoY + 50, this.itemRadius, FiveChess.USER_TWO);
        },
        drawTwoName : function(name) {
            this.ctx.beginPath();
            this.ctx.font = "bold 20px Courier New";
            this.ctx.fillStyle = "#000";
            this.ctx.fillText(name, this.twoX + 70, this.twoY + 55);
        },
        drawInfo : function() {
            this.ctx.beginPath();
            this.ctx.fillStyle = '#ff8c00';
            this.ctx.fillRect(this.x, this.y, this.width, this.height);

            this.drawOne("red");
            this.drawTwo("#fff");

            CommonUtils.drawRoundRect(this.ctx, this.msgX, this.msgY, this.width - this.padding * 2, this.itemHeight * 5, this.itemRadius, this.lineWidth, "#FFF", "#B5B5B5");
        },
        drawMsg : function(msg, line) {
            this.ctx.beginPath();
            this.ctx.font = "bold 20px Courier New";
            this.ctx.fillStyle = "#000";
            this.ctx.fillText(msg, this.msgX + 20, this.msgY + 55 * line);
        },
        changeUser : function() {
            var color = this.chess.lastPoint().color;
            if (color == FiveChess.USER_ONE) {
                CommonUtils.drawRoundLine(this.ctx, this.oneX, this.oneY, this.width - this.padding * 2, this.itemHeight, this.itemRadius, this.lineWidth, "#fff");
                CommonUtils.drawRoundLine(this.ctx, this.twoX, this.twoY, this.width - this.padding * 2, this.itemHeight, this.itemRadius, this.lineWidth, "red");
            } else {
                CommonUtils.drawRoundLine(this.ctx, this.oneX, this.oneY, this.width - this.padding * 2, this.itemHeight, this.itemRadius, this.lineWidth, "red");
                CommonUtils.drawRoundLine(this.ctx, this.twoX, this.twoY, this.width - this.padding * 2, this.itemHeight, this.itemRadius, this.lineWidth, "#fff");
            }
        }
    };

    function FiveChess(num, id) {
        var infoWidth = 300;
        this.num = num;
        this.id = id;
        this.cvs = document.getElementById(this.id);
        this.ctx = this.cvs.getContext('2d');
        this.cellWidth = 50;//棋盤格單元大小
        this.paddingTop = this.cellWidth * 1.5;
        this.paddingLeft = this.cellWidth * 1.5;
        this.boardArray = [];
        this.historyPoints = [];
        this.boardWidth = this.paddingLeft * 2 + this.cellWidth * (this.num - 1);
        this.boardHeight = this.paddingTop * 2 + this.cellWidth * (this.num - 1);
        this.cvs.width = this.boardWidth + 20 + infoWidth;
        this.cvs.height = this.boardHeight;
        this.chessInfo = new ChessInfo(this, this.ctx, this.boardWidth + 20, 0, infoWidth, this.boardHeight);
        this.status = 0;
        this.fromUser = '';
        this.toUser = '';
        this.room = '';
        this.socket = '';
    }
    FiveChess.prototype = {
        init : function() {
            this.initBoardArray();
            this.drawBoard();
            this.drawInfo();
            this.addEvent();
        },
        initBoardArray : function() {
            for (var i = 1; i <= this.num; i++) {
                this.boardArray[i] = new Array();
                for (var j = 1; j <= this.num; j++) {
                    this.boardArray[i][j] = 0;
                }
            }
        },

        lastPoint : function() {
            var len = this.historyPoints.length;
            if (len == 0) {
                return new Point(0, 0, FiveChess.USER_TWO);
            } else {
                return this.historyPoints[len - 1];
            }
        },
        changeColor : function(color) {
            if (color == FiveChess.USER_ONE) {
                return FiveChess.USER_TWO;
            } else {
                return FiveChess.USER_ONE;
            }
        },
        drawInfo : function() {
            this.chessInfo.drawInfo();
        },
        drawBoard : function() {
            this.ctx.beginPath();
            this.ctx.fillStyle = "#ff8c00";
            this.ctx.fillRect(0, 0, this.boardWidth, this.boardWidth);

            this.ctx.beginPath();
            this.ctx.fillStyle = '#eee';//填充顏色
            this.ctx.strokeStyle = '#000';//線條顏色
            this.ctx.lineWidth = 2;//設置線寬
            for (var i = 1; i <= this.num; i++) {//劃橫
                this.ctx.moveTo(this.paddingLeft, this.paddingTop + this.cellWidth * (i - 1));
                this.ctx.lineTo(this.paddingLeft + this.cellWidth * (this.num - 1), this.paddingTop + this.cellWidth * (i - 1));
            }
            for (var i = 1; i <= this.num; i++) {//劃豎
                this.ctx.moveTo(this.paddingLeft + this.cellWidth * (i - 1), this.paddingTop);
                this.ctx.lineTo(this.paddingLeft + this.cellWidth * (i - 1), this.paddingTop + this.cellWidth * (this.num - 1));
            }
            this.ctx.stroke();//畫線框
            this.ctx.fill();//填充顏色
            //this.ctx.closePath();

            this.ctx.beginPath();
            this.ctx.font = "bold 20px Courier New";
            this.ctx.fillStyle = "#000";
            for (var i = 1; i <= this.num; i++) {
                var code = 'A'.charCodeAt() - 1 + i;
                this.ctx.fillText(String.fromCharCode(code), this.paddingLeft + (i - 1) * this.cellWidth - 5, this.paddingTop - 25);
            }
            for (var i = 1; i <= this.num; i++) {
                this.ctx.fillText(i + '', this.paddingLeft + this.cellWidth * (this.num - 1) + 25, this.paddingTop + (i - 1) * this.cellWidth + 5);
            }
        },
        addEvent : function() {
            var self = this;
            this.cvs.addEventListener('click', function(e) {
                var wx = e.layerX;
                var wy = e.layerY;
                var x = parseInt((wx - self.paddingLeft + self.cellWidth / 2) / self.cellWidth) + 1;
                var y = parseInt((wy - self.paddingTop + self.cellWidth / 2) / self.cellWidth) + 1;
                var currColor = self.changeColor(self.lastPoint().color);
                var point = new Point(x, y, currColor);
                if (self.status == 1 && self.drawChess(point)) {
                    self.emitPrivate(point);
                    self.status = 2;
                    $("#msg").html('Waiting for the opponent to play chess......');
                }
            }, false);
        },
        drawChess : function(point) {
            var x = point.x;
            var y = point.y;
            var color = point.color;
            if (x > 0 && y > 0 && x <= this.num && y <= this.num && this.boardArray[x][y] == 0) {
                this.boardArray[x][y] = color;
                this.historyPoints.push(point);
                this.chessInfo.changeUser();
                CommonUtils.drawCircle(this.ctx, point.getLayerX(this.cellWidth, this.paddingLeft), point.getLayerY(this.cellWidth, this.paddingTop), (this.cellWidth - 5) / 2,
                        point.color);
                return true;
            }
            return false;
        },
        initSocket : function() {
            var self = this;
            this.socket = io.connect('http://10.6.104.111:10000');
            this.socket.on("connect", function() {

            });

            this.socket.emit('login', {
                name : self.fromUser,
                room : self.room
            }, function(data) {
                console.info(data);
                if (data.code == -1) {
                    $("#msg").html("Room Full! Please choose another room.");
                } else if (data.code == -2) {
                    $("#msg").html("Waiting for another user.");
                }
            });

            this.socket.on('private', function(data) {
                console.info(data);
                var point = new Point(data.x, data.y, data.color);
                if (self.status == 2 && self.drawChess(point)) {
                    self.status = 1;
                    $("#msg").html("Now it's your turn!!!");
                }
            });

            this.socket.on('status', function(data) {
                console.info(data);
                self.toUser = data.toUser;
                self.status = data.status;
                if (data.status == 1) {
                    $("#msg").html("It's your turn");
                    self.chessInfo.drawOneName('Self:' + self.fromUser);
                    self.chessInfo.drawTwoName('Opp:' + self.toUser);
                } else if (data.status == 2) {
                    $("#msg").html("Wait Opponent chess");
                    self.chessInfo.drawOneName('Opp:' + self.toUser);
                    self.chessInfo.drawTwoName('Self:' + self.fromUser);
                }
            });
        },
        emitPrivate : function(point) {
            var sendData = {
                room : this.room,
                fromUser : this.fromUser,
                toUser : this.toUser,
                x : point.x,
                y : point.y,
                color : point.color
            };
            this.socket.emit('private', sendData, function(data) {
                console.info(data);
            });
        }
    };
    FiveChess.USER_ONE = '#000';
    FiveChess.USER_TWO = '#FFF';

    function Point(x, y, color) {
        this.x = x;
        this.y = y;
        this.color = color;
        this.getLayerX = function(cellWidth, paddingLeft) {
            return cellWidth * (this.x - 1) + paddingLeft;
        };
        this.getLayerY = function(cellWidth, paddingTop) {
            return cellWidth * (this.y - 1) + paddingTop
        };
    }

    $(function() {
        var fiveChess = new FiveChess(15, 'fiveChess');
        fiveChess.init();

        var room = $.trim(prompt("Room", ""));
        if (room == '') {
            return;
        }
        fiveChess.chessInfo.drawMsg('Room:' + room, 1);
        var fromUser = $.trim(prompt("Your name", ""));
        if (fromUser == '') {
            return;
        }
        fiveChess.fromUser = fromUser;
        fiveChess.room = room;
        fiveChess.initSocket();
    });
</script>






服務器端

var io = require('socket.io')(10000);

var ROOM_LIST = {};

io.on('disconnect', function (socket) {
    console.info('disconnect');
});
io.on('connection', function (socket) {
    socket.on("login", function (data, callback) {
        console.info('login:' + data);
        var room = data.room;
        var name = data.name;

        console.info('1:' + room + '--' + name);
        if (room == '' || name == '') {
            callback({
                code : -3,
                msg : 'error'
            });
        }
        var obj = {
            socket : socket,
            name : data.name,
            lastLogin : new Date().getTime()
        };
        if (!ROOM_LIST[room]) {
            ROOM_LIST[room] = {};
        }
        var roomSize = ROOM_LIST[room].size || 0;
        if (roomSize == 2) {
            callback({
                code : -1,
                msg : 'Room Full'
            });
            return;
        }
        if (roomSize == 0) {
            ROOM_LIST[room].users = {};
            ROOM_LIST[room].one = obj;
            callback({
                code : -2,
                msg : 'Waiting for another user'
            });
        }
        if (roomSize == 1) {
            ROOM_LIST[room].two = obj;
            ROOM_LIST[room].one.socket.emit('status', {
                room : room,
                status : 1,
                toUser : name,
                msg : "Begin -- It's your turn"
            });
            ROOM_LIST[room].two.socket.emit('status', {
                room : room,
                status : 2,
                toUser : ROOM_LIST[room].one.name,
                msg : 'Begin -- Wait Opponent'
            });
        }

        ROOM_LIST[room].size = ++roomSize;
        ROOM_LIST[room].users[name] = obj;
    });

    socket.on("private", function (data, callback) {
        console.info(data);

        var room = data.room;
        var fromUser = data.fromUser;
        var toUser = data.toUser;

        if (ROOM_LIST[room] && ROOM_LIST[room].users && ROOM_LIST[room].users[toUser]) {
            ROOM_LIST[room].users[toUser].socket.emit('private', {
                room : room,
                fromUser : fromUser,
                toUser : toUser,
                x : data.x,
                y : data.y,
                color : data.color
            });
            callback({});
        } else {
            callback({});
        }

    });

    console.info('Server Start Success!');
});












下載地址   http://download.csdn.net/detail/rgbaflf/9435669

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章