效果
思路
canvans 绘制棋盘,绘制时候边缘预留棋子位置 监听点击事件绘制落子并记录到字典中 获胜判定,在四个方向上检测是否有足够数量的连贯棋子
代码
<!DOCTYPE html>
< html lang = " en" >
< head> < meta charset = " UTF-8" > < title> ym</ title> < style> canvas { display : block; margin : 0 auto; border : 0} .result { text-align : center; } button { display : block; margin : 0 auto; padding : 4px 20px; border : 0; color : #fff; outline : none; border-radius : 3px; background : #43a6ff} button:hover { font-weight : bold; cursor : pointer; } </ style>
</ head>
< body>
< canvas id = " cv" width = " 200px" height = " 200px" > </ canvas>
< p class = " result" > </ p>
< button onclick = " loadPanel(400, 400,30,13)" > 刷新</ button>
< script> loadPanel ( 400 , 400 , 30 , 13 ) ; function loadPanel ( w, h, cs, ps) { let i, j, k; let chks = [ [ 1 , 0 ] , [ 0 , 1 ] , [ 1 , 1 ] , [ 1 , - 1 ] ] ; let successNum = 5 ; let resultEl = document. querySelector ( '.result' ) ; cs = cs || 16 ; ps = ps || 4 ; h = h || w; let el = document. getElementById ( 'cv' ) ; el. setAttribute ( 'width' , w + 'px' ) ; el. setAttribute ( 'height' , h + 'px' ) ; let context = el. getContext ( "2d" ) ; let splitX = ~ ~ ( ( w - 2 * ps) / cs) , splitY = ~ ~ ( ( h - 2 * ps) / cs) ; let pieces = { } ; context. translate ( ps, ps) ; context. beginPath ( ) ; context. strokeStyle = '#000' ; for ( i = 0 ; i < splitX + 1 ; i++ ) { context. moveTo ( cs * i, 0 ) ; context. lineTo ( cs * i, splitY * cs) ; context. stroke ( ) ; } for ( j = 0 ; j < splitY + 1 ; j++ ) { context. moveTo ( 0 , cs * j) ; context. lineTo ( splitX * cs, cs * j) ; context. stroke ( ) ; } context. closePath ( ) ; let user = 0 , colors = [ '#000' , '#fefefe' ] ; el. addEventListener ( 'click' , function ( e) { let x = e. offsetX, y = e. offsetY, rx = ~ ~ ( ( x - ps) / cs) + ( ( ( x - ps) % cs <= cs / 2 ) ? 0 : 1 ) , ry = ~ ~ ( ( y - ps) / cs) + ( ( ( y - ps) % cs <= cs / 2 ) ? 0 : 1 ) ; context. beginPath ( ) ; context. arc ( cs * rx, cs * ry, ps, 2 * Math. PI , false ) ; context. fillStyle = colors[ user] ; context. strokeStyle = '#000' ; user ? user = 0 : user = 1 ; context. fill ( ) ; context. stroke ( ) ; context. closePath ( ) ; let piece = pieces[ rx + '-' + ry] = user; for ( j = 0 ; j < chks. length; j++ ) { let num = 1 , chk = chks[ j] ; for ( i = 1 ; i <= 4 ; i++ ) { if ( pieces[ ( rx + chk[ 0 ] * i) + '-' + ( ry + chk[ 1 ] * i) ] == piece) { num++ } else { for ( i = - 1 ; i >= - 4 ; i-- ) { if ( pieces[ ( rx + chk[ 0 ] * i) + '-' + ( ry + chk[ 1 ] * i) ] == piece) { num++ } } break } } if ( num == successNum) { resultEl. innerHTML = [ '白' , '黑' ] [ user] + '方赢' ; break ; } } } ) }
</ script>
</ body>
</ html>