From fcd7ce5b78f0cc8f420f6ee1189e99ad81582854 Mon Sep 17 00:00:00 2001 From: Sage Vaillancourt Date: Thu, 31 Dec 2020 13:39:56 -0500 Subject: [PATCH] Board-generation from strings, and vice-versa --- src/index.js | 81 +++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 74 insertions(+), 7 deletions(-) diff --git a/src/index.js b/src/index.js index 25cc578..2f5f4da 100644 --- a/src/index.js +++ b/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];