Skip to content
Snippets Groups Projects

Added w/l ratio to db

Merged Rasmus Svala requested to merge win-loss-ratio into dev
4 files
+ 41
35
Compare changes
  • Side-by-side
  • Inline
Files
4
+ 25
8
@@ -96,14 +96,31 @@ export default function MainGame({ url, myID }) {
set(winnerRef, "none");
function checkWinner(snapshot) {
function updateStats(stringRef) {
const statRef = ref(database, "users/" + user.uid + stringRef);
function updateStats(winsOrLosses) {
const userStatsRef = ref(database, `users/${user.uid}/`);
get(statRef).then((s) => {
if (!s.exists()) return;
// Increment wins or losses and update w/l ratio
get(userStatsRef).then((snapshot) => {
if (!snapshot.exists()) return;
const currentValue = s.val();
set(statRef, currentValue + 1);
const userStats = snapshot.val();
const wins = userStats.wins;
const losses = userStats.losses;
// Increment the appropriate stat
if (winsOrLosses === "wins") userStats.wins = wins + 1;
else if (winsOrLosses === "losses") userStats.losses = losses + 1;
// Calculate new W/L ratio
const newRatio =
losses === 0
? userStats.wins.toFixed(2)
: (userStats.wins / userStats.losses).toFixed(2);
userStats.ratio = newRatio;
// Update the database
set(userStatsRef, userStats);
});
}
@@ -113,11 +130,11 @@ export default function MainGame({ url, myID }) {
if (winner !== myID) {
setEndMsg("Defeat");
setEndClass("defeat");
updateStats("/losses");
updateStats("losses");
} else {
setEndMsg("Victory");
setEndClass("victory");
updateStats("/wins");
updateStats("wins");
}
setEndOfGame(true);
}
Loading