|
| 1 | +import Phaser from "phaser"; |
| 2 | + |
| 3 | +export class NameEntryScene extends Phaser.Scene { |
| 4 | + private enteredName: string = ""; |
| 5 | + private score: number = 0; |
| 6 | + private nameText!: Phaser.GameObjects.Text; |
| 7 | + |
| 8 | + constructor() { |
| 9 | + super("NameEntryScene"); |
| 10 | + } |
| 11 | + |
| 12 | + init(data: { score: number }) { |
| 13 | + this.score = data.score; |
| 14 | + } |
| 15 | + |
| 16 | + create() { |
| 17 | + const { width, height } = this.cameras.main; |
| 18 | + |
| 19 | + document.fonts.load('20px "Monogram"').then(() => { |
| 20 | + this.add |
| 21 | + .text(width / 2, 10, "ENTER YOUR INITIALS", { |
| 22 | + fontFamily: "Monogram", |
| 23 | + fontSize: "20px", |
| 24 | + color: "#0f380f", |
| 25 | + }) |
| 26 | + .setOrigin(0.5); |
| 27 | + |
| 28 | + this.add |
| 29 | + .text(width / 2, height - 24, "Confirm: SPACE", { |
| 30 | + fontFamily: "Monogram", |
| 31 | + fontSize: "20px", |
| 32 | + color: "#0f380f", |
| 33 | + }) |
| 34 | + .setOrigin(0.5); |
| 35 | + |
| 36 | + this.nameText = this.add |
| 37 | + .text(width / 2, height / 2, `${this.nameText ?? ""}`, { |
| 38 | + fontFamily: "Monogram", |
| 39 | + fontSize: "20px", |
| 40 | + color: "#0f380f", |
| 41 | + }) |
| 42 | + .setOrigin(0.5); |
| 43 | + |
| 44 | + this.input.keyboard?.on("keydown", (event: KeyboardEvent) => { |
| 45 | + const key = event.key; |
| 46 | + if (/^[a-zA-Z]$/.test(key) && this.enteredName.length < 3) { |
| 47 | + this.enteredName += key.toUpperCase(); |
| 48 | + this.updateNameDisplay(); |
| 49 | + } else if (event.key === "Backspace" && this.enteredName.length > 0) { |
| 50 | + this.enteredName = this.enteredName.slice(0, -1); |
| 51 | + this.updateNameDisplay(); |
| 52 | + } else if (event.key === " ") { |
| 53 | + this.saveScore(); |
| 54 | + this.scene.start("MenuScene"); |
| 55 | + } |
| 56 | + }); |
| 57 | + }); |
| 58 | + } |
| 59 | + |
| 60 | + updateNameDisplay() { |
| 61 | + this.nameText.setText(this.enteredName); |
| 62 | + } |
| 63 | + |
| 64 | + saveScore() { |
| 65 | + const newEntry = { name: this.enteredName, score: this.score }; |
| 66 | + const stored = localStorage.getItem("switchy-hiscores"); |
| 67 | + let scores = stored ? JSON.parse(stored) : []; |
| 68 | + |
| 69 | + scores.push(newEntry); |
| 70 | + scores.sort((a: any, b: any) => b.score - a.score); |
| 71 | + scores = scores.slice(0, 5); // Keep only top 5 scores |
| 72 | + |
| 73 | + localStorage.setItem("switchy-hiscores", JSON.stringify(scores)); |
| 74 | + } |
| 75 | +} |
0 commit comments