素材牛VIP会员
用canvas画五子棋出现的问题
 霍***跑  分类:Html5  人气:1041  回帖:1  发布于6年前 收藏

通过我的代码当我需要在canvas上下棋(描点)时,显示(里面的4只是我点击的点对应的property)

Uncaught TypeError: Cannot set property '4' of undefined
at Gobang._next 
at HTMLCanvasElement.<anonymous> 

我的部分代码如下:
html部分:

<div id="chessboard_container" class="chessboard-container hidden"></div>
<div id="chessboard_canvas_container" class="chessboard-canvas-container ">
    <canvas id="chessboard_bg_canvas" width="458" height="458"></canvas>
    <canvas id="chessboard_shadow_canvas" width="458" height="458"></canvas>
    <canvas id="chessboard_canvas" width="458" height="458"></canvas>
</div>

js部分:

function Gobang() {
        this._status = 0; // 棋局状态,0表示对战中,1表示对战结束
        this._role = 0; // 棋子颜色,0表示黑棋,1表示白棋
        this._chessDatas = []; // 存放下棋数据
        this._chessboardDatas = [];//存放棋盘数据            
        this._chessCanvas = document.getElementById('chessboard_canvas');
        this._chessContext = this._chessCanvas.getContext('2d');
    };
    
/**
     * 在canvas落子
     */
    Gobang.prototype._drawChessInCanvas = function(position,role) {
        var vm = this;
        if(position == undefined || position == null) return;
        var x = 4 + ((position % 15) + 0.5) * 30;
        var y = 4 + (parseInt((position / 15), 10) + 0.5) * 30;
        vm._chessContext.beginPath();
        vm._chessContext.arc(x, y, 13, 0, 2 * Math.PI);// 画圆
        //定义棋子颜色
        if(role){
            vm._chessContext.fillStyle = "#FFF";
        }else{
            vm._chessContext.fillStyle = "#000";
        }
        vm._chessContext.fill();
        vm._chessContext.closePath();
    };

    /**
     * 落子
     */
    Gobang.prototype._drawChess = function(position) {
        var vm = this;
        if (position === undefined || position === null) return;          
        vm._drawChessInCanvas(position, vm._role);
    };
    
/**
     * 下一步棋
     */
    Gobang.prototype._next = function(position) {
        var vm = this;
        if(vm._hasChess(position)) return;
        vm._chessboardDatas[(position % 15)][parseInt((position / 15), 10)] = vm._role;
        vm._chessDatas.push(position);

        // 绘制棋子
        vm._drawChess(position,vm._role);
    };
    
    vm._chessCanvas.addEventListener('click', function(e) {
                var x = e.offsetX;
                var y = e.offsetY;
                var i = Math.floor((x - 4) / 30);
                var j = Math.floor((y - 4) / 30);
                var position = i + j * 15;
                if(vm._status == 0) {
                    vm._next(position);
                   
                    vm._role = 1 - vm._role;
                }
            }, false);
            
            

请问我的代码如何改,才能正常实现下棋的效果。

讨论这个帖子(1)垃圾回帖将一律封号处理……

Lv3 码奴
二***了 交互设计师 6年前#1

应该

这个是空的。

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取