Board-generation from strings, and vice-versa
This commit is contained in:
parent
4d927e1866
commit
fcd7ce5b78
81
src/index.js
81
src/index.js
|
@ -112,13 +112,23 @@ class Piece {
|
|||
class Board extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
squares: this.reset(),
|
||||
blackIsNext: true,
|
||||
hand: {
|
||||
heldPiece: null,
|
||||
},
|
||||
};
|
||||
if (props && props.text) {
|
||||
this.state = {
|
||||
squares: this.stateFromText(props.text),
|
||||
blackIsNext: true,
|
||||
hand: {
|
||||
heldPiece: null,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
this.state = {
|
||||
squares: this.reset(),
|
||||
blackIsNext: true,
|
||||
hand: {
|
||||
heldPiece: null,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
setHand(hand) {
|
||||
|
@ -139,6 +149,63 @@ class Board extends React.Component {
|
|||
return board;
|
||||
}
|
||||
|
||||
stateFromText(text) {
|
||||
text = text.replace(/[\n]+/g, '');
|
||||
const squares = text.substring(1);
|
||||
return {
|
||||
hand: null,
|
||||
blackIsNext: text[0].toUpperCase() === 'B',
|
||||
squares: squares.split('').map(c => {
|
||||
const type = c.toLowerCase();
|
||||
const color = c === type ? WHITE : BLACK;
|
||||
switch (type) {
|
||||
case 'r':
|
||||
return new Piece(color, ROOK);
|
||||
case 'n':
|
||||
return new Piece(color, KNIGHT);
|
||||
case 'b':
|
||||
return new Piece(color, BISHOP);
|
||||
case 'q':
|
||||
return new Piece(color, QUEEN);
|
||||
case 'k':
|
||||
return new Piece(color, KING);
|
||||
case 'p':
|
||||
return new Piece(color, PAWN);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
textFromState() {
|
||||
const turn = (this.state.blackIsNext? 'B' : 'W');
|
||||
return turn + this.state.squares.map(square => {
|
||||
if (!square) {
|
||||
return '_';
|
||||
}
|
||||
let color = (c) => {
|
||||
return square.color === BLACK ? c.toUpperCase() : c;
|
||||
};
|
||||
switch (square.type) {
|
||||
case ROOK:
|
||||
return color('r');
|
||||
case KNIGHT:
|
||||
return color('n');
|
||||
case BISHOP:
|
||||
return color('b');
|
||||
case QUEEN:
|
||||
return color('q');
|
||||
case KING:
|
||||
return color('k');
|
||||
case PAWN:
|
||||
return color('p');
|
||||
default:
|
||||
return '_';
|
||||
}
|
||||
}).join('');;
|
||||
}
|
||||
|
||||
reset() {
|
||||
let squares = [];
|
||||
const mainRow = [ROOK, KNIGHT, BISHOP, QUEEN, KING, BISHOP, KNIGHT, ROOK];
|
||||
|
|
Loading…
Reference in New Issue