components: add move validation, draw lines on mouse move

This commit is contained in:
Artur Tamborski 2020-11-28 09:55:59 +01:00
parent ec3be89ad4
commit 27b824c235
3 changed files with 23 additions and 19 deletions

View File

@ -14,7 +14,7 @@ export default function App(): JSX.Element {
<Board
numRows={10}
numCols={10}
numLines={1}
numLines={5}
/>
</div>
<div />

View File

@ -17,7 +17,7 @@ interface IBoardProps {
interface IBoardState {
cells: string[][];
lines: string[];
lines: boolean[];
isSelecting: boolean;
startPos: Point;
endPos: Point;
@ -29,33 +29,34 @@ export default class Board extends React.Component<IBoardProps, IBoardState> {
this.state = {
cells: Array(props.numCols).fill(Array(props.numRows).fill('A')),
lines: Array(props.numLines).fill(''),
lines: Array(props.numLines).fill(false),
isSelecting: false,
startPos: {x: 0, y: 0},
endPos: {x: 0, y: 0},
}
}
moveIsValid(pos: Point): boolean {
const x = Math.abs(pos.x - this.state.startPos.x);
const y = Math.abs(pos.y - this.state.startPos.y);
const lineIsValid = x === 0 || y === 0 || x === y;
return this.state.isSelecting && lineIsValid;
}
handleMouseDown(startPos: Point) {
this.setState({...this.state, startPos, isSelecting: true});
const endPos = startPos;
this.setState({...this.state, startPos, endPos, isSelecting: true});
}
handleMouseUp(endPos: Point) {
const x = Math.abs(endPos.x - this.state.startPos.x);
const y = Math.abs(endPos.y - this.state.startPos.y);
if (!(x === 0 || y === 0 || x === y))
return;
if (this.moveIsValid(endPos))
this.setState({...this.state, endPos, isSelecting: false});
}
handleMouseOver(currentPos: Point) {
if (!this.state.isSelecting) {
this.setState({...this.state});
} else {
}
handleMouseOver(endPos: Point) {
if (this.moveIsValid(endPos))
this.setState({...this.state, endPos});
}
renderCell(s: string, pos: Point): JSX.Element {
@ -76,9 +77,10 @@ export default class Board extends React.Component<IBoardProps, IBoardState> {
return (
<Line
key={`Line${x}`}
startPos={this.state.startPos}
endPos={this.state.endPos}
startPos={{...this.state.startPos}}
endPos={{...this.state.endPos}}
cellSize={60}
isVisible={this.state.lines[0]}
/>
);
}

View File

@ -8,6 +8,7 @@ interface ILineProps {
startPos: Point;
endPos: Point;
cellSize: number;
isVisible: boolean;
}
export default function Line(props: ILineProps): JSX.Element {
@ -16,6 +17,7 @@ export default function Line(props: ILineProps): JSX.Element {
return (
<line
className="Line"
// style={{display: props.isVisible ? 'shown' : 'hidden'}}
x1={`${pos(props.endPos.x)}`}
y1={`${pos(props.endPos.y)}`}
x2={`${pos(props.startPos.x)}`}