Skip to content
Snippets Groups Projects
Commit cca97f87 authored by jjd358's avatar jjd358
Browse files

Merge branch '1-develop-web-socket-code' into 'main'

1-develop-web-socket-code - There were issues with the previous Websocket...

Closes #1

See merge request !6
parents b6b92290 68d47147
Branches
No related tags found
1 merge request!61-develop-web-socket-code - There were issues with the previous Websocket...
......@@ -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
......
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}`));
const sockserver = new WebSocketServer({ port: 3001 });
// Maintain a list of connections
// This will eventually map connections to lobby or game instances
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 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.");
// Game loop
//setInterval(() => {
// console.log('Broadcasting message to clients, connections.length: ', connections.length);
// connections.forEach(connection => {
// connection.send('Hello, world!')
// })
//}, 1000);
doc/msg.png

29.8 KiB

@startuml
set separator ::
struct client::RequestNewGameMsg {
int msgid = 1
}
struct client::RequestMoveMsg {
int msgid = 2
int direction
}
struct client::JoinGameMsg {
int msgid = 3
string gameid
string nickname
string password
}
struct client::LeaveGameMsg {
int msgid = 4
string gameid
}
struct server::GameStartedMsg {
int msgid = 5
string gameid
}
struct server::GameEndedMsg {
int msgid = 6
string gameid
}
struct server::PlayerJoinedMsg {
int msgid = 7
string gameid
string nickname
}
struct server::PlayerLeftMsg {
int msgid = 8
string gameid
string nickname
}
struct server::GameUpdateMsg {
int msgid = 9
string gameid
int[][] localBoard // array of 100x100 centered on snake head
}
@enduml
doc/uml.png

22.7 KiB

@startuml
Client -> Router : connect(ws, 'game-protocol')
Router -> GameModel : getGame(gameId)
GameModel -> Game : new Game(gameId)
GameModel -> GameModel : new WebSocket()
GameModel -> GameModel : ws.onopen = () => { ws.send('{gameId}') }
GameModel -> GameModel : ws.onmessage = (msg) => { game.handleMessage(msg) }
@enduml
This diff is collapsed.
......@@ -4,11 +4,19 @@
"description": "",
"main": "app.js",
"scripts": {
"test": "jest"
"test": "jest",
"start": "node app.js",
"format:check": "prettier --check .",
"format:write": "prettier --write ."
},
"author": "",
"license": "ISC",
"devDependencies": {
"jest": "^29.7.0"
"jest": "^29.7.0",
"prettier": "^3.3.3"
},
"dependencies": {
"express": "^4.19.2",
"ws": "^8.18.0"
}
}
<!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>
</html>
......@@ -21,7 +21,10 @@ 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) {
......
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;
......@@ -36,8 +36,8 @@ const gameState = {
//Initialize the game elements such as canvas size, color, etc.
function init() {
canvas = document.createElement('canvas');
element = canvas.getContext('2d');
canvas = document.createElement("canvas");
element = canvas.getContext("2d");
canvas.width = 600;
canvas.height = 600;
......@@ -46,7 +46,7 @@ function init(){
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
......
test('this is a test', () => {
expect(1 + 2).toBe(3);
});
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();
});
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment