aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorThomas Voss <thomasvoss@live.com> 2022-01-09 23:45:47 +0100
committerThomas Voss <thomasvoss@live.com> 2022-01-09 23:45:47 +0100
commitfc39c5256e9366d417a64ec4a3554eab5c84c64b (patch)
tree4ef19ffcad90f7e7053dea793168b79a51fcdf54
parent1053479c039e120fc892384084a76ff0ed11e1a9 (diff)
Create a game class
The game class contains the entire state of the game, its history, and the websockets connected to both clients. The class also has a `messageAll()' method which can be used to send a message to both of the clients. The `boardInit()' function can be used to initialize a brand new 10x10 draughts board.
-rw-r--r--draughts/game.js51
1 files changed, 36 insertions, 15 deletions
diff --git a/draughts/game.js b/draughts/game.js
index 40b0c1d..748c696 100644
--- a/draughts/game.js
+++ b/draughts/game.js
@@ -1,19 +1,40 @@
-const websocket = requre("ws");
+const WebSocket = require("ws")
-const game = function(gameID){
- this.playerRed;
- this.playerBlue;
- this.id = gameID;
- this.gameState = "0 JOINT";
+const Color = require("./color")
+const Piece = require("./piece")
+
+/* Initialize and return new 10x10 draughts board */
+const boardInit = () => [
+ /* Initialize the blue pieces */
+ Array.from({ length: 10 }, (_, i) => (i & 1) ? null : new Piece(i, 0, i >> 1, Color.BLUE)),
+ Array.from({ length: 10 }, (_, i) => (i & 1) ? new Piece(i, 1, (i >> 1) + 5, Color.BLUE) : null),
+ Array.from({ length: 10 }, (_, i) => (i & 1) ? null : new Piece(i, 2, (i >> 1) + 10, Color.BLUE)),
+ Array.from({ length: 10 }, (_, i) => (i & 1) ? new Piece(i, 3, (i >> 1) + 15, Color.BLUE) : null),
+
+ /* Initialize the empty middle rows */
+ Array.from({ length: 10 }, () => null),
+ Array.from({ length: 10 }, () => null),
+
+ /* Initialize the red pieces */
+ Array.from({ length: 10 }, (_, i) => (i & 1) ? null : new Piece(1, 6, i >> 1, Color.RED)),
+ Array.from({ length: 10 }, (_, i) => (i & 1) ? new Piece(1, 7, (i >> 1) + 5, Color.RED) : null),
+ Array.from({ length: 10 }, (_, i) => (i & 1) ? null : new Piece(1, 8, (i >> 1) + 10, Color.RED)),
+ Array.from({ length: 10 }, (_, i) => (i & 1) ? new Piece(1, 9, (i >> 1) + 15, Color.RED) : null),
+]
+
+/* A class representing a game. It contains the current game state as well as the complete move
+ * history and the websockets of both players.
+ */
+const Game = function(gameID) {
+ this.id = gameID
+ this.board = boardInit()
+ this.ongoing = false
+ this.bluePlayer = null
+ this.redPlayer = null
+ this.history = [] /* [ { blue: "42x31", red: "19-24" }, ... ] */
}
-game.prototype.transitionStates = {
- "0 JOINT": 0,
- "1 JOINT": 1,
- "2 JOINT": 2,
- "Red": 3, //Red won
- "Blue": 4, //Blue won
- "ABORTED": 5
- };
+/* Send the message `msg' to both players */
+Game.prototype.messageAll = msg => [this.bluePlayer, this.redPlayer].forEach(p => p.send(msg))
- \ No newline at end of file
+module.exports = Game