Skip to content
Snippets Groups Projects
Commit dc6f910a authored by Patrick's avatar Patrick
Browse files

Added the leaderboard functionality.

parent 79657a2a
Branches ptl46
No related tags found
No related merge requests found
...@@ -41,6 +41,10 @@ function userExists(user) { ...@@ -41,6 +41,10 @@ function userExists(user) {
return db.prepare("SELECT COUNT(*) FROM users WHERE username = $user").get({$user: user})[0] > 0; return db.prepare("SELECT COUNT(*) FROM users WHERE username = $user").get({$user: user})[0] > 0;
} }
function getRecords() {
return db.exec("SELECT username, score FROM leaderboard ORDER BY score DESC LIMIT 10;");
}
function queryUser(user) { function queryUser(user) {
return db.prepare("SELECT * FROM users WHERE username = $user").getAsObject({$user: user}); return db.prepare("SELECT * FROM users WHERE username = $user").getAsObject({$user: user});
} }
...@@ -87,4 +91,4 @@ async function login(user, pass) { ...@@ -87,4 +91,4 @@ async function login(user, pass) {
} }
} }
module.exports = {login, signup, getUserForToken, writeRecord}; module.exports = {login, signup, getUserForToken, getRecords, writeRecord};
body {
margin: 2rem;
}
table {
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 10px;
}
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>2doku Home</title>
<link rel="stylesheet" type="text/css" href="/leaderboard.css"></link>
</head>
<body>
<h1>2doku Leaderboard</h1>
<div id="message"></div>
<table class="table">
<thead>
<th>
Rank
</th>
<th>
Username
</th>
<th>
Score
</th>
</thead>
<tbody id="table">
</tbody>
</table>
<br>
<a href="/">Back</a>
<script>
function createRow(rank, user, score) {
let row = document.createElement("tr");
let rankCell = document.createElement("td");
rankCell.textContent = rank;
let userCell = document.createElement("td");
userCell.textContent = user;
let scoreCell = document.createElement("td");
scoreCell.textContent = score;
row.append(rankCell);
row.append(userCell);
row.append(scoreCell);
return row;
}
fetch("/get-leaderboard").then(res => {
return res.json();
}).then(body => {
const { code } = body;
console.log(body);
document.querySelector("#message").textContent = ""; // Clear message
document.querySelector("#table").textContent = ""; // Clear the table
if (code === 200) {
// Fetch leaderboard
const { data } = body;
console.log(data);
for (let i = 0; i < data.length; i++) {
const record = data[i];
const user = record[0], score = record[1];
// adding 1 to the index gives the rank.
const row = createRow(1 + i, user, score);
document.querySelector("#table").append(row);
}
} else {
document.querySelector("#message").textContent = res.body["error"];
}
});
</script>
</body>
</html>
...@@ -200,13 +200,6 @@ function ensureAuth(req, res, fn) { ...@@ -200,13 +200,6 @@ function ensureAuth(req, res, fn) {
fn(user); fn(user);
} }
function writeUser(user, hash) {
db.run("INSERT INTO users (username, pwhash) VALUES (?, ?);", [user, hash]);
const data = db.export();
const buffer = Buffer.from(data);
fs.writeFileSync(env["db_path"], buffer);
}
app.get("/", (req, res) => { app.get("/", (req, res) => {
clearBadToken(req, res); clearBadToken(req, res);
return res.sendFile(__dirname + "/semipublic/index.html"); return res.sendFile(__dirname + "/semipublic/index.html");
...@@ -222,6 +215,22 @@ app.get("/login", (req, res) => { ...@@ -222,6 +215,22 @@ app.get("/login", (req, res) => {
return res.sendFile(__dirname + "/semipublic/login.html"); return res.sendFile(__dirname + "/semipublic/login.html");
}) })
app.get("/leaderboard", (req, res) => {
clearBadToken(req, res);
return res.sendFile(__dirname + "/semipublic/leaderboard.html");
});
app.get("/get-leaderboard", (req, res) => {
// Attempt to get top 10 from database.
let records;
try {
records = login.getRecords();
res.status(200).send({"code": 200, "data": records[0].values});
} catch (e) {
res.status(500).send({"code": 500, "error": e});
}
});
app.post("/signup", (req, res) => { app.post("/signup", (req, res) => {
const user = req.body['user']; const user = req.body['user'];
const pass = req.body['pass']; const pass = req.body['pass'];
...@@ -304,28 +313,12 @@ io.on("connection", (socket) => { ...@@ -304,28 +313,12 @@ io.on("connection", (socket) => {
game.sendBoard(); game.sendBoard();
}); });
socket.on("join game", (_, fn) => { socket.on("join game", () => {
if (!game.playerUsers.includes(user)) { if (!game.playerUsers.includes(user)) {
game.userJoin(socketId, user); game.userJoin(socketId, user);
} else {
fn("duplicate");
} }
}); });
socket.on("verify solution", args => {
const { board, playerScores } = args;
// Check for missing/incorrect answers
for (let y = 0; y < 9; y++) {
for (let x = 0; x < 9; x++) {
if (board[y][x] !== game.boardSolution[y][x]) {
return;
}
}
}
// We solved the sudoku!
login.writeRecord(user, playerScores[user]);
});
socket.on("disconnect", () => { socket.on("disconnect", () => {
if (game) { if (game) {
game.userLeave(socketId, user); game.userLeave(socketId, user);
...@@ -333,7 +326,6 @@ io.on("connection", (socket) => { ...@@ -333,7 +326,6 @@ io.on("connection", (socket) => {
}); });
}); });
httpServer.listen(port, hostname, () => { httpServer.listen(port, hostname, () => {
console.log(`http://${hostname}:${port}`); console.log(`http://${hostname}:${port}`);
}); });
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment