-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBoard.js
91 lines (73 loc) · 1.95 KB
/
Board.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const BoardSettings = require('./BoardSettings');
const Move = require('./Move');
const Square = require('./Square');
const State = require('./State');
/**
* Represents a Board.
*/
class Board {
/**
* Create a board.
* @param {object} settings - The board settings.
*/
constructor(settings) {
this.boardSettings = settings instanceof BoardSettings ? settings : new BoardSettings(settings);
// clear the board first
this.clear();
// set the start position
this.addStartState();
}
clear() {
this.states = [];
}
addStartState() {
// create the starting state
let state = new State(this.boardSettings);
state.setStartingPosition();
this.addState(state);
}
addState(State) {
this.states.push(State);
}
// function get the last/current state
getCurrentState() {
// the current state is read-only
return this.states.length ? this.states[this.states.length - 1].clone() : null;
}
// move a piece in the current state
move(fromX, fromY, toX, toY) {
let current = this.getCurrentState();
if(!current) {
return false;
}
let move = new Move(current.getSquare(fromX,fromY), current.getSquare(toX,toY));
// validate move - (beforeMove,afterMove) then return state if valid or false
if(!current.validateMove(move)) { // possibleMoves() then move(move)
return false;
}
current.beforeMove(move);
let newState = current.move(move);
current.afterMove(move);
if(!newState) {
return false;
}
// validate state - return modified state if valid or false
if(newState) {
// validate the state
if(newState.validate()) { // check win, lose, draw, errors
// end turn
// add the state to the board
this.addState(newState);
return newState;
}
}
return false;
}
}
module.exports = {
Board: Board,
BoardSettings: BoardSettings,
State: State,
Square: Square,
Move: Move
}