Version 1.0: Funktioniere Bestenliste und sonst auch alles Funktionell

This commit is contained in:
2025-05-02 18:42:48 +02:00
parent b36d7a4274
commit a422ef879e
12 changed files with 124 additions and 1402 deletions

View File

@@ -1,7 +1,8 @@
class Score{
/** @param {UserManager} usermanager */
constructor(scoreJson){
constructor(scoreJson, rank = 0){
this.id = scoreJson.id;
this.rank = rank;
this.user1ID = scoreJson.user1;
this.user2ID = scoreJson.user2;
this.score = scoreJson.score;

View File

@@ -5,11 +5,13 @@ class ScoreManager{
/**@param {mySql.Connection} connection*/
constructor(connection) {
this.connection = connection;
this.splitLimit = 25;
}
async getAllScores(){
const response = await this.connection.promise().query("SELECT * FROM scores ORDER BY score DESC");
const sortedScores = response[0].map(scoreData => new Score(scoreData));
const sortedScores = response[0].map((scoreData, index) => new Score(scoreData, index + 1));
return sortedScores;
}
@@ -32,24 +34,27 @@ class ScoreManager{
return new Score(response.rows[0][0]);
}
async getScoreRang(id){
const allSortetScores = await this.getAllScores();
const score = allSortetScores.find(score => score.id === id);
return allSortetScores.indexOf(score) + 1;
}
async getSplitedScoreCount(){
const allSortetScores = await this.getAllScores();
const count = Math.ceil(allSortetScores.lenght / 25);
const count = Math.ceil(allSortetScores.length / 25);
return count;
}
async getSpiltedScore(count){
const offset = (count - 1) * this.splitLimit;
const response = await this.connection.promise().query(
`SELECT * FROM scores ORDER BY score DESC LIMIT ${this.splitLimit} OFFSET ${offset}`,
);
const sortedScoreSplit = response[0].map((scoreData, index) => {
const rank = offset + index + 1;
return new Score(scoreData, rank);
});
return sortedScoreSplit;
}
}

View File

@@ -10,6 +10,8 @@ class HighScoreRoute {
this.db = dbManager;
this.router.get("/", async (req, res) => await this.getHighscores(req, res));
this.router.get("/split/:count", async (req, res) => await this.getSplitedHighScores(req, res));
this.router.get("/count", async (req, res) => await this.getSplitedHighScoreCount(req, res));
}
/**@param {express.Request} req @param {express.Response} res*/
@@ -22,11 +24,47 @@ class HighScoreRoute {
}
for(const highscore of highscores){
const highscoreJSON = await this.formatHighScore(highscore);
returnJSON.scores.push(highscoreJSON);
}
res.json(returnJSON);
}
/**@param {express.Request} req @param {express.Response} res*/
async getSplitedHighScores(req, res){
const count = req.params.count;
/** @type {Array<Score>} */
const highscores = await this.db.scoremanager.getSpiltedScore(count);
let returnJSON = {
scores: []
}
for(const highscore of highscores){
const highscoreJSON = await this.formatHighScore(highscore);
returnJSON.scores.push(highscoreJSON);
}
res.json(returnJSON);
}
/**@param {express.Request} req @param {express.Response} res*/
async getSplitedHighScoreCount(req, res){
const count = await this.db.scoremanager.getSplitedScoreCount();
res.json({
count: count
});
}
/** @param {Score} highscore */
async formatHighScore(highscore){
const user1 = await this.db.usermanager.getUser({id: highscore.user1ID});
const user2 = await this.db.usermanager.getUser({id: highscore.user2ID});
const rang = highscores.indexOf(highscore) + 1;
returnJSON.scores.push({
const rang = highscore.rank;
const returnJSON = {
id: highscore.id,
score: highscore.score,
rang: rang,
@@ -40,10 +78,9 @@ class HighScoreRoute {
username: user2.username,
fullName: user2.fullName
},
});
}
res.json(returnJSON);
return returnJSON;
}
}

View File

@@ -32,13 +32,11 @@
</th>
</thead>
</table>
<div id="siteSelector">
<label for="site">Seite</label>
<select id="site" name="site">
<option>1</option>
<option>2</option>
</select>
</div>
<div id="countSelector">
<label for="count">Seite:</label>
<select id="count" name="count">
</select>
</div>
</div>
<div class="container">

View File

@@ -1,26 +1,50 @@
class HighScoreLoader{
constructor(){
this.table = document.getElementById("highscoreTable");
this.data = undefined;
// Jetzigen Count finden
const urlParams = new URLSearchParams(window.location.search);
this.count = parseInt(urlParams.get("count")) || 1;
this.countSelector = document.getElementById("count");
this.setup();
}
async setup(){
// const response = await fetch("/api/highscore");
// this.data = await response.json();
// Load all Data
const response = await fetch(`/api/highscore/split/${this.count}`);
this.data = await response.json();
// for(const score of this.data.scores){
// this.table.innerHTML += `
// <tr>
// <td>${score.rang}</td>
// <td>${score.user1.username}</td>
// <td>${score.user2.username}</td>
// <td>${score.score}</td>
// </tr>
// `;
// }
for(const score of this.data.scores){
this.table.innerHTML += `
<tr>
<td>${score.rang}</td>
<td>${score.user1.username}</td>
<td>${score.user2.username}</td>
<td>${score.score}</td>
</tr>
`;
}
// Lade alle options
const response2 = await fetch("/api/highscore/count");
const data2 = await response2.json();
for(let i = 1; i <= data2.count; i++){
this.countSelector.innerHTML += `
<option>${i}</option>
`
}
this.countSelector.addEventListener("change", (e) => {
const targetCount = e.target.value;
window.location.href = `/highscores/?count=${targetCount}`;
})
this.countSelector.value = this.count;
}
}

View File

@@ -67,10 +67,16 @@ tr td:last-child {
border-left: 3px solid rgba(255, 255, 255, 0.6);
}
#siteSelector{
#countSelector{
display: flex;
align-items: center;
justify-content: center;
}
#countSelector > * {
margin: 10px;
}
.navButtons{
flex-direction: column;
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,18 +0,0 @@
{
"name": "backend",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "node ./src/index.js"
},
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"body-parser": "^1.20.3",
"express": "^4.21.2",
"socket.io": "^4.8.1",
"socket.io-client": "^4.8.1"
}
}

View File

@@ -1,103 +0,0 @@
const express = require("express");
const http = require("http");
const socketIO = require("socket.io");
const bp = require("body-parser");
const path = require("path");
const _PORT = 3000;
const app = express();
const server = http.createServer(app);
/** @type {import("socket.io").Server} */
const io = socketIO(server);
app.use(bp.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "../../frontend")));
app.use((req, res, next) => {
console.log(`${req.method} | ${req.url}`);
next();
})
const playerList = [];
io.on('connection', (socket) => {
console.log("Es ist ein neuer Spieler beigetreten");
const player = {
id: socket.id,
x: 100,
y: 100,
socket: socket,
};
playerList.push(player);
emitPlayerMovement();
socket.on("moveUp", () => {
const player = playerList.find((p) => p.id === socket.id);
if (player) {
player.y -= 10;
}
emitPlayerMovement();
});
socket.on("moveDown", () => {
const player = playerList.find((p) => p.id === socket.id);
if (player) {
player.y += 10;
}
emitPlayerMovement();
});
socket.on("moveRight", () => {
const player = playerList.find((p) => p.id === socket.id);
if (player) {
player.x += 10;
}
emitPlayerMovement();
});
socket.on("moveLeft", () => {
const player = playerList.find((p) => p.id === socket.id);
if (player) {
player.x -= 10;
}
emitPlayerMovement();
});
// Handle player disconnect
socket.on("disconnect", () => {
console.log(`Spieler ${socket.id} hat das Spiel verlassen`);
const index = playerList.findIndex((p) => p.id === socket.id);
if (index !== -1) {
playerList.splice(index, 1);
}
emitPlayerMovement();
});
socket.on("disconnect", () => {
playerList.splice(playerList.findIndex(p => p.id === socket.id), 1);
})
});
function emitPlayerMovement() {
const playerMap = playerList.map(x => {
return {
id: x.id,
x: x.x,
y: x.y
}
});
io.emit("updatePos", playerMap);
}
server.listen(_PORT, () => {
console.log(`Backend gestartet auf http://localhost:${_PORT}`);
})

View File

@@ -1,17 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Erste Socket.io Seite</title>
<link rel="stylesheet" href="style/style.css" />
</head>
<body>
<h1>Multigame</h1>
</body>
<script src="https://cdn.socket.io/4.7.2/socket.io.min.js"></script>
<script src="index.js" type="module"></script>
<canvas id="game" height="300px" width="300px" id> </canvas>
</html>

View File

@@ -1,37 +0,0 @@
/** @type {import("../backend/node_modules/socket.io-client").Socket} */
const socket = io("http://localhost:3000");
const gameScreen = document.getElementById("game");
const ctx = gameScreen.getContext("2d")
ctx.fillStyle = "red";
socket.on("connect", () => {
console.log(`Connected as ${socket.id}`);
});
let keysPressed = new Set();
document.addEventListener("keydown", (e) => {
keysPressed.add(e.key);
});
document.addEventListener("keyup", (e) => {
keysPressed.delete(e.key);
});
setInterval(() => {
if (keysPressed.has("ArrowUp")) socket.emit("moveUp");
if (keysPressed.has("ArrowDown")) socket.emit("moveDown");
if (keysPressed.has("ArrowRight")) socket.emit("moveRight");
if (keysPressed.has("ArrowLeft")) socket.emit("moveLeft");
}, 50);
socket.on("updatePos", (map) => {
ctx.clearRect(0, 0, gameScreen.width, gameScreen.height);
map.forEach(e => {
ctx.beginPath();
ctx.arc(e.x, e.y, 10, 0, Math.PI * 2, false);
ctx.fill();
});
})

View File

@@ -1,3 +0,0 @@
#game{
background-color: grey;
}