From 8ad1d1a0587c86e94458852f0979ca5e72c5c2dc Mon Sep 17 00:00:00 2001 From: Jake Dreher <jdreherschool@gmail.com> Date: Sat, 10 Aug 2024 22:58:26 -0400 Subject: [PATCH] 1-develop-web-socket-code - Run prettier --- README.md | 2 +- app.js | 178 +++++++++++++++++---------------- package.json | 40 ++++---- public/index.html | 216 ++++++++++++++++++++-------------------- src/game/gameLogic.js | 21 ++-- src/game/index.js | 34 +++---- tests/websocket.test.js | 102 +++++++++---------- 7 files changed, 298 insertions(+), 295 deletions(-) diff --git a/README.md b/README.md index 7895cb8..f12c049 100644 --- a/README.md +++ b/README.md @@ -12,10 +12,10 @@ This is a repository for the CS375 Web Development course at Drexel University. - [ ] Chat - Chat with other players in the waiting room - [ ] Skins - Customizable snake skins - ## Rooms When a user creates a room, update internal data table to reflect new room. Send message to client containing all available rooms, and whether they are private or public. User can set a password for the private rooms. + <!-- ## Getting started diff --git a/app.js b/app.js index 8ad230c..f7eff54 100644 --- a/app.js +++ b/app.js @@ -1,96 +1,104 @@ -const express = require('express') -const { WebSocketServer } = require('ws') +const express = require("express"); +const { WebSocketServer } = require("ws"); const webserver = express() - .use((_, res) => - res.sendFile('/index.html', { root: `${__dirname}/public` }) - ) - .listen(3000, () => console.log(`Listening on ${3000}`)) + .use((_, res) => res.sendFile("/index.html", { root: `${__dirname}/public` })) + .listen(3000, () => console.log(`Listening on ${3000}`)); -const sockserver = new WebSocketServer({ port: 3001 }) +const sockserver = new WebSocketServer({ port: 3001 }); // Maintain a list of connections // This will eventually map connections to lobby or game instances -let connections = [] +let connections = []; -let gameBoard = [ [0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 1, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0] ] +let gameBoard = [ + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], +]; let moveHandler = (connection, message) => { - console.log('Received move: ' + message.data) - let movement = message.data; - - for(var i = 0; i < gameBoard.length; i++) { - for(var j = 0; j < gameBoard[0].length; j++) { - if(movement === "up" && gameBoard[i][j] === 1 && i > 0) { - gameBoard[i][j] = 0; - gameBoard[i-1][j] = 1; - return; - } - - if(movement === "down" && gameBoard[i][j] === 1 && i < gameBoard.length - 1) { - gameBoard[i][j] = 0; - gameBoard[i+1][j] = 1; - return; - } - - if(movement === "left" && gameBoard[i][j] === 1 && j > 0) { - gameBoard[i][j] = 0; - gameBoard[i][j-1] = 1; - return; - } - - if(movement === "right" && gameBoard[i][j] === 1 && j < gameBoard[0].length - 1) { - gameBoard[i][j] = 0; - gameBoard[i][j+1] = 1; - return; - } - } - } -} - -sockserver.on('connection', connection => { - console.log('New client connected!') - - connections.push(connection) - - connection.on('close', () => { - connections = connections.filter(curr => curr !== connection) - console.log('Client has disconnected!') - }); - - connection.on('message', (event) => { - try { - let message = JSON.parse(event) - // All messages are expected to have a type - if (message.type === 'move') { - console.log('Received move: ' + message.data) - moveHandler(connection, message) - connection.send(JSON.stringify({ type: 'gameBoard', data: gameBoard })) - } else if (message.type === 'chat') { - console.log('Received chat: ' + message.data) - } else if (message.type === 'join') { - console.log('Received join: ' + message.data) - connection.send(JSON.stringify({ type: 'gameBoard', data: gameBoard })) - } else if (message.type === 'leave') { - console.log('Received leave: ' + message.data) - } else { - console.log('Received: ' + message) - } - } catch (e) { - console.log('Error parsing JSON: ' + message) - } - }) - - connection.onerror = function () { - console.log('websocket error') - } -}) - -console.log('Server started.') + console.log("Received move: " + message.data); + let movement = message.data; + + for (var i = 0; i < gameBoard.length; i++) { + for (var j = 0; j < gameBoard[0].length; j++) { + if (movement === "up" && gameBoard[i][j] === 1 && i > 0) { + gameBoard[i][j] = 0; + gameBoard[i - 1][j] = 1; + return; + } + + if ( + movement === "down" && + gameBoard[i][j] === 1 && + i < gameBoard.length - 1 + ) { + gameBoard[i][j] = 0; + gameBoard[i + 1][j] = 1; + return; + } + + if (movement === "left" && gameBoard[i][j] === 1 && j > 0) { + gameBoard[i][j] = 0; + gameBoard[i][j - 1] = 1; + return; + } + + if ( + movement === "right" && + gameBoard[i][j] === 1 && + j < gameBoard[0].length - 1 + ) { + gameBoard[i][j] = 0; + gameBoard[i][j + 1] = 1; + return; + } + } + } +}; + +sockserver.on("connection", (connection) => { + console.log("New client connected!"); + + connections.push(connection); + + connection.on("close", () => { + connections = connections.filter((curr) => curr !== connection); + console.log("Client has disconnected!"); + }); + + connection.on("message", (event) => { + try { + let message = JSON.parse(event); + // All messages are expected to have a type + if (message.type === "move") { + console.log("Received move: " + message.data); + moveHandler(connection, message); + connection.send(JSON.stringify({ type: "gameBoard", data: gameBoard })); + } else if (message.type === "chat") { + console.log("Received chat: " + message.data); + } else if (message.type === "join") { + console.log("Received join: " + message.data); + connection.send(JSON.stringify({ type: "gameBoard", data: gameBoard })); + } else if (message.type === "leave") { + console.log("Received leave: " + message.data); + } else { + console.log("Received: " + message); + } + } catch (e) { + console.log("Error parsing JSON: " + message); + } + }); + + connection.onerror = function () { + console.log("websocket error"); + }; +}); + +console.log("Server started."); // Game loop //setInterval(() => { @@ -99,5 +107,3 @@ console.log('Server started.') // connection.send('Hello, world!') // }) //}, 1000); - - diff --git a/package.json b/package.json index e3940e0..9c07861 100644 --- a/package.json +++ b/package.json @@ -1,22 +1,22 @@ { - "name": "web-dev", - "version": "1.0.0", - "description": "", - "main": "app.js", - "scripts": { - "test": "jest", - "start": "node app.js", - "format:check": "prettier --check .", - "format:write": "prettier --write ." - }, - "author": "", - "license": "ISC", - "devDependencies": { - "jest": "^29.7.0", - "prettier": "^3.3.3" - }, - "dependencies": { - "express": "^4.19.2", - "ws": "^8.18.0" - } + "name": "web-dev", + "version": "1.0.0", + "description": "", + "main": "app.js", + "scripts": { + "test": "jest", + "start": "node app.js", + "format:check": "prettier --check .", + "format:write": "prettier --write ." + }, + "author": "", + "license": "ISC", + "devDependencies": { + "jest": "^29.7.0", + "prettier": "^3.3.3" + }, + "dependencies": { + "express": "^4.19.2", + "ws": "^8.18.0" + } } diff --git a/public/index.html b/public/index.html index 4826bf6..8f45579 100644 --- a/public/index.html +++ b/public/index.html @@ -1,109 +1,111 @@ -<!DOCTYPE html> +<!doctype html> <html lang="en"> - - <head> - <title>WebSocket Example</title> - </head> - - <body> - <h1>WebSocket Client</h1> - <input type="text" - id="messageInput" - placeholder="Type a message..." /> - <button id="sendButton"> - Send - </button> - <div id="messages"> - </div> - - <div id="game"> - <canvas id="gameCanvas" width="800" height="600"></canvas> - </div> - - <script> - const joinMessage = {type: 'join', data: 'Hello, server'}; - const socket = new WebSocket('ws://127.0.0.1:3001'); - - const canvas = document.getElementById('gameCanvas'); - const width = canvas.width; - const height = canvas.height; - - let moveMessage = {type: 'move', data: 'up'}; - - let gameBoardHandler = (event) => { - let ctx = canvas.getContext('2d'); - ctx.clearRect(0, 0, width, height); - ctx.fillStyle = 'black'; - ctx.fillRect(0, 0, width, height); - ctx.fillStyle = 'white'; - - let board = event.data; - - widthStep = width / board[0].length; - heightStep = height / board.length; - - for(let i = 0; i < board.length; i++) { - for(let j = 0; j < board[i].length; j++) { - if(board[i][j] === 0) { - ctx.fillRect(j * widthStep + 1, i * heightStep + 1, widthStep-2, heightStep-2); - } - if(board[i][j] === 1) { - ctx.fillStyle = 'red'; - ctx.fillRect(j * widthStep + 1, i * heightStep + 1, widthStep-2, heightStep-2); - ctx.fillStyle = 'white'; - } - } - } - }; - - socket.addEventListener('open', () => { - console.log('Connected to server'); - socket.send(JSON.stringify(joinMessage)); - }); - - socket.addEventListener('message', (event) => { - try { - let msg = JSON.parse(event.data); - if(msg.type === 'gameBoard') { - gameBoardHandler(msg); - } else { - const messages = document.getElementById('messages'); - const messageElement = document.createElement('div'); - messageElement.innerText = event.data; - messages.appendChild(messageElement); - } - } catch { - console.log(event.data); - } - }); - - document.addEventListener('keydown', (event) => { - if(event.key === 'ArrowUp') { - moveMessage.data = 'up'; - socket.send(JSON.stringify(moveMessage)); - } - if(event.key === 'ArrowDown') { - moveMessage.data = 'down'; - socket.send(JSON.stringify(moveMessage)); - } - if(event.key === 'ArrowLeft') { - moveMessage.data = 'left'; - socket.send(JSON.stringify(moveMessage)); - } - if(event.key === 'ArrowRight') { - moveMessage.data = 'right'; - socket.send(JSON.stringify(moveMessage)); - } - }); - - document.getElementById('sendButton').addEventListener('click', () => { - const messageInput = document.getElementById('messageInput'); - const message = messageInput.value; - socket.send(message); - messageInput.value = ''; - }); - - - </script> - </body> + <head> + <title>WebSocket Example</title> + </head> + + <body> + <h1>WebSocket Client</h1> + <input type="text" id="messageInput" placeholder="Type a message..." /> + <button id="sendButton">Send</button> + <div id="messages"></div> + + <div id="game"> + <canvas id="gameCanvas" width="800" height="600"></canvas> + </div> + + <script> + const joinMessage = { type: "join", data: "Hello, server" }; + const socket = new WebSocket("ws://127.0.0.1:3001"); + + const canvas = document.getElementById("gameCanvas"); + const width = canvas.width; + const height = canvas.height; + + let moveMessage = { type: "move", data: "up" }; + + let gameBoardHandler = (event) => { + let ctx = canvas.getContext("2d"); + ctx.clearRect(0, 0, width, height); + ctx.fillStyle = "black"; + ctx.fillRect(0, 0, width, height); + ctx.fillStyle = "white"; + + let board = event.data; + + widthStep = width / board[0].length; + heightStep = height / board.length; + + for (let i = 0; i < board.length; i++) { + for (let j = 0; j < board[i].length; j++) { + if (board[i][j] === 0) { + ctx.fillRect( + j * widthStep + 1, + i * heightStep + 1, + widthStep - 2, + heightStep - 2, + ); + } + if (board[i][j] === 1) { + ctx.fillStyle = "red"; + ctx.fillRect( + j * widthStep + 1, + i * heightStep + 1, + widthStep - 2, + heightStep - 2, + ); + ctx.fillStyle = "white"; + } + } + } + }; + + socket.addEventListener("open", () => { + console.log("Connected to server"); + socket.send(JSON.stringify(joinMessage)); + }); + + socket.addEventListener("message", (event) => { + try { + let msg = JSON.parse(event.data); + if (msg.type === "gameBoard") { + gameBoardHandler(msg); + } else { + const messages = document.getElementById("messages"); + const messageElement = document.createElement("div"); + messageElement.innerText = event.data; + messages.appendChild(messageElement); + } + } catch { + console.log(event.data); + } + }); + + document.addEventListener("keydown", (event) => { + if (event.key === "ArrowUp") { + moveMessage.data = "up"; + socket.send(JSON.stringify(moveMessage)); + } + if (event.key === "ArrowDown") { + moveMessage.data = "down"; + socket.send(JSON.stringify(moveMessage)); + } + if (event.key === "ArrowLeft") { + moveMessage.data = "left"; + socket.send(JSON.stringify(moveMessage)); + } + if (event.key === "ArrowRight") { + moveMessage.data = "right"; + socket.send(JSON.stringify(moveMessage)); + } + }); + + document.getElementById("sendButton").addEventListener("click", () => { + const messageInput = document.getElementById("messageInput"); + const message = messageInput.value; + socket.send(message); + messageInput.value = ""; + }); + </script> + </body> </html> diff --git a/src/game/gameLogic.js b/src/game/gameLogic.js index e70b22c..f07562d 100644 --- a/src/game/gameLogic.js +++ b/src/game/gameLogic.js @@ -10,10 +10,10 @@ function gen(arr) { for (var i = 0; i < arr.length; i++) { let suba = []; - for (var x = 0; x < 25; x++) { + for (var x = 0; x < 25; x++) { suba.push(true); } - parent.push(suba); + parent.push(suba); } return parent; } @@ -21,15 +21,18 @@ function gen(arr) { array = gen(array); //Place snake into array grid -var snake = [{ x: 15, y: 10 }, { x: 15, y: 11}]; +var snake = [ + { x: 15, y: 10 }, + { x: 15, y: 11 }, +]; function placeSnake(arr, row, col) { - if (arr[row] && arr[row][col] !== undefined) { - //Head - arr[row][col] = false; - //Tail - arr[row] [col + 1] = false; - } + if (arr[row] && arr[row][col] !== undefined) { + //Head + arr[row][col] = false; + //Tail + arr[row][col + 1] = false; + } } placeSnake(array, 15, 10); diff --git a/src/game/index.js b/src/game/index.js index ae33734..4f0e806 100644 --- a/src/game/index.js +++ b/src/game/index.js @@ -1,8 +1,8 @@ -const BACKGROUND_COLOR = '#27ae60'; -const SNAKE_COLOR = '#3498db'; -const FOOD_COLOR = '#e74c3c'; +const BACKGROUND_COLOR = "#27ae60"; +const SNAKE_COLOR = "#3498db"; +const FOOD_COLOR = "#e74c3c"; -const gameScreen = document.getElementById('gameScreen'); +const gameScreen = document.getElementById("gameScreen"); let canvas, element; @@ -19,10 +19,10 @@ const gameState = { x: 1, y: 0, }, - //Give a temporary position of the snake body + //Give a temporary position of the snake body snake: [ - {x: 2, y: 10}, - {x: 3, y: 10}, + { x: 2, y: 10 }, + { x: 3, y: 10 }, ], }, //Give a temporary position for the food, we will change it later to a random position @@ -35,22 +35,22 @@ const gameState = { }; //Initialize the game elements such as canvas size, color, etc. -function init(){ - canvas = document.createElement('canvas'); - element = canvas.getContext('2d'); +function init() { + canvas = document.createElement("canvas"); + element = canvas.getContext("2d"); canvas.width = 600; canvas.height = 600; - + element.fillStyle = BACKGROUND_COLOR; element.fillRect(0, 0, canvas.width, canvas.height); gameScreen.appendChild(canvas); - - document.addEventListener('keydown', keydown); + + document.addEventListener("keydown", keydown); } //Here is where we will implement movement/direction logic. The server is not implemented yet so we just use console.log(event.keyCode) to represent keys pressed -function keydown(event){ +function keydown(event) { console.log(event.keyCode); } @@ -72,13 +72,13 @@ function paintGame(state) { } //Change snake cell color (All elements in the snake length) -function paintPlayer(playerState, size, color){ +function paintPlayer(playerState, size, color) { const snake = playerState.snake; element.fillStyle = color; - for(let cell of snake){ + for (let cell of snake) { element.fillRect(cell.x * size, cell.y * size, size, size); } } -paintGame(gameState); \ No newline at end of file +paintGame(gameState); diff --git a/tests/websocket.test.js b/tests/websocket.test.js index ddd2935..1dfa743 100644 --- a/tests/websocket.test.js +++ b/tests/websocket.test.js @@ -1,58 +1,50 @@ - -let WebSocketClient = require('websocket').client; +let WebSocketClient = require("websocket").client; let createClient = (port, hostname, protocol) => { - let WebSocketClient = require('websocket').client; - let client = new WebSocketClient(); - - client.on('connectFailed', (error) => { - console.log('Connect Error: ' + error.toString()); - }); - - client.on('connect', (connection) => { - console.log('WebSocket Client Connected'); - connection.on('error', (error) => { - console.log("Connection Error: " + error.toString()); - }); - - connection.on('close', () => { - console.log(`${protocol} Connection Closed`); - }); - - connection.on('message', (message) => { - if (message.type === 'utf8') { - console.log("Received: '" + message.utf8Data + "'"); - } - }); - }); - - client.connect(`ws://${hostname}:${port}/`, protocol); -} - - -test('start websocket server', () => { - - let ConnectionController = require('../src/route/connectionController'); - let wsServer = ConnectionController.startServer(8080, 'localhost'); - expect(wsServer).toBeDefined(); - expect(wsServer.server).toBeDefined(); - expect(wsServer.app).toBeDefined(); - expect(wsServer.connections).toBeDefined(); - - console.log(wsServer.server); - - - let shutdown = () => { - wsServer.server.closeAllConnections(); - wsServer.server.shutDown(); - wsServer.app.close(); - } - - let client = createClient(8080, 'localhost', 'echo-protocol'); - - - - - - shutdown(); + let WebSocketClient = require("websocket").client; + let client = new WebSocketClient(); + + client.on("connectFailed", (error) => { + console.log("Connect Error: " + error.toString()); + }); + + client.on("connect", (connection) => { + console.log("WebSocket Client Connected"); + connection.on("error", (error) => { + console.log("Connection Error: " + error.toString()); + }); + + connection.on("close", () => { + console.log(`${protocol} Connection Closed`); + }); + + connection.on("message", (message) => { + if (message.type === "utf8") { + console.log("Received: '" + message.utf8Data + "'"); + } + }); + }); + + client.connect(`ws://${hostname}:${port}/`, protocol); +}; + +test("start websocket server", () => { + let ConnectionController = require("../src/route/connectionController"); + let wsServer = ConnectionController.startServer(8080, "localhost"); + expect(wsServer).toBeDefined(); + expect(wsServer.server).toBeDefined(); + expect(wsServer.app).toBeDefined(); + expect(wsServer.connections).toBeDefined(); + + console.log(wsServer.server); + + let shutdown = () => { + wsServer.server.closeAllConnections(); + wsServer.server.shutDown(); + wsServer.app.close(); + }; + + let client = createClient(8080, "localhost", "echo-protocol"); + + shutdown(); }); -- GitLab