Last active
April 24, 2021 19:53
-
-
Save trurl-master/27749b6dff46cec9af0a845fe6916c8e to your computer and use it in GitHub Desktop.
Chess.com no click move
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Welcome to the reverse engineering hell! | |
The idea is to disable pointer interactions with the board | |
(with the exception of my pieces) when my piece is selected | |
Known issues: | |
- it won't work if your pieces are on top ("flipped" check | |
that is used to determine "my" pieces is wrong in that case) | |
*/ | |
const WHITE_PIECES = ['wp', 'wn', 'wb', 'wr', 'wq', 'wk'] | |
const BLACK_PIECES = ['bp', 'bn', 'bb', 'br', 'bq', 'bk'] | |
let isPieceSelected = false | |
// re-enable pointer events for my pieces only | |
// if enabled for all pieces click to move will | |
// still work when capturing opponent's piece | |
const adjustPiecesClickability = (chessBoard) => { | |
const isBlack = chessBoard.classList.contains('flipped') | |
const myPiecesSelector = '.' + | |
(isBlack ? BLACK_PIECES.join(',.') : WHITE_PIECES.join(',.')) | |
const opponentPiecesSelector ='.' + | |
(isBlack ? WHITE_PIECES.join(',.') : BLACK_PIECES.join(',.')) | |
Array.from(chessBoard.querySelectorAll(myPiecesSelector)) | |
.forEach(piece => piece.style.pointerEvents = 'all') | |
Array.from(chessBoard.querySelectorAll(opponentPiecesSelector)) | |
.forEach(piece => piece.style.pointerEvents = 'inherit') | |
} | |
const chessBoardPointerDownHandler = (e) => { | |
const chessBoard = document.getElementsByTagName('chess-board')[0] | |
const isBlack = chessBoard.classList.contains('flipped') | |
const myPieces = isBlack ? BLACK_PIECES : WHITE_PIECES | |
const isMyPiece = Array.from(e.target.classList).filter( | |
className => myPieces.includes(className) | |
).length > 0 | |
if (isMyPiece) { | |
// do it here, because the board isn't initialized instantly | |
// and because you can start a new game on the same board | |
adjustPiecesClickability(chessBoard) | |
if (!isPieceSelected) { | |
chessBoard.style.pointerEvents = 'none' | |
e.stopPropagation() | |
} | |
isPieceSelected = true | |
} | |
} | |
const parentPointerDownHandler = () => { | |
const chessBoard = document.getElementsByTagName('chess-board')[0] | |
chessBoard.style.pointerEvents = 'all' | |
isPieceSelected = false | |
} | |
const chessBoardCollection = document.getElementsByTagName('chess-board'); | |
if (chessBoardCollection.length > 0) { | |
const chessBoard = chessBoardCollection[0] | |
chessBoard.addEventListener('pointerdown', chessBoardPointerDownHandler) | |
chessBoard.parentElement.addEventListener('pointerdown', parentPointerDownHandler) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment