1

I am currently working on a simple JS game developed with Angular, and I am trying to register players using localStorage.

I have already done the part where I can store a player into localStorage, but what I am trying to do is to only register a player if the localStorage does not contain it, otherwise, I just want to move to the next page and continue the game where it was left.

I will provide all the code next.

home.component.html

<button
            class="btn btn-primary mt-3"
            type="button"
            routerLink="game"
            [disabled]="player.name === ''"
            (click)="addPlayer(name)"
          >
            JOIN
</button>

home.component.ts

export class HomeComponentComponent implements OnInit {
  constructor(public gameService: GameService) {}

  ngOnInit(): void {}

  player: Player = {
    name: '',
    score: 0,
    maxScore: 0,
  };

  addPlayer(name: HTMLInputElement) {
    this.gameService.addPlayer({
      name: name.value,
      score: 0,
      maxScore: 0,
    });
  }
}

game.service.ts

export class GameService {
  players: Player[];

  constructor() {
    this.players = [];
  }

  addPlayer(player: Player) {
    if (localStorage.getItem('players') === null) {
      if (localStorage.getItem('players')?.includes(player.name)) {
        alert('Player already exists');
      } else {
        this.players.push(player);
        localStorage.setItem('players', JSON.stringify(this.players));
      }
    } else {
      this.players = JSON.parse(localStorage.getItem('players') || '[]');
      this.players.push(player);
      localStorage.setItem('players', JSON.stringify(this.players));
    }
  }
}

player.ts

export interface Player {
    name: string;
    score: number;
    maxScore: number;
}

This is the first time I am working with localStorage, so maybe I am missing something and I have not figured it out yet.

PS: I am storing it with a key named "players" and the value is a string of player objects, like this:

[{"name":"Joe","score":0,"maxScore":0},{"name":"Mama","score":0,"maxScore":0}]
  • Maybe you could store it using HashMap and then look up by the key – Tony Ngo Apr 19 '22 at 11:04
  • @TonyNgo - Local storage only stores strings. But you could certainly store JSON for an array of `[key, value]` arrays and then load it, parse it, and pass it to the `Map` constructor, yeah. – T.J. Crowder Apr 19 '22 at 11:07

0 Answers0