五子棋 UI篇

效果图

五子棋 UI篇_第1张图片

HTML

DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>五子棋title>
        <link rel="stylesheet" type="text/css" href="css/index.css"/>
    head>
    <body>
        <canvas id="chess" width="450px" height="450px">canvas>
        <script src="js/index.js">script>
    body>
html>

CSS

canvas{
    display: block;
    margin: 50px auto;
    box-shadow: -2px -2px 2px #EFEFEF,5px 5px 5px #B9B9B9;
}

JS

var me=true;//判断是黑棋还是白棋
var chessBoard=[];//判断是否已落子
for(var i=0;i<15;i++){
    chessBoard[i]=[];
    for(var j=0;j<15;j++){
        chessBoard[i][j]=0;
    }
}

var chess=document.getElementById("chess");
var cxt=chess.getContext('2d');

cxt.strokeStyle="#BFBFBF";
var bgimg=new Image();
bgimg.src="img/2.png";
bgimg.onload=function(){
    cxt.drawImage(bgimg,0,0,450,450);//画背景
    drawline();//画棋盘线
}

var drawline=function(){
    for(var i=0;i<15;i++)
    {
        cxt.moveTo(15+i*30,15);
        cxt.lineTo(15+i*30,435);
        cxt.stroke();
        cxt.moveTo(15,15+i*30);
        cxt.lineTo(435,15+i*30);
        cxt.stroke();
    }
}

var oneStep=function(i,j,me){//画棋子
    cxt.beginPath();
    cxt.arc(15+i*30,15+j*30,13,0,2*Math.PI);
    cxt.closePath();
    var gradient=cxt.createRadialGradient(15+i*30+2,15+j*30-2,13,15+i*30+2,15+j*30-2,0);
    if(me){
        gradient.addColorStop(0,"#0a0a0a");
        gradient.addColorStop(1,"#636766");
    }else{
        gradient.addColorStop(0,"#D1D1D1");
        gradient.addColorStop(1,"#F9F9F9");
    }

    cxt.fillStyle=gradient;
    cxt.fill();
}

chess.onclick=function(e){//点击棋盘下棋
    var x=e.offsetX;
    var y=e.offsetY;
    var i=Math.floor(x/30);
    var j=Math.floor(y/30);
    if(chessBoard[i][j]==0){
        oneStep(i,j,me);
        if(me){
            chessBoard[i][j]=1;
        }
        else{
            chessBoard[i][j]=2;
        }
        me=!me;
    }
}

你可能感兴趣的:(五子棋 UI篇)