Skip to content

Commit

Permalink
leaderboard
Browse files Browse the repository at this point in the history
  • Loading branch information
jm1021 committed Dec 19, 2023
1 parent 644e4a9 commit f6a7e86
Showing 1 changed file with 330 additions and 0 deletions.
330 changes: 330 additions & 0 deletions _notebooks/2023-12-14-CSSE_student_leaderboard.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,330 @@
{
"cells": [
{
"cell_type": "raw",
"metadata": {},
"source": [
"---\n",
"comments: true\n",
"toc: true\n",
"layout: post\n",
"title: Leaderboard Lesson\n",
"type: collab\n",
"courses: { csse: {week: 16} }\n",
"authors: Nora A, Katie K, Tim V.\n",
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# What we did #\n",
"Created a leaderbaord that will display times of the players in fastest to slowest order. To do this, we implemented local storage that will save on your computers that will stay even when the tab is refreshed."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### STEP ONE\n",
"\n",
"in the main oop-game-levels.md start by adding a DIV to show the time/score (you can customize colors and font sizes to your liking)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"vscode": {
"languageId": "javascript"
}
},
"outputs": [],
"source": [
"//it should go after all of your divs for the buttons, like settings, start, invert, etc\n",
"//its own separate div category !\n",
"\n",
"<div id=\"score\" style=\"position: absolute; top: 75px; left: 10px; color: black; font-size: 20px; background-color: white;\">\n",
" Time: <span id=\"timeScore\">0</span>\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### STEP TWO\n",
"\n",
"create a button for the leaderboard screen"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"vscode": {
"languageId": "javascript"
}
},
"outputs": [],
"source": [
"//this one will go in the \"canvas container\" div as with the settings, start, invert, etc\n",
"<button id=\"leaderboardButton\">Leaderboard</button>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### STEP THREE\n",
"\n",
"add a function to show the leaderboard screen/switch to the leaderboard screen. place this code bellow the assets enemies. (in the MD file)\n",
"\n",
"within the function, the local storage variables are also defined and will be displayed in this manner:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"vscode": {
"languageId": "javascript"
}
},
"outputs": [],
"source": [
"// we put this in the oop file after our assets\n",
"\n",
"// Function to switch to the leaderboard screen\n",
"function showLeaderboard() {\n",
" const id = document.getElementById(\"gameOver\");\n",
" id.hidden = false;\n",
" // Hide game canvas and controls\n",
" document.getElementById('canvasContainer').style.display = 'none';\n",
" document.getElementById('controls').style.display = 'none';\n",
"\n",
" // Create and display leaderboard section\n",
" const leaderboardSection = document.createElement('div');\n",
" leaderboardSection.id = 'leaderboardSection';\n",
" leaderboardSection.innerHTML = '<h1 style=\"text-align: center; font-size: 18px;\">Leaderboard </h1>';\n",
" document.querySelector(\".page-content\").appendChild(leaderboardSection)\n",
" // document.body.appendChild(leaderboardSection);\n",
"\n",
" const playerScores = localStorage.getItem(\"playerScores\")\n",
" const playerScoresArray = playerScores.split(\";\")\n",
" const scoresObj = {}\n",
" const scoresArr = []\n",
" for(let i = 0; i< playerScoresArray.length-1; i++){\n",
" const temp = playerScoresArray[i].split(\",\")\n",
" scoresObj[temp[0]] = parseInt(temp[1])\n",
" scoresArr.push(parseInt(temp[1]))\n",
" }\n",
"\n",
" scoresArr.sort()\n",
"\n",
" const finalScoresArr = []\n",
" for (let i = 0; i<scoresArr.length; i++) {\n",
" for (const [key, value] of Object.entries(scoresObj)) {\n",
" if (scoresArr[i] ==value) {\n",
" finalScoresArr.push(key + \",\" + value)\n",
" break;\n",
" }\n",
" }\n",
" }\n",
" let rankScore = 1;\n",
" for (let i =0; i<finalScoresArr.length; i++) {\n",
" const rank = document.createElement('div');\n",
" rank.id = `rankScore${rankScore}`;\n",
" rank.innerHTML = `<h2 style=\"text-align: center; font-size: 18px;\">${finalScoresArr[i]} </h2>`;\n",
" document.querySelector(\".page-content\").appendChild(rank) \n",
" }\n",
"}\n",
"\n",
"//rest of the code here\n",
"\n",
"// Event listener for leaderboard button to be clicked\n",
"document.getElementById('leaderboardButton').addEventListener('click', showLeaderboard);\n",
"\n",
" // add File to assets, ensure valid site.baseurl\n",
" Object.keys(assets).forEach(category => {\n",
" Object.keys(assets[category]).forEach(assetName => {\n",
" assets[category][assetName]['file'] = \"{{site.baseurl}}\" + assets[category][assetName].src;\n",
" });\n",
" });\n",
"\n",
" //this should be above the game level callbacks"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### STEP FOUR\n",
"we're going to edit our gameOverCallBack function so that it will PROMPT the users to input their names after so it can assign the time to the name (key value data pair). \n",
"\n",
"Since you already have an existing function, you should be able to add these parts. \n",
"\n",
"The if statemet for the function was added so that the timer would not continously record the time, and only do this process once. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"vscode": {
"languageId": "javascript"
}
},
"outputs": [],
"source": [
"async function gameOverCallBack() {\n",
" const id = document.getElementById(\"gameOver\");\n",
" id.hidden = false;\n",
"\n",
" // Store whether the game over screen has been shown before\n",
" const gameOverScreenShown = localStorage.getItem(\"gameOverScreenShown\");\n",
"\n",
" // Check if the game over screen has been shown before\n",
" if (!gameOverScreenShown) {\n",
" const playerScore = document.getElementById(\"timeScore\").innerHTML;\n",
" const playerName = prompt(`You scored ${playerScore}! What is your name?`);\n",
" let temp = localStorage.getItem(\"playerScores\");\n",
" temp += playerName + \",\" + playerScore.toString() + \";\";\n",
" localStorage.setItem(\"playerScores\", temp);\n",
" // Set a flag in local storage to indicate that the game over screen has been shown\n",
" localStorage.setItem(\"gameOverScreenShown\", \"true\");\n",
" }\n",
"\n",
"// Use waitForRestart to wait for the restart button click\n",
" await waitForButton('restartGame');\n",
" id.hidden = true;\n",
" // Change currentLevel to start/restart value of null\n",
" GameEnv.currentLevel = null;\n",
" // Reset the flag so that the game over screen can be shown again on the next game over\n",
" localStorage.removeItem(\"gameOverScreenShown\");\n",
" return true;\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### STEP FIVE\n",
"We've finished adding the code to the MD file, now we can set up and define the timer in GameEnv.js\n",
"\n",
"After the constructor for the class GameEnv, we're going to add in the functions for timer start, stop, reset, and update."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"vscode": {
"languageId": "javascript"
}
},
"outputs": [],
"source": [
"let time = 0; // Initialize time variable\n",
"let timerInterval; // Variable to hold the interval reference\n",
"\n",
"\n",
"// Function to update and display the timer\n",
"function updateTimer() {\n",
" const id = document.getElementById(\"gameOver\");\n",
" if (id.hidden == false) {\n",
" stopTimer()\n",
" time=-1\n",
" }\n",
" time++; // Increment time (you can adjust this based on your game logic)\n",
"\n",
"\n",
" // Display the updated time in the span element with id 'timeScore'\n",
" const timeScoreElement = document.getElementById('timeScore');\n",
" if (timeScoreElement) {\n",
" timeScoreElement.textContent = time; // Update the displayed time\n",
" }\n",
"}\n",
"\n",
"\n",
"// Function to start the timer\n",
"function startTimer() {\n",
" // Start the timer interval, updating the timer every second (1000 milliseconds)\n",
" timerInterval = setInterval(updateTimer, 1000);\n",
"}\n",
"\n",
"\n",
"// Function to stop the timer\n",
"function stopTimer() { \n",
" clearInterval(timerInterval); // Clear the interval to stop the timer\n",
" }\n",
"\n",
"\n",
"// Event listener for the start game button click\n",
"document.getElementById('startGame').addEventListener('click', () => {\n",
" startTimer(); // Start the timer when the game starts\n",
"});\n",
"\n",
"\n",
"// Function to reset the timer\n",
"function resetTimer() {\n",
" stopTimer(); // Stop the timer\n",
" time = 0; // Reset the time variable\n",
" updateTimer(); // Update the displayed time to show 0\n",
"}\n",
"\n",
"\n",
"// Game Over callback\n",
"async function gameOverCallBack() {\n",
" const id = document.getElementById(\"gameOver\");\n",
" id.hidden = false;\n",
"\n",
"\n",
" // Stop the timer on game over\n",
" stopTimer();\n",
"\n",
"\n",
" // Use waitForRestart to wait for the restart button click\n",
" await waitForButton('restartGame');\n",
" id.hidden = true;\n",
"\n",
"\n",
" // Change currentLevel to start/restart value of null\n",
" GameEnv.currentLevel = null;\n",
"\n",
"\n",
" // Reset the timer when restarting the game\n",
" resetTimer();\n",
"\n",
"\n",
" return true;\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Homework and Hacks!\n",
"The timer should be fully working in your game now, but because of local storage, it will only start once the start button is pressed and the game is complete. \n",
"\n",
"##### Homework #####\n",
"- implement the timer function so it works correctly \n",
"- create a \"clear\" button for the leaderboard that will reset or delete all of the local storage values saved (note that this will also remove your local storage for gamespeed)\n",
"\n",
"##### Challenge #####\n",
"- customize the leaderboard (adding tables, filter button to sort what order the values are ordered, color!)"
]
}
],
"metadata": {
"language_info": {
"name": "python"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}

0 comments on commit f6a7e86

Please sign in to comment.