1
0
mirror of https://github.com/danbee/chess synced 2025-03-04 08:39:06 +00:00
chess/assets/js/components/chess-board-square.js
Dan Barber bedd6605ef
Redesign whole site in B&W
* Forms and board tweaks for small screen sizes
* Re-style game status indicators
* Re-style viewing/offline indicator
* Better eyecons 👁
* Re-organise CSS according to ITCSS principles
* Pick new font from Google Fonts
* Fix up tests
* Move some things into partials
2018-09-16 14:02:52 -04:00

100 lines
2.3 KiB
JavaScript

import React from "react";
import _ from "lodash";
import classNames from "classnames";
import API from "../services/api";
import { selectPiece } from "../store/actions";
class ChessBoardSquare extends React.Component {
constructor(props) {
super(props);
}
get squareCoords() {
return [this.props.file, this.props.rank];
}
get squareId() {
return `f${this.props.file}-r${this.props.rank}`;
}
get squareClass() {
if (this.props.piece == undefined) {
return classNames(
"square",
{ "square--available": this.isAvailableSquare() }
);
} else {
return classNames(
"square",
`square--${this.props.piece.type}`,
`square--${this.props.piece.colour}`,
{ "square--selected": this.isSelectedSquare() },
{ "square--available": this.isAvailableSquare() }
);
}
}
selectSquare() {
const { piece, store, channel } = this.props;
const { gameId, selectedSquare, player } = store.getState();
if (this.moveIsValid(selectedSquare)) {
channel.sendMove({
from: selectedSquare,
to: this.squareCoords,
});
} else if (selectedSquare != null) {
store.dispatch(selectPiece(null));
} else if (this.playerCanSelectPiece(player, piece)) {
store.dispatch(selectPiece(this.squareCoords));
channel.getAvailableMoves(this.squareCoords);
}
}
moveIsValid(selectedSquare) {
return selectedSquare != null &&
!this.isSelectedSquare() &&
this.isAvailableSquare();
}
playerCanSelectPiece(player, piece) {
const { store } = this.props;
const { turn } = store.getState();
return piece !== undefined &&
piece.colour == player &&
player == turn;
}
isSelectedSquare() {
const { store } = this.props;
if (store.getState().selectedSquare == null) {
return false;
} else {
return _.isEqual(this.squareCoords, store.getState().selectedSquare);
}
}
isAvailableSquare() {
const { store } = this.props;
const availableMoves = store.getState().availableMoves;
return _.find(availableMoves, (square) => {
return square.join() == this.squareCoords.join();
});
}
render() {
return <div
id={this.squareId}
className={this.squareClass}
onClick={this.selectSquare.bind(this)}
/>;
}
}
export default ChessBoardSquare;