From da41334412b348e066de3249e08ef91d96e056dd Mon Sep 17 00:00:00 2001
From: Jake Dreher <jdreherschool@gmail.com>
Date: Wed, 14 Aug 2024 20:58:55 -0400
Subject: [PATCH] Write initial api for game code

---
 app.js           |  9 +++++++
 src/game/game.js | 66 ++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 75 insertions(+)
 create mode 100644 src/game/game.js

diff --git a/app.js b/app.js
index 373acfe..4d2cfa6 100644
--- a/app.js
+++ b/app.js
@@ -1,5 +1,6 @@
 const express = require("express");
 const { WebSocketServer } = require("ws");
+const gameModule = require("./src/game/game.js");
 
 const webserver = express()
   .use((_, res) => res.sendFile("/index.html", { root: `${__dirname}/public` }))
@@ -11,6 +12,14 @@ const sockserver = new WebSocketServer({ port: 3001 });
 // This will eventually map connections to lobby or game instances
 let connections = [];
 
+let games = {};
+
+// TO BE REWRITTEN
+games["game1"] = {
+  gameBoard: gameModule.createGameBoard(100, 100),
+  players: [],
+};
+
 let gameBoard = [
   [0, 0, 0, 0, 0, 0, 0, 0, 0],
   [0, 1, 0, 0, 0, 0, 0, 0, 0],
diff --git a/src/game/game.js b/src/game/game.js
new file mode 100644
index 0000000..dfcc9d5
--- /dev/null
+++ b/src/game/game.js
@@ -0,0 +1,66 @@
+module.exports = {
+  cellTypes: {
+    EMPTY: 0,
+    PLAYERHEAD: 1,
+    PLAYERBODY: 2,
+    FOOD: 3,
+  },
+
+  createGameBoard: (width, height) => {
+    let gameBoard = [];
+    for (var i = 0; i < height; i++) {
+      row = [];
+      for (var j = 0; j < width; j++) {
+        row.push(createCell(j, i, cellTypes.EMPTY));
+      }
+      gameBoard.push(row);
+    }
+    return gameBoard;
+  },
+
+  addPlayer: (gameBoard, pid) => {
+    let x = getRandomInt(gameBoard[0].length);
+    let y = getRandomInt(gameBoard.length);
+
+    gameBoard[y][x].type = cellTypes.PLAYERHEAD;
+    gameBoard[y][x].pid = pid;
+    gameBoard[y][x].direction = 0;
+
+    let y2 = y - 1;
+    gameBoard[y2][x].type = cellTypes.PLAYERBODY;
+    gameBoard[y2][x].pid = pid;
+    gameBoard[y2][x].direction = 0;
+    gameBoard[y][x].next = gameBoard[y2][x];
+
+    return gameBoard;
+  },
+
+  moveOneStep: (gameBoard) => {
+    // Loop through board until we find a PLAYERHEAD
+    //     Move the head in the direction it is facing
+    //     if the head has a next, move the next to the head's old position
+    //     if the next has a next, move the next's next to the next's old position
+    //     and so on
+    // return the new gameBoard
+  },
+
+  checkColissions: (gameBoard) => {
+    // returns a list of players that have collided,
+    // and a new gameBoard with the players removed
+  },
+};
+
+let createCell = (x, y, type) => {
+  return {
+    x: x,
+    y: y,
+    type: type,
+    pid: 0,
+    direction: 0,
+    next: null,
+  };
+};
+
+function getRandomInt(max) {
+  return Math.floor(Math.random() * max);
+}
-- 
GitLab