文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

JavaScript Canvas实现井字棋游戏

2024-04-02 19:55

关注

本文实例为大家分享了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;
            }
 
            #game {
                display: flex;
                align-items: center;
                justify-content: center;
            }
        </style>
    </head>
    <body>
        <div id="game">
            <canvas id="canvas" width="300" height="300"></canvas>
        </div>
        <script src="game.js"></script>
    </body>
</html>

game.js


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 fillRect(i, j, color = '#F5F5F5') {
    ctx.fillStyle = color;
    ctx.fillRect(i * cell_size, j * cell_size, cell_size, cell_size);
}
 
var draw = {
    grid: (color = '#ccc') => {
        for (let i = 1; i < cell_count; i++) {
            line(cell_size * i, 0, 0, size, color);
            line(0, cell_size * i, size, 0, color);
    }
    },
 
    // draw nothing, stub
    0: (i, j, _) => {
    },
 
    // draw X figure
    1: (i, j, color = '#3F51B5') => {
        let left = (i + 0.1) * cell_size,
                top = (j + 0.1) * cell_size,
                size = 0.8 * cell_size;
 
        line(left, top, size, size, color);
        line(left + size, top, -size, size, color);
    },
 
    // draw O figure
    2: (i, j, color = '#FF5722') => {
        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();
    },
 
    // draw Δ figure
    3: (i, j, color = '#FDE619') => {
        let center = (i + 0.5) * cell_size,
                size = Math.sqrt(3) * 0.525 * cell_size,
                top = (j + 0.125) * cell_size,
                height = 0.75 * cell_size,
                step = size / 2;
 
        line(center, top, -step, height, color);
        line(center, top, step, height, color);
        line(center - step, top + height, size, 0, color);
    }
};
 
 
let grid = new Array(cell_count * cell_count).fill(0),
        get = (i, j) => grid[j * cell_count + i],
        set = (i, j, val = 0) => grid[j * cell_count + i] = val,
        isFree = (i, j) => get(i, j) == 0,
        checkVictory = (who) => {
    let iterate = getter => {
        for (let i = 0; i < winCount; i++)
            if (getter(i) != who)
                return false;
        return true;
    };
 
    let row, col, path = {
        vertical: _ => iterate(i => get(row + i, col)),
        horizntl: _ => iterate(j => get(col, row + j)),
        diagonal: _ => iterate(i => get(row + i, col + i)),
        opposite: _ => iterate(i => get(row + i, col + winCount - 1 - i)),
    };
 
    for (row = 0; row <= cell_count - winCount; row++) {
        for (col = 0; col < cell_count; col++) {
            if (path.vertical())
                return ['vertical', row, col];
            if (path.horizntl())
                return ['horizntl', col, row];
        }
 
        for (col = 0; col <= cell_count - winCount; col++) {
            if (path.diagonal())
                return ['diagonal', row, col];
            if (path.opposite())
                return ['opposite', row, col];
        }
    }
 
    return [];
},
        onWin = ([type, row, col]) => {
    if (!type)
        return;
 
    let iterate = action => {
        for (let i = 0; i < winCount; i++)
            action(i);
    };
 
    let drawSequence = {
        vertical: _ => iterate(i => fillRect(row + i, col)),
        horizntl: _ => iterate(j => fillRect(row, col + j)),
        diagonal: _ => iterate(i => fillRect(row + i, col + i)),
        opposite: _ => iterate(i => fillRect(row + i, col + winCount - 1 - i)),
    };
 
    clear();
    drawSequence[type]();
    draw.grid();
 
    for (let i = 0; i < cell_count; i++) {
        for (let j = 0; j < cell_count; j++)
            draw[get(i, j)](i, j);
    }
 
    return true;
};
 
 
let playerTurn = 0;
 
function click(e) {
    let i = e.offsetX / cell_size | 0,
            j = e.offsetY / cell_size | 0;
 
    if (isFree(i, j)) {
        let figure = playerTurn++ % players + 1;
 
        set(i, j, figure);
        draw[figure](i, j);
        onWin(checkVictory(figure)) && canvas.removeEventListener('click', click, false);
        ;
    }
}
 
 
draw.grid();

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

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-前端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯