찾다
웹 프론트엔드H5 튜토리얼Doudizhu 게임 구현을 위한 Html5 Canvas의 샘플 코드 분석

이제 HTML5 및 캔버스 관련 지식과 Doudizhu 데모를 읽은 후 데모에 있는 자료를 사용하여 Doudizhu를 작성해 보았습니다. 코드가 잘 리팩토링되지 않았습니다.

할 말이 많지 않으니 차근차근 설명해보자

common.js 파일이 하나뿐이다

1 . 리소스 클래스

var Resource = Class.create();
$.extend(Resource.prototype, {
    initialize: function () { },
    Images: [
        { path: 'img/bg1.png', x: 0, y: 0, w: 800, h: 480, data: null, type: 61, visible: true },
        { path: 'img/BeiMian.jpg', x: 320, y: 5, w: 100, h: 121, data: null, type: 62, visible: true },
        { path: 'img/btn.jpg', x: 300, y: 281, w: 140, h: 50, data: null, type: 63, visible: true, text: '开始', textX: 366, textY: 310 },
        { x: 0, y: 0, type: 66, isText: true, visible: false },
        { path: 'img/1.jpg', data: null, type: 16, visible: false },
        { path: 'img/2.jpg', data: null, type: 17, visible: false },
        { path: 'img/3.jpg', data: null, type: 3, visible: false, se: 1 },
        { path: 'img/4.jpg', data: null, type: 4, visible: false, se: 1 },
        { path: 'img/5.jpg', data: null, type: 5, visible: false, se: 1 },
        { path: 'img/6.jpg', data: null, type: 6, visible: false, se: 1 },
        { path: 'img/7.jpg', data: null, type: 7, visible: false, se: 1 },
        { path: 'img/8.jpg', data: null, type: 8, visible: false, se: 1 },
        { path: 'img/9.jpg', data: null, type: 9, visible: false, se: 1 },
        { path: 'img/10.jpg', data: null, type: 10, visible: false, se: 1 },
        { path: 'img/11.jpg', data: null, type: 11, visible: false, se: 1 },
        { path: 'img/12.jpg', data: null, type: 12, visible: false, se: 1 },
        { path: 'img/13.jpg', data: null, type: 13, visible: false, se: 1 },
        { path: 'img/14.jpg', data: null, type: 14, visible: false, se: 1 },
        { path: 'img/15.jpg', data: null, type: 15, visible: false, se: 1 },
        { path: 'img/16.jpg', data: null, type: 3, visible: false, se: 4 },
        { path: 'img/17.jpg', data: null, type: 4, visible: false, se: 4 },
        { path: 'img/18.jpg', data: null, type: 5, visible: false, se: 4 },
        { path: 'img/19.jpg', data: null, type: 6, visible: false, se: 4 },
        { path: 'img/20.jpg', data: null, type: 7, visible: false, se: 4 },
        { path: 'img/21.jpg', data: null, type: 8, visible: false, se: 4 },
        { path: 'img/22.jpg', data: null, type: 9, visible: false, se: 4 },
        { path: 'img/23.jpg', data: null, type: 10, visible: false, se: 4 },
        { path: 'img/24.jpg', data: null, type: 11, visible: false, se: 4 },
        { path: 'img/25.jpg', data: null, type: 12, visible: false, se: 4 },
        { path: 'img/26.jpg', data: null, type: 13, visible: false, se: 4 },
        { path: 'img/27.jpg', data: null, type: 14, visible: false, se: 4 },
        { path: 'img/28.jpg', data: null, type: 15, visible: false, se: 4 },
        { path: 'img/29.jpg', data: null, type: 3, visible: false, se: 3 },
        { path: 'img/30.jpg', data: null, type: 4, visible: false, se: 3 },
        { path: 'img/31.jpg', data: null, type: 5, visible: false, se: 3 },
        { path: 'img/32.jpg', data: null, type: 6, visible: false, se: 3 },
        { path: 'img/33.jpg', data: null, type: 7, visible: false, se: 3 },
        { path: 'img/34.jpg', data: null, type: 8, visible: false, se: 3 },
        { path: 'img/35.jpg', data: null, type: 9, visible: false, se: 3 },
        { path: 'img/36.jpg', data: null, type: 10, visible: false, se: 3 },
        { path: 'img/37.jpg', data: null, type: 11, visible: false, se: 3 },
        { path: 'img/38.jpg', data: null, type: 12, visible: false, se: 3 },
        { path: 'img/39.jpg', data: null, type: 13, visible: false, se: 3 },
        { path: 'img/40.jpg', data: null, type: 14, visible: false, se: 3 },
        { path: 'img/41.jpg', data: null, type: 15, visible: false, se: 3 },
        { path: 'img/42.jpg', data: null, type: 3, visible: false, se: 2 },
        { path: 'img/43.jpg', data: null, type: 4, visible: false, se: 2 },
        { path: 'img/44.jpg', data: null, type: 5, visible: false, se: 2 },
        { path: 'img/45.jpg', data: null, type: 6, visible: false, se: 2 },
        { path: 'img/46.jpg', data: null, type: 7, visible: false, se: 2 },
        { path: 'img/47.jpg', data: null, type: 8, visible: false, se: 2 },
        { path: 'img/48.jpg', data: null, type: 9, visible: false, se: 2 },
        { path: 'img/49.jpg', data: null, type: 10, visible: false, se: 2 },
        { path: 'img/50.jpg', data: null, type: 11, visible: false, se: 2 },
        { path: 'img/51.jpg', data: null, type: 12, visible: false, se: 2 },
        { path: 'img/52.jpg', data: null, type: 13, visible: false, se: 2 },
        { path: 'img/53.jpg', data: null, type: 14, visible: false, se: 2 },
        { path: 'img/54.jpg', data: null, type: 15, visible: false, se: 2 }
    ]
});

Resource.Images는 다양한 자료(여러 버튼, 텍스트, 54개 카드, 배경 이미지 등)입니다. 데모를 다운로드하여 살펴볼 수 있습니다. 🎜> 2. Labels 클래스, 버튼 텍스트 등 캔버스 캔버스에 텍스트를 그립니다. 관련 지식은 캔버스 튜토리얼

var Labels = Class.create();
$.extend(Labels.prototype, {
    initialize: function (cxt) {
        this.cxt = cxt;
    },
    setText: function (text, postion) {
        this.cxt.font = 'bold 20px serif';
        this.cxt.fillStyle = '#000000';
        this.cxt.textAlign = 'center';
        this.cxt.fillText(text, postion.x, postion.y);
    }
});

을 참조하세요. 이 클래스의 setText 메소드는 주로 캔버스에 텍스트를 그리는 데 사용됩니다. 설정된 글꼴, 글꼴 크기 및 글꼴 색상을 기반으로 this.cxt는 캔버스 컨텍스트입니다(이름은 각 튜토리얼마다 다름). 먼저 this.cxt.font = 'bold 20px serif'; 크기, 스타일 등, this.cxt.fillStyle = '#000000 ';이

는 글꼴 색상을 설정하는 것이고, this.cxt.textAlign = 'center';글꼴 정렬을 설정하는 것입니다. this.cxt.fillText(text, postion.x, position.y); 캔버스에 텍스트 그리기 시작입니다. position.x, position.y는 각각 x 좌표와 y 좌표입니다.

3. DdZGame 게임 카테고리의 주요 기능은 집주인 초기화, 카드 거래, 집주인 잡기 등입니다. 카드가 완료되지 않아 계속됩니다. 후속 업데이트

var DdZGame = Class.create();
DdZGame.Statics = { DealedNums: 0, isLeftFirstDeal: true };
$.extend(DdZGame.prototype, {
    initialize: function () {
        DdZGame.Statics.IsGetLander = false;
        DdZGame.Statics.DealTime = 66;
        this.leftPokers = [];
        this.rightPokers = [];
        this.myPokers = [];
        this.LastPokers = [];//最后3张牌

        this.leftPlays = [];
        this.rightPlays = [];
        this.myPlays = [];

        this.myBtnPostion = { y: 245, x: 162 };

        this.isStart = false;

        this.Res = new Resource();

        this.allPokers = new Array();

        this.Lander = 0;//地主,1右边,2My,3左边
        this.isGetLander = {};
        this.GmCanvas = document.getElementById('gmCanvas');


        this.cxt = this.GmCanvas.getContext('2d');
        this.Lbl = new Labels(this.cxt);
        this.init();
        this.initEvt();
    },
    initEvt: function () {
        this.GmCanvas.onclick = $.proxy(function (e) {
            var box = this.GmCanvas.getBoundingClientRect();

            DdZGame.Statics.MousePostion = { x: e.pageX - box.left, y: e.pageY - box.top };
            this.onControlClick();
        }, this);
    },
    onControlClick: function () {
        var isClick = false;
        for (var i = 0; i < this.Controls.length; i++) {
            var c = this.Controls[i];
            var postion = DdZGame.Statics.MousePostion;
            if (c.onClick) {
                if (postion.x >= c.x && postion.x <= c.x + c.w && postion.y >= c.y && postion.y <= c.y + c.h) {
                    c.onClick();
                    isClick = true;
                    break;
                }
            }
        }
        if (!isClick) {
            for (var i = 0; i < this.myPokers.length; i++) {
                var c = this.myPokers[i];
                var postion = DdZGame.Statics.MousePostion;
                if (c.onClick) {
                    if (postion.x >= c.x && postion.x <= c.x + c.w && postion.y >= c.y && postion.y <= c.y + c.h) {
                        c.onClick();
                        isClick = true;
                        break;
                    }
                }
            }
        }
    },
    loadImages: function (callback) {
        var loadedNums = 0;
        var totalNums = this.Res.Images.length - 1;
        this.Controls = [];
        $.each(this.Res.Images, $.proxy(function (i, o) {
            if (!o.path) {
                return true;
            }
            o.data = new Image();
            o.data.src = o.path;
            o.data.onload = $.proxy(function () {
                if (o.type <= 17) {
                    this.allPokers.push(o);
                }
                else
                    this.Controls.push(o);


                loadedNums++;
                if (loadedNums >= totalNums) {
                    callback.call(this);
                }
            }, this);
        }, this));
    },
    drawImage: function (callback, isUnVisibleLast) {//isVisibleLast 是否让底牌不可见
        $.each(this.Controls, $.proxy(function (i, o) {
            if (!o.visible)
                return true;
            if (o.type == 62) {
                var x = 0;
                for (var i = 0; i < 54 - DdZGame.Statics.DealedNums ; i++) {
                    if (i == 0) x = o.x;
                    this.cxt.drawImage(o.data, o.x, o.y, o.w, o.h);
                    o.x++;
                }
                o.x = x;
            }
            else if (!o.isText) {
                this.cxt.drawImage(o.data, o.x, o.y, o.w, o.h);
            }
            if (o.type == 63) {
                this.Lbl.setText(o.text, { x: o.textX, y: o.textY });



                if (!o.onClick)
                    o.onClick = $.proxy(function () {
                        o.onClick = null;
                        o.visible = false;
                        this.drawImage();
                        this.Dealing();
                    }, this);
            }

            if (o.type == 66) {
                this.Lbl.setText(o.text, { x: o.x, y: o.y });
            }
        }, this));


        /*克隆*/
        var copyLeftPokers = this.leftPokers.slice();
        var copyRightPokers = this.rightPokers.slice();
        var copyMyPokers = this.myPokers.slice();
        var copyLastPokers = this.LastPokers.slice();

        var isDealEndLeft = false;
        var isDealEndRight = false;
        var isDealEndMy = false;
        var isDealEndLast = false;

        var beiMain = $.grep(this.Res.Images, $.proxy(function (o, i) { return o.type == 62; }, this))[0];
        var DrawPokers = function (arry, direction, isBeiMian, identiy, axis) {
            if (arry && arry.length > 0) {
                var o = arry[0];
                var x = 0, y = 0;


                if (!DdZGame.Statics[direction]) {
                    DdZGame.Statics[direction] = this[direction];
                }

                if (!o.x) {
                    x = DdZGame.Statics[direction].x;
                    y = DdZGame.Statics[direction].y;

                    o.x = this[direction].x;
                    o.y = this[direction].y;
                }
                else {
                    x = o.x;
                    y = o.y;
                }


                if (!o.visible) {
                    return true;
                }



                o.w = 18;
                o.h = 129;
                if (arry.length == 1) {
                    o.w = 105;
                    o.h = 150;
                }







                var img = o.data;
                if (isBeiMian) {
                    img = beiMain.data;
                }
                else if (direction == &#39;myPannel&#39;) {
                    o.onClick = $.proxy(function () {
                        if (!this.isStart)
                            return;
                        if (!o.isPlay) {
                            o.isPlay = true;
                            o.y -= 30;
                        }
                        else {
                            o.isPlay = false;
                            o.y += 30;
                        }

                        DdZGame.Statics.DealTime = 0;
                        this.drawImage();
                    }, this);
                }
                this.cxt.drawImage(img, x, y);
                DdZGame.Statics[direction][axis] += identiy;

                arry.splice(0, 1);
                if (DdZGame.Statics.DealTime > 0)
                    DdZGame.Statics[direction + &#39;handle&#39;] = setTimeout($.proxy(function () {
                        DrawPokers.call(this, arry, direction, isBeiMian, identiy, axis);
                    }, this), DdZGame.Statics.DealTime);
                else
                    DrawPokers.call(this, arry, direction, isBeiMian, identiy, axis);
            }
            else if (DdZGame.Statics[direction + &#39;handle&#39;] || DdZGame.Statics.DealTime == 0) {
                clearTimeout(DdZGame.Statics[direction + &#39;handle&#39;]);


                if (direction == &#39;leftPannel&#39; && copyLeftPokers.length == 0) {
                    isDealEndLeft = true;
                }
                if (direction == &#39;rightPannel&#39; && copyRightPokers.length == 0) {
                    isDealEndRight = true;
                }
                if (direction == &#39;myPannel&#39; && copyMyPokers.length == 0) {
                    isDealEndMy = true;
                }
                if (direction == &#39;lastPannel&#39; && copyLastPokers.length == 0) {
                    isDealEndLast = true;
                }
                if (isDealEndLeft && isDealEndRight && isDealEndMy && isDealEndLast) {
                    /*发牌完毕*/
                    /*抢地主*/
                    if (callback)
                        callback();
                }
            }
        };


        DrawPokers.call(this, copyLeftPokers, &#39;leftPannel&#39;, true, 26, &#39;y&#39;);
        DrawPokers.call(this, copyRightPokers, &#39;rightPannel&#39;, true, 26, &#39;y&#39;);
        DrawPokers.call(this, copyMyPokers, &#39;myPannel&#39;, false, 19, &#39;x&#39;);

        DrawPokers.call(this, copyLastPokers, &#39;lastPannel&#39;, isUnVisibleLast, 126, &#39;x&#39;);
    },
    init: function () {
        this.loadImages(this.drawImage);
    },
    Dealing: function () {//发牌        
        this.leftPannel = { x: 5, y: 18 };
        this.rightPannel = { x: 691, y: 18 };
        this.myPannel = { x: 198, y: 330 };
        this.lastPannel = { x: 243, y: 5 };


        if (DdZGame.Statics.DealedNums >= 51) { //发牌完毕 

            $.each(this.allPokers, $.proxy(function (i, o) {
                o.visible = true;
                this.LastPokers.push(o);
            }, this));


            this.myPokers.sort(function (a, b) {
                if (a.type != b.type)
                    return b.type - a.type;
                return b.se - a.se;
            });
            $.grep(this.Res.Images, $.proxy(function (o, i) { return o.type == 62; }, this))[0].visible = false;
            this.drawImage($.proxy(function () { this.GetLander(); }, this), true);

        }
        else {
            /*1、left*/
            var index = Math.floor(Math.random() * (this.allPokers.length - 1) + 0);
            var c = this.allPokers.splice(index, 1);
            c[0].visible = true;
            this.leftPokers.push(c[0]);
            DdZGame.Statics.DealedNums++;

            /*2、right*/
            index = Math.floor(Math.random() * (this.allPokers.length - 1) + 0);
            c = this.allPokers.splice(index, 1);
            c[0].visible = true;
            this.rightPokers.push(c[0]);
            DdZGame.Statics.DealedNums++;

            index = Math.floor(Math.random() * (this.allPokers.length - 1) + 0);
            c = this.allPokers.splice(index, 1);
            c[0].visible = true;
            this.myPokers.push(c[0]);
            DdZGame.Statics.DealedNums++;

            this.Dealing();
        }
    },
    GetLander: function (firstGet, minScore, curScore) {
        /*随机出谁先叫地主*/

        //if (curScore && !this.isGetLander[1] && !this.isGetLander[2] && !this.isGetLander[3]) {
        //    //**Game Over !
        //    alert(&#39;无人抢地主&#39;);
        //    return;
        //}


        var postion = { 1: { y: 100, x: 640 }, 3: { y: 100, x: 126 }, 2: { x: 216, y: 297 } };
        if (!curScore) {
            if (!minScore)
                minScore = 1;
            if (!firstGet)
                firstGet = Math.floor(Math.random() * (3 - 1 + 1) + 1);
            if (firstGet == 1 || firstGet == 3) {  //电脑抢地主
                if (this.isGetLander[firstGet] == -1 || this.isGetLander[firstGet]) {
                    $.each(this.Controls, $.proxy(function (i, o) {
                        if (o.Lander) {
                            o.visible = false;
                        }
                    }, this));

                    var max = 0;
                    if (this.isGetLander[1] > this.isGetLander[2]) {
                        max = this.isGetLander[1];
                        this.Lander = 1;
                    }
                    else {
                        max = this.isGetLander[2];
                        this.Lander = 2;
                    }
                    if (max < this.isGetLander[3]) {
                        max = this.isGetLander[3];
                        this.Lander = 3;
                    }
                    if (max == 0) {
                        alert(&#39;Game Over !&#39;);
                        return;
                    }

                    var txt = max + &#39;分&#39;;
                    var t = {};
                    var tObj = $.grep(this.Res.Images, function (o, i) { return o.type == 66; })[0];
                    $.extend(t, tObj);//复制对象
                    if (this.CurScore == 4) {
                        txt = &#39;不抢&#39;;
                    }
                    t.text = txt;
                    t.x = postion[this.Lander].x;
                    t.y = postion[this.Lander].y;
                    t.visible = true;
                    this.Controls.push(t);



                    //this.drawImage($.proxy(function () {

                    //    this.FanDiPai(this.Lander);
                    //}, this));
                    this.FanDiPai(this.Lander);
                    return;
                }
                console.log(&#39;电脑抢地主&#39;);
                this.CurScore = Math.floor(Math.random() * (4 - minScore + 1) + minScore);

                this.isGetLander[firstGet] = this.CurScore == 4 ? -1 : this.CurScore;

                var txt = this.CurScore + &#39;分&#39;;
                var t = {};
                var tObj = $.grep(this.Res.Images, function (o, i) { return o.type == 66; })[0];
                $.extend(t, tObj);//复制对象
                if (this.CurScore == 4) {
                    txt = &#39;不抢&#39;;
                }

                t.text = txt;
                t.x = postion[firstGet].x;
                t.y = postion[firstGet].y;
                t.visible = true;

                this.Controls.push(t);

                if (this.CurScore == 3) {
                    this.Lander = firstGet;
                    //DdZGame.Statics.IsGetLander = true;
                    //DdZGame.Statics.DealTime = 0;

                    var dz = {};
                    $.extend(dz, tObj);//复制对象
                    dz.text = &#39;地主&#39;;
                    dz.x = t.x + 30;
                    dz.y = t.y;
                    dz.visible = true;

                    this.Controls.push(dz);

                    //this.drawImage($.proxy(function () { this.Play(this.Lander, &#39;电脑地主&#39;); }, this));//电脑抢到地主优先出牌
                    this.FanDiPai(this.Lander);
                    return;
                }
                else {
                    if (this.CurScore == 4) {
                        var test = &#39;abcdefg&#39;;
                    }
                    var nextGet = firstGet == 1 ? 2 : 1;
                    minScore = this.CurScore == 4 ? minScore : this.CurScore + 1;
                    this.CurScore = this.CurScore == 4 ? 0 : this.CurScore;


                    DdZGame.Statics.DealTime = 0;
                    this.drawImage($.proxy(function () { this.GetLander(nextGet, minScore); }, this), true);//电脑抢到地主优先出牌
                    return;
                }
            }
        }
        if (curScore) {
            /*代码写的很垃圾,这点没用面向对象*/
            /*My已经叫过地主,按钮需要隐藏*/
            $.each(this.Controls, $.proxy(function (i, o) {
                if (o.Lander) {
                    o.visible = false;
                }
            }, this));

            this.CurScore = curScore;
            var txt = this.CurScore + &#39;分&#39;;
            var t = {};
            var tObj = $.grep(this.Res.Images, function (o, i) { return o.type == 66; })[0];
            $.extend(t, tObj);//复制对象
            if (this.CurScore == 4) {
                txt = &#39;不抢&#39;;
            }
            t.text = txt;
            t.x = postion[2].x;
            t.y = postion[2].y;
            t.visible = true;
            this.Controls.push(t);

            this.isGetLander[2] = curScore == 4 ? -1 : curScore;

            if (this.CurScore == 3 || (this.isGetLander[1] && this.isGetLander[3] && this.CurScore != 4)) {
                this.Lander = 2;
                //DdZGame.Statics.IsGetLander = true;
                //DdZGame.Statics.DealTime = 0;

                var dz = {};
                $.extend(dz, tObj);//复制对象
                dz.text = &#39;地主&#39;;
                dz.x = t.x + 50;
                dz.y = t.y;
                dz.visible = true;

                this.Controls.push(dz);

                //this.drawImage($.proxy(function () { this.Play(this.Lander, &#39;我是地主&#39;); }, this), false);//电脑抢到地主优先出牌
                this.FanDiPai(this.Lander);
                return;
            }
            else {
                minScore = this.CurScore == 4 ? minScore : this.CurScore + 1;
                this.CurScore = this.CurScore == 4 ? 0 : this.CurScore;
                if (!this.isGetLander[3]) {
                    DdZGame.Statics.DealTime = 0;
                    this.drawImage($.proxy(function () { this.GetLander(3, minScore) }, this), true);
                    return;
                }
                else {  //已经转了一圈,则比较抢地主的分数大小
                    var max = 0;
                    if (this.isGetLander[1] > this.isGetLander[2]) {
                        max = this.isGetLander[1];
                        this.Lander = 1;
                    }
                    else {
                        max = this.isGetLander[2];
                        this.Lander = 2;
                    }
                    if (max < this.isGetLander[3]) {
                        max = this.isGetLander[3];
                        this.Lander = 3;
                    }
                    if (max == 0) {
                        alert(&#39;Game Over !&#39;);
                        return;
                    }

                    var txt = &#39;地主&#39;;
                    var t = {};
                    var tObj = $.grep(this.Res.Images, function (o, i) { return o.type == 66; })[0];
                    $.extend(t, tObj);//复制对象                   
                    t.text = txt;
                    t.x = postion[this.Lander].x;
                    t.y = postion[this.Lander].y;
                    if (this.Lander != 2) {
                        t.x += 30;
                    }
                    else {
                        t.x += 50;
                    }
                    t.visible = true;
                    this.Controls.push(t);


                    //DdZGame.Statics.DealTime = 0;
                    //this.drawImage($.proxy(function () { this.Play(this.Lander, &#39;抢地主啊&#39;); }, this), false);
                    this.FanDiPai(this.Lander);
                    return;
                }
            }
        }
        else if (this.isGetLander[2] == -1 || this.isGetLander[2]) {
            $.each(this.Controls, $.proxy(function (i, o) {
                if (o.Lander) {
                    o.visible = false;
                }
            }, this));

            var max = 0;
            if (this.isGetLander[1] > this.isGetLander[2]) {
                max = this.isGetLander[1];
                this.Lander = 1;
            }
            else {
                max = this.isGetLander[2];
                this.Lander = 2;
            }
            if (max < this.isGetLander[3]) {
                max = this.isGetLander[3];
                this.Lander = 3;
            }
            if (max == 0) {
                alert(&#39;Game Over !&#39;);
                return;
            }

            var txt = max + &#39;分&#39;;
            var t = {};
            var tObj = $.grep(this.Res.Images, function (o, i) { return o.type == 66; })[0];
            $.extend(t, tObj);//复制对象
            if (this.CurScore == 4) {
                txt = &#39;不抢&#39;;
            }
            t.text = txt;
            t.x = postion[this.Lander].x;
            t.y = postion[this.Lander].y;
            t.visible = true;
            this.Controls.push(t);


            //DdZGame.Statics.DealTime = 0;
            //this.drawImage($.proxy(function () { this.Play(this.Lander, &#39;抢地主啊&#39;); }, this), false);
            this.FanDiPai(this.Lander);
            return;
        }
        //if (DdZGame.Statics.IsGetLander) {
        //    return;
        //}
        //DdZGame.Statics.IsGetLander = true;//是否在抢地主
        console.log(&#39;我抢地主&#39;);
        var btnObj = $.grep(this.Res.Images, $.proxy(function (o, i) {
            return o.type == 63;
        }, this))[0];
        if (!this.CurScore) {
            this.CurScore = 0;
        }
        var txtX = 0;
        for (var i = 1; i <= 3; i++) {
            if (i > this.CurScore) {
                var btn = {};
                $.extend(btn, btnObj);
                btn.text = i + &#39;分&#39;;
                btn.x = this.myBtnPostion.x;
                btn.y = this.myBtnPostion.y;
                btn.visible = true;
                btn.type = 63;
                btn.textX = this.myBtnPostion.x + 30;
                btn.textY = 286;
                btn.h = 50;
                btn.w = 81;
                btn.Lander = true;
                btn.onClick = (function (i, obj) { return function () { obj.GetLander(3, i + 1, i); }; })(i, this)
                DdZGame.Statics.DealTime = 0;
                this.Controls.push(btn);
                this.myBtnPostion.x += btn.w + 10;
            }
        }
        if (DdZGame.Statics.DealTime == 0) {
            var btn = {};
            $.extend(btn, btnObj);
            btn.text = &#39;不抢&#39;;
            btn.x = this.myBtnPostion.x;
            btn.y = this.myBtnPostion.y;
            btn.visible = true;
            btn.type = 63;
            btn.textX = this.myBtnPostion.x + 30;
            btn.textY = 286;
            btn.h = 50;
            btn.w = 81;
            btn.Lander = true;
            btn.onClick = $.proxy(function () { this.GetLander(3, minScore, 4); }, this);
            this.Controls.push(btn);
            this.drawImage(null, true);
        }
    },
    FanDiPai: function (lander) {//翻底牌
        DdZGame.Statics.DealTime = 0;
        var p = &#39;&#39;;
        if (lander == 1) {
            p = &#39;rightPokers&#39;;
        }
        else if (lander == 2) {
            p = &#39;myPokers&#39;;
        }
        else if (lander == 3) {
            p = &#39;leftPokers&#39;;
        }
        /*谁抢到地主,底牌归谁*/
        $.each(this.LastPokers, $.proxy(function (i, o) {
            var c = {};
            $.extend(c, o);
            c.x = null;
            c.y = null;
            this[p].push(c);
            test = c.path;
        }, this));
        if (lander == 2) {
            this.myPokers.sort(function (a, b) {
                a.x = null;
                a.y = null;
                b.x = null;
                b.y = null;
                if (a.type != b.type)
                    return b.type - a.type;
                return b.se - a.se;
            });
            this.myPannel = { x: 198, y: 330 };
            DdZGame.Statics[&#39;myPannel&#39;] = null;
        }
        this.drawImage($.proxy(function () { this.isStart = true; this.Play(lander, &#39;是地主啊&#39;); }, this), false);
    },
    Play: function (lander, msg) {//出牌
        //alert(&#39;&#39;);
    }
});


코드 보기

초기화: 이 함수 생성자 일부 시작점 변수를 초기화합니다.

여기서 initEvt는 캔버스 이벤트를 초기화하는 것입니다. 캔버스 클릭 이벤트는 svg와 다릅니다. 왜냐하면 캔버스는 프레임별로 그려지고 그 안의 각 요소는

javascript에서 볼 수 없기 때문입니다. 물론 캔버스에서 요소를 얻는 것은 불가능합니다. 그러면 캔버스 요소의 클릭 이벤트는 어떻게 처리됩니까?

먼저 캔버스의 이벤트를 정의한 다음 마우스의 좌표를 가져오도록 정의한 다음 캔버스의 상대 좌표를 계산합니다. 각 요소에도 고유한 좌표, 너비, 높이가 있으므로 이를 판단할 수 있습니다. 이러한 좌표를 기준으로 좌표가 요소 내에 있는지 여부입니다.

onControlClick: 이 함수는 위에서 계산된 좌표를 기반으로 좌표가 요소 내에 있는지 결정하며, onclick 함수가 정의됩니다. 실제로는 아닙니다. 요소 이벤트는 객체 속성 )의 함수일 뿐이며 onclick 함수를 호출하여 해당 코드를 실행합니다.

loadImages: 모든 이미지를 로드하는 것입니다. 이미지가 로드된 후 캔버스에 초기 요소를 그리기 시작합니다.

init: 이 함수는 loadImages 함수를 호출하고 모든 이미지가 로드된 후 콜백 함수 가 호출되어 캔버스에 초기 요소를 그립니다.

딜링: 카드 딜이며, 각 측의 카드는 무작위입니다. if (DdZGame.Statics.DealedNums >= 51) 51장의 카드를 딜링한 후 홀은 3개뿐입니다. 그런 다음 캔버스에 이 51장의 카드와 3개의 구멍 카드를 뽑습니다.

GetLander: 토지 소유자를 먼저 잡는 사람이 컴퓨터에 무작위인 경우 토지 소유자를 잡는 것입니다. 첫째, 지주를 잡는 점수도 랜덤이다.

위 내용은 Doudizhu 게임 구현을 위한 Html5 Canvas의 샘플 코드 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
H5 코드 예제 : 실제 응용 프로그램 및 튜토리얼H5 코드 예제 : 실제 응용 프로그램 및 튜토리얼Apr 25, 2025 am 12:10 AM

H5는 다양한 새로운 기능과 기능을 제공하여 프론트 엔드 개발 기능을 크게 향상시킵니다. 1. 멀티미디어 지원 : 미디어를 포함하고 요소를 포함하여 플러그인이 필요하지 않습니다. 2. 캔버스 : 요소를 사용하여 2D 그래픽 및 애니메이션을 동적으로 렌더링합니다. 3. 로컬 스토리지 : LocalStorage 및 SessionStorage를 통해 지속적인 데이터 저장을 구현하여 사용자 경험을 향상시킵니다.

H5와 HTML5 사이의 연결 : 유사성과 차이H5와 HTML5 사이의 연결 : 유사성과 차이Apr 24, 2025 am 12:01 AM

H5 및 HTML5는 다른 개념입니다. HTML5는 새로운 요소 및 API를 포함하는 HTML의 버전입니다. H5는 HTML5를 기반으로 한 모바일 애플리케이션 개발 프레임 워크입니다. HTML5는 브라우저를 통해 코드를 구문 분석하고 렌더링하는 반면 H5 응용 프로그램은 컨테이너를 실행하고 JavaScript를 통해 기본 코드와 상호 작용해야합니다.

H5 코드의 빌딩 블록 : 주요 요소 및 그 목적H5 코드의 빌딩 블록 : 주요 요소 및 그 목적Apr 23, 2025 am 12:09 AM

HTML5의 주요 요소에는 최신 웹 페이지를 작성하는 데 사용되는 ,,,,, 등이 포함됩니다. 1. 헤드 컨텐츠 정의, 2. 링크를 탐색하는 데 사용됩니다. 3. 독립 기사의 내용을 나타내고, 4. 페이지 내용을 구성하고, 5. 사이드 바 컨텐츠 표시, 6. 바닥 글을 정의하면, 이러한 요소는 웹 페이지의 구조와 기능을 향상시킵니다.

HTML5 및 H5 : 일반적인 사용법 이해HTML5 및 H5 : 일반적인 사용법 이해Apr 22, 2025 am 12:01 AM

HTML5와 H5 사이에는 차이가 없으며, 이는 HTML5의 약어입니다. 1.HTML5는 HTML의 다섯 번째 버전으로 웹 페이지의 멀티미디어 및 대화식 기능을 향상시킵니다. 2.H5는 종종 HTML5 기반 모바일 웹 페이지 또는 응용 프로그램을 참조하는 데 사용되며 다양한 모바일 장치에 적합합니다.

HTML5 : 현대 웹의 빌딩 블록 (H5)HTML5 : 현대 웹의 빌딩 블록 (H5)Apr 21, 2025 am 12:05 AM

HTML5는 W3C에 의해 표준화 된 하이퍼 텍스트 마크 업 언어의 최신 버전입니다. HTML5는 새로운 시맨틱 태그, 멀티미디어 지원 및 양식 향상을 도입하여 웹 구조, 사용자 경험 및 SEO 효과를 개선합니다. HTML5는 웹 페이지 구조를 더 명확하게하고 SEO 효과를 더 좋게하기 위해, 등 등과 같은 새로운 시맨틱 태그를 소개합니다. HTML5는 멀티미디어 요소를 지원하며 타사 플러그인이 필요하지 않으므로 사용자 경험을 향상시키고 속도를로드합니다. HTML5는 양식 함수를 향상시키고 사용자 경험을 향상시키고 양식 검증 효율성을 향상시키는 새로운 입력 유형을 도입합니다.

H5 코드 : 깨끗하고 효율적인 html5 작성H5 코드 : 깨끗하고 효율적인 html5 작성Apr 20, 2025 am 12:06 AM

깨끗하고 효율적인 HTML5 코드를 작성하는 방법은 무엇입니까? 답은 태그, 구조화 된 코드, 성능 최적화 및 일반적인 실수를 피함으로써 일반적인 실수를 피하는 것입니다. 1. 코드 가독성 및 SEO 효과를 향상시키기 위해 시맨틱 태그 등을 사용하십시오. 2. 적절한 계약과 의견을 사용하여 코드를 구성하고 읽을 수 있도록하십시오. 3. CDN 및 압축 코드를 사용하여 불필요한 태그를 줄임으로써 성능을 최적화합니다. 4. 태그가 닫히지 않은 것과 같은 일반적인 실수를 피하고 코드의 유효성을 확인하십시오.

H5 : 웹에서 사용자 경험을 향상시키는 방법H5 : 웹에서 사용자 경험을 향상시키는 방법Apr 19, 2025 am 12:08 AM

H5는 멀티미디어 지원, 오프라인 스토리지 및 성능 최적화로 웹 사용자 경험을 향상시킵니다. 1) 멀티미디어 지원 : H5 및 요소는 개발을 단순화하고 사용자 경험을 향상시킵니다. 2) 오프라인 스토리지 : WebStorage 및 IndexedDB는 오프라인으로 사용하여 경험을 향상시킵니다. 3) 성능 최적화 : 웹 워즈 및 요소는 성능을 최적화하여 대역폭 소비를 줄입니다.

H5 코드 해체 : 태그, 요소 및 속성H5 코드 해체 : 태그, 요소 및 속성Apr 18, 2025 am 12:06 AM

HTML5 코드는 태그, 요소 및 속성으로 구성됩니다. 1. 태그는 컨텐츠 유형을 정의하고 다음과 같은 각도 브래킷으로 둘러싸여 있습니다. 2. 요소는 컨텐츠와 같은 시작 태그, 내용 및 엔드 태그로 구성됩니다. 3. 속성 시작 태그에서 키 값 쌍을 정의하고 기능을 향상시킵니다. 웹 구조를 구축하기위한 기본 단위입니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)