Highscore of best 5

Hi everybody,

i wondering about what’s the best option to create a highscoretable of the best five players with nameinput. The nameinput works with a HTML-Textfield. I tought about a map or a textfile where the score and the associated names are saved, but i didn’t get a solution yet.
How would you do it?

Thank you!

Hi,
Look at localStorage

I already used localStorage to compare the actual score with the highest, but that was only one value.
I didn’t get what struct i should use to work with the five highest and associated names…

Hi, you can use whatever structure, with arrays for example, or a common one I would use would be a JSON…

localStorage.setItem("highscores", JSON.stringify({name1: 100, name2: 200}))
highscores = JSON.parse(localStorage.getItem("highscores"))

Maybe an array of JSON would be better if you want map and ordering…

I’d agree with the others. I’d personally go with localstorage and create an array of players.
Player Contract:
{
name: string,
score: number
}

It would allow for greater extensibility and readability

I’m sorry, but i think i need more help…
Here is my Code:

//change the string of localStorageName to reset highscore
var localStorageName = "new";
var highScore;


let element;
let pointer;
var name;


class Highscore extends Phaser.Scene {
	
	constructor() {
	
		super("Highscore");
		
	}
		
	init(data){
		//get score from Level.js
		this.score = 100;//data.score;
		this.time = data.time;
		this.player = "";
			
		//checks if any highscore is saved, otherwise highscore = 0
		highScore = localStorage.getItem(localStorageName) == null ? 0 :
            localStorage.getItem(localStorageName);
	}
	
	create() {
		highScore =[0, "", 0, "", 0, "", 0, "", 0, ""];
		this.scene.bringToTop("Sound");
		
		//add background
		let bg = this.add.image(0,0,"highscore", "background_scenes").setOrigin(0,0).setScale(1.05);
		
		//let duration = Phaser.Math.RoundTo(this.time/60000, -1);

		//add texts 
		this.add.text(200, 150, "RANG		PUNKTE 		NAME", 
		{fontSize: "32px", fontFamily: "Consolas", fill: "#ffffff", align: "center"});

		let replay = this.add.text(100, 400, "Drücke die Leertaste um nocheinmal zu spielen!", 
		{fontSize: "24px", fontFamily: "Consolas", fill: "#ffffff", align: "center"});
		
		pointer = this.input.activePointer;
		this.player = this.add.text(200, 200, "");

		element = this.add.dom(400, 225).createFromCache("nameform");
		element.visible = true;
	    element.addListener('click');
		this.enterName();
					
}
	
	update(){
		/*//restart at Scene ChooseChar.js if SPACE is pressed
		this.input.keyboard.once("keydown-" + "SPACE", () => {
			score = 0;
			this.scene.start("ChooseChar");	
		});
		
		if(pointer.isDown){
			score = 0;
			this.scene.start("ChooseChar");
		}*/
		
		if (!element.visible){
			this.showHighscore();
		}
		
		if(element.visible){
			this.input.keyboard.once("keydown-" + "ENTER", () =>{
				this.enterName();
			});
		}
	}
	
	enterName(){	
	    element.on('click', (event) => {
	
	        if (event.target.name === 'playButton')
	        {
	           var name = element.getChildByName('nameField');
	
	            //  Have they entered anything?
	            if (name.value !== '')
	            {
	                element.removeListener('click');
	                element.setVisible(false);
					this.player = name.value;
					this.addToMap(this.score, this.player);
					console.log(localStorage);
	            }
			}
		});
	}

	
	addToMap(score, name) {
		if(score >= highScore[0]) {
			highScore[0] = score;
			highScore[1] = name;
		} else if(score >= highScore[2]) {
			highScore[2] = score;
			highScore[3] = name;
		} else if(score >= highScore[4]) {
			highScore[4] = score;
			highScore[5] = name;
		} else if(score >= highScore[6]) {
			highScore[6] = score;QA
			highScore[7] = name;
		} else if (score >= highScore[8]) {
			highScore[8] = score;
			highScore[9] = name;
		}
		localStorage.setItem("new", highScore);
		this.showHighscore();
	}
		
	
	showHighscore() {
		for(var i = 0; i <= highScore.size/2; i+2) {
			for(var j = 200; j <= highScore.size/2; j+=50) {
				highScore[i] = this.add.text(200, j);
				highScore[i+1] = this.add.text(400, j);
			}
		}
	}
	

	
 }

My problem is that the localStorage gets override everytime and i don’t get how to compare the existing values with the new ones and update on demand.
Also i’m not sure, if localStoage is the right way cause as i understand the data is stored in the users browser, but in this case every user just get his own Highscoretable or am i wrong?

Thanks for your help

If you want a multiplayer high score, localStorage isn’t what you need, you need to store highscores server side, on a database for example.

I’d recommend firebase

Okay, thanks. I’m trying it with firebase by using this example: https://rexrainbow.github.io/phaser3-rex-notes/docs/site/firebase-leaderboard/

So i adjust my index.html like this:

<head>
	<meta charset="UTF-8" />
	<meta name=viewport content="width=device-width, initial-scale=1">

	<title>infoteam-Universe</title>

	<script src="lib/phaser.js"></script>
	<script src="main.js"></script>


	<style>
		body {
			background: black;
			margin: 0;
			padding: 0;
		}
	</style>
</head>

<body>
	<div id="game-container">
	</div>

	<script src="https://www.gstatic.com/firebasejs/7.15.0/firebase-app.js"></script>

	<!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#available-libraries -->
	<script src="https://www.gstatic.com/firebasejs/7.15.0/firebase-analytics.js"></script>
	<script defer src="https://www.gstatic.com/firebasejs/7.15.0/firebase-firestore.js"></script>

	<script>
	  	// Your web app's Firebase configuration
	 	var firebaseConfig = {
	    apiKey: ,
	    authDomain: ,
	    databaseURL: ,
	    projectId: ,
	    storageBucket: ,
	    messagingSenderId:,
	    appId: ,
	    measurementId:
 		 };
  		// Initialize Firebase
	  	firebase.initializeApp(firebaseConfig);
	  	firebase.analytics();
	</script>
	
	
	
</body>
</html>

And my Highscore.js like this:

let element;
let pointer;
var name;

class Highscore extends Phaser.Scene {
	
	constructor() {
	
		super("Highscore");
		
	}
		
	init(data){
		//get score from Level.js
		this.score = data.score;
		this.time = data.time;
		this.player = "";
	}
	
	preload() {
		this.load.plugin('rexfirebaseplugin', 
		'https://raw.githubusercontent.com/rexrainbow/phaser3-rex-notes/master/dist/rexfirebaseplugin.min.js', true);
	}
	
	create() {
		this.scene.bringToTop("Sound");
		
		//add background
		let bg = this.add.image(0,0,"highscore", "background_scenes").setOrigin(0,0).setScale(1.05);
		
		//let duration = Phaser.Math.RoundTo(this.time/60000, -1);

		//add texts 
		this.add.text(200, 150, "RANG		PUNKTE 		NAME", 
		{fontSize: "32px", fontFamily: "Consolas", fill: "#ffffff", align: "center"});

		let replay = this.add.text(100, 400, "Drücke die Leertaste um nocheinmal zu spielen!", 
		{fontSize: "24px", fontFamily: "Consolas", fill: "#ffffff", align: "center"});
		
		pointer = this.input.activePointer;
		this.player = this.add.text(200, 200, "");

		element = this.add.dom(400, 225).createFromCache("nameform");
		element.visible = true;
	    element.addListener('click');
		this.enterName();
		
		var userID = 1;
		var userName = this.player;
		var leaderBoard = this.plugins.get('rexfirebaseplugin').add.leaderBoard({root: "infoteam-universe"});
		leaderBoard.setUser(userID, userName);
		leaderBoard.post(this.score);
		leaderBoard.loadFirstPage()
    	.then(function(scores) { })
    	.catch(function(error) {
			return; 
		});
}
	
	update(){
		/*//restart at Scene ChooseChar.js if SPACE is pressed
		this.input.keyboard.once("keydown-" + "SPACE", () => {
			score = 0;
			this.scene.start("ChooseChar");	
		});
		
		if(pointer.isDown){
			score = 0;
			this.scene.start("ChooseChar");
		}*/

	}
	
	enterName(){	
	    element.on('click', (event) => {
	
	        if (event.target.name === 'playButton')
	        {
	           var name = element.getChildByName('nameField');
	
	            //  Have they entered anything?
	            if (name.value !== '')
	            {
	                element.removeListener('click');
	                element.setVisible(false);
					this.player = name.value;
	            }
			}
		});
	}



	
 }

I created an account at firebase.google.com and added a project with a webapp.
But now my console Shows this error:

[2020-06-06T20:28:25.619Z]  @firebase/firestore: Firestore (7.15.0): Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: FirebaseError: [code=failed-precondition]: The Cloud Firestore API is not available for Datastore Mode projects.
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.

But my device has a Internet connection…what could be the issue?

For the error i don’t, but don’t publish your api keys here, for security reasons

1 Like

While I’m not too familiar with firebase I’d agree not to post the API key here though your key is generally not a security risk either so don’t worry about it being in the Dev tools.

Change your firebase version to 7.14.0 in the cdn link. To see if it helps.

I see the issue talked about here https://github.com/firebase/firebase-js-sdk/issues/2923

Use of StarUML DDL to create HighScore leader board. Tutorial @ you Tube.