-
Notifications
You must be signed in to change notification settings - Fork 412
/
Copy path5003-highlight-legal-moves.example
98 lines (77 loc) · 2.25 KB
/
5003-highlight-legal-moves.example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
===== id
5003
===== Name
Highlight Legal Moves
===== Description
Use the <code class="js plain"><a href="docs.html#config:onMouseoverSquare">onMouseoverSquare</a></code> and <code class="js plain"><a href="docs.html#config:onMouseoutSquare">onMouseoutSquare</a></code> events to highlight legal squares.
===== HTML
<div id="myBoard" style="width: 400px"></div>
===== JS
// NOTE: this example uses the chess.js library:
// https://github.com/jhlywa/chess.js
var board = null
var game = new Chess()
var whiteSquareGrey = '#a9a9a9'
var blackSquareGrey = '#696969'
function removeGreySquares () {
$('#myBoard .square-55d63').css('background', '')
}
function greySquare (square) {
var $square = $('#myBoard .square-' + square)
var background = whiteSquareGrey
if ($square.hasClass('black-3c85d')) {
background = blackSquareGrey
}
$square.css('background', background)
}
function onDragStart (source, piece) {
// do not pick up pieces if the game is over
if (game.game_over()) return false
// or if it's not that side's turn
if ((game.turn() === 'w' && piece.search(/^b/) !== -1) ||
(game.turn() === 'b' && piece.search(/^w/) !== -1)) {
return false
}
}
function onDrop (source, target) {
removeGreySquares()
// see if the move is legal
var move = game.move({
from: source,
to: target,
promotion: 'q' // NOTE: always promote to a queen for example simplicity
})
// illegal move
if (move === null) return 'snapback'
}
function onMouseoverSquare (square, piece) {
// get list of possible moves for this square
var moves = game.moves({
square: square,
verbose: true
})
// exit if there are no moves available for this square
if (moves.length === 0) return
// highlight the square they moused over
greySquare(square)
// highlight the possible squares for this piece
for (var i = 0; i < moves.length; i++) {
greySquare(moves[i].to)
}
}
function onMouseoutSquare (square, piece) {
removeGreySquares()
}
function onSnapEnd () {
board.position(game.fen())
}
var config = {
draggable: true,
position: 'start',
onDragStart: onDragStart,
onDrop: onDrop,
onMouseoutSquare: onMouseoutSquare,
onMouseoverSquare: onMouseoverSquare,
onSnapEnd: onSnapEnd
}
board = Chessboard('myBoard', config)