Major update

- Improved frontend
- Server-client toasting framework
- Huge improvements to server side utils
- Working ship placement validation
This commit is contained in:
MaciejkaG 2024-03-03 01:29:11 +01:00
parent 10dcb50aa1
commit 7c4801db2d
7 changed files with 130 additions and 41 deletions

View File

@ -135,7 +135,7 @@ io.on('connection', async (socket) => {
// Teraz utwórz objekt partii w trakcie w bazie Redis // Teraz utwórz objekt partii w trakcie w bazie Redis
const gameId = uuidv4(); const gameId = uuidv4();
redis.json.set(`game:${gameId}`, '$', { redis.json.set(`game:${gameId}`, '$', {
hostId: opp.id, hostId: opp.request.session.id,
state: "pregame", state: "pregame",
boards: [ boards: [
{ // typ 2 to trójmasztowiec pozycja i obrót na planszy które pola zostały trafione { // typ 2 to trójmasztowiec pozycja i obrót na planszy które pola zostały trafione
@ -176,7 +176,6 @@ io.on('connection', async (socket) => {
} else { } else {
callback({ callback({
status: "alreadyInLobby", status: "alreadyInLobby",
gameCode: id,
}); });
} }
} }
@ -212,7 +211,12 @@ io.on('connection', async (socket) => {
const members = [...roomMemberIterator(playerGame.id)]; const members = [...roomMemberIterator(playerGame.id)];
for (let i = 0; i < members.length; i++) { for (let i = 0; i < members.length; i++) {
const sid = members[i][0]; const sid = members[i][0];
io.to(sid).emit('player idx', i); const socket = io.sockets.sockets.get(sid);
if (socket.request.session.id === playerGame.data.hostId) {
io.to(sid).emit('player idx', 0);
} else {
io.to(sid).emit('player idx', 1);
}
} }
let UTCTs = Math.floor((new Date()).getTime() / 1000 + 90); let UTCTs = Math.floor((new Date()).getTime() / 1000 + 90);
@ -223,21 +227,30 @@ io.on('connection', async (socket) => {
AFKEnd(playerGame.id); AFKEnd(playerGame.id);
}); });
}); });
await redis.json.set(`game:${playerGame.id}`, '$.state', "preparation");
} }
} }
socket.on('place ship', async (type, posX, posY, rot) => { socket.on('place ship', async (type, posX, posY, rot) => {
const playerGame = await GInfo.getPlayerGameData(socket); const playerGame = await GInfo.getPlayerGameData(socket);
if (playerGame.state === 'preparation') { if (playerGame.data.state === 'preparation') {
const playerShips = await GInfo.getPlayerShips(socket);
let canPlace = bships.validateShipPosition(playerShips, type, posX, posY, rot);
if (canPlace) {
console.log("placed");
} else {
socket.emit("toast", "Nie możesz postawić tak statku")
}
} }
}); });
socket.on('shoot', async () => { socket.on('shoot', async () => {
const playerGame = await GInfo.getPlayerGameData(socket); const playerGame = await GInfo.getPlayerGameData(socket);
if (playerGame.state === 'action') { if (playerGame.data.state === 'action') {
if (bships.checkTurn(playerGame, socket.id)) { if (bships.checkTurn(playerGame, socket.id)) {
} }
@ -271,12 +284,15 @@ function resetUserGame(req) {
} }
function endGame(gameId) { function endGame(gameId) {
const members = [...roomMemberIterator(gameId)]; let iterator = roomMemberIterator(gameId);
for (let i = 0; i < members.length; i++) { if (iterator != null) {
const sid = members[i][0]; const members = [...iterator];
const socket = io.sockets.sockets.get(sid); for (let i = 0; i < members.length; i++) {
resetUserGame(socket.request); const sid = members[i][0];
socket.leave(gameId); const socket = io.sockets.sockets.get(sid);
resetUserGame(socket.request);
socket.leave(gameId);
}
} }
redis.json.del(`game:${gameId}`); redis.json.del(`game:${gameId}`);
@ -288,5 +304,5 @@ function AFKEnd(gameId) {
} }
function roomMemberIterator(id) { function roomMemberIterator(id) {
return io.sockets.adapter.rooms.get(id).entries(); return io.sockets.adapter.rooms.get(id) == undefined ? null : io.sockets.adapter.rooms.get(id).entries();
} }

View File

@ -70,6 +70,20 @@ h1,h2,h3,h4,h5,h6 {
transition: background 0.05s; transition: background 0.05s;
} }
.field .shipField {
width: 100%;
aspect-ratio: 1;
border-radius: 20%;
background: var(--ship-valid);
pointer-events: none;
opacity: 0;
transition: opacity 0.15s;
}
#secondaryBoard .field .shipField {
background: var(--ship-invalid);
}
.field svg { .field svg {
opacity: 0; opacity: 0;
width: 100%; width: 100%;

View File

@ -13,6 +13,18 @@
to {transform: translateY(0%);} to {transform: translateY(0%);}
} }
.bshipstoast {
background: rgba(0, 0, 0, 0.6);
backdrop-filter: blur(15px);
color: white;
padding: 0.75rem 1rem;
border-radius: 15px;
border: solid 2px white;
display: flex;
justify-content: center;
align-items: center;
}
.header { .header {
text-align: center; text-align: center;
} }

View File

@ -12,7 +12,7 @@ class Battleships {
for (var i = 0; i < size; i++) { for (var i = 0; i < size; i++) {
let row = "<div class=\"row\">"; let row = "<div class=\"row\">";
for (var n = 0; n < size; n++) { for (var n = 0; n < size; n++) {
row += `<div class="field" data-pos-x="${i}" data-pos-y="${n}"><svg xmlns='http://www.w3.org/2000/svg' version='1.1' preserveAspectRatio='none' viewBox='0 0 100 100'><path d='M100 0 L0 100 ' stroke='black' stroke-width='3'/><path d='M0 0 L100 100 ' stroke='black' stroke-width='3'/></svg></div>`; row += `<div class="field" data-pos-x="${i}" data-pos-y="${n}"><div class="shipField"><svg xmlns='http://www.w3.org/2000/svg' version='1.1' preserveAspectRatio='none' viewBox='0 0 100 100'><path d='M100 0 L0 100 ' stroke='black' stroke-width='3'/><path d='M0 0 L100 100 ' stroke='black' stroke-width='3'/></svg></div></div>`;
} }
row += "</div>"; row += "</div>";
board += row; board += row;

View File

@ -2,7 +2,24 @@ const socket = io();
var playerIdx; var playerIdx;
var timerDestination = null; var timerDestination = null;
var gamePhase = "pregame"; var gamePhase = 'pregame';
$('.field').on('click', function () {
console.log("Clicked");
socket.emit("place ship", selectedShip, $(this).data('pos-x'), $(this).data('pos-y'), shipRotation);
});
socket.on('toast', (msg) => {
Toastify({
text: msg,
duration: 5000,
newWindow: true,
gravity: "bottom",
position: "right",
stopOnFocus: true,
className: "bshipstoast",
}).showToast();
});
socket.on('connect', () => { socket.on('connect', () => {
$(".cover h1").html("Oczekiwanie na serwer..."); $(".cover h1").html("Oczekiwanie na serwer...");
@ -15,6 +32,7 @@ socket.on("players ready", () => {
socket.on("player idx", (idx) => { socket.on("player idx", (idx) => {
console.log(idx); console.log(idx);
playerIdx = idx; playerIdx = idx;
console.log(playerIdx);
}); });
socket.on('turn update', (turnData) => { socket.on('turn update', (turnData) => {

View File

@ -1,13 +1,3 @@
// export class Client {
// constructor(clientId, clientSecret, redirectUri) {
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.redirectUri = redirectUri;
// }
// getAccessToken(code) {
// }
// }
export class GameInfo { export class GameInfo {
constructor(redis, io) { constructor(redis, io) {
this.redis = redis; this.redis = redis;
@ -24,6 +14,12 @@ export class GameInfo {
return game == null ? null : { id: socket.session.activeGame, data: game }; return game == null ? null : { id: socket.session.activeGame, data: game };
} }
async getPlayerShips(socket) {
const game = await this.redis.json.get(`game:${socket.session.activeGame}`);
const idx = socket.request.session.id === game.hostId ? 0 : 1;
return game.boards[idx].ships;
}
async endPrepPhase(socket) { async endPrepPhase(socket) {
const gameId = socket.session.activeGame; const gameId = socket.session.activeGame;
const key = `game:${gameId}`; const key = `game:${gameId}`;
@ -152,42 +148,73 @@ export function checkHit(data, playerIdx, posX, posY) {
} }
}); });
boardRender.forEach(row => {
let log = "";
row.forEach(field => {
log += `${field}\t`
});
console.log(log);
});
return boardRender[posY][posX]; return boardRender[posY][posX];
} }
export function validateShipPosition(type, posX, posY, rot) { export function validateShipPosition(ships, type, posX, posY, rot) {
let multips; let multips;
let boardRender = [];
for (let i = 0; i < 10; i++) {
var array = [];
for (let i = 0; i < 10; i++) {
array.push(false);
}
boardRender.push(array);
}
ships.forEach(ship => {
let multips;
switch (ship.rot) {
case 0:
multips = [0, 1];
break;
case 1:
multips = [1, 0];
break;
case 2:
multips = [0, -1];
break;
case 3:
multips = [1, 0];
break;
}
for (let i = 0; i < ship.type + 1; i++) {
boardRender[ship.posY + multips[1] * i][ship.posX + multips[0] * i] = true;
}
});
switch (rot) { switch (rot) {
case 0: case 0:
multips = [1, 0];
break;
case 1:
multips = [0, 1]; multips = [0, 1];
break; break;
case 1:
multips = [1, 0];
break;
case 2: case 2:
multips = [-1, 0]; multips = [0, -1];
break; break;
case 3: case 3:
multips = [0, -1]; multips = [1, 0];
break; break;
} }
for (let i = 0; i < type + 2; i++) { for (let i = 0; i < type + 1; i++) {
if (posY + multips[1] * i > 9 || posY + multips[1] * i < 0 || posX + multips[0] * i > 9 || posX + multips[0] * i < 0) { if (posY + multips[1] * i > 9 || posY + multips[1] * i < 0 || posX + multips[0] * i > 9 || posX + multips[0] * i < 0) {
return false; return false;
} }
if (boardRender[posY + multips[1] * i][posX + multips[0] * i]) {
return false;
}
} }
return true; return true;

View File

@ -9,8 +9,10 @@
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,400;0,700;1,400;1,700&family=Poppins:ital,wght@0,600;1,600&family=Roboto+Mono:ital@0;1&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,400;0,700;1,400;1,700&family=Poppins:ital,wght@0,600;1,600&family=Roboto+Mono:ital@0;1&display=swap" rel="stylesheet">
<script src="https://cdn.socket.io/4.7.3/socket.io.min.js"></script> <script src="https://cdn.socket.io/4.7.3/socket.io.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
<link rel="stylesheet" href="/assets/css/board.css"> <link rel="stylesheet" href="/assets/css/board.css">
<link rel="stylesheet" href="/assets/css/main.css"> <link rel="stylesheet" href="/assets/css/main.css">
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
</head> </head>
<body> <body>
<span class="designerTag">Designed by Maciejka</span> <span class="designerTag">Designed by Maciejka</span>