Blog>
Snippets

Multiplayer Game Lobby

Use Angular to create the front-end for a game lobby where players can join using WebSocket, with real-time updates on player's actions.
import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';
import { WebSocketSubject, webSocket } from 'rxjs/webSocket';

@Injectable({
  providedIn: 'root'
})
export class WebSocketService {
  private socket$: WebSocketSubject<any>;

  public connect(url:string): void {
    if (!this.socket$ || this.socket$.closed) {
      this.socket$ = webSocket(url);
    }
  }

  public sendMessage(msg: any): void {
    this.socket$.next(msg);
  }

  public getMessages(): Observable<any> {
    return this.socket$.asObservable();
  }
}
WebSocketService that handles the WebSocket connection, sending messages, and receiving messages. It utilizes the RxJS library for handling WebSocket as an Observable.
import { Component, OnInit, OnDestroy } from '@angular/core';
import { WebSocketService } from './web-socket.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-lobby',
  templateUrl: './lobby.component.html',
  styleUrls: ['./lobby.component.css']
})
export class LobbyComponent implements OnInit, OnDestroy {
  players: string[] = [];
  playerSubscription: Subscription;

  constructor(private webSocketService: WebSocketService) { }

  ngOnInit() {
    this.webSocketService.connect('wss://game-lobby.example.com');

    this.playerSubscription = this.webSocketService.getMessages().subscribe(
      (message) => {
        if (message.type === 'PLAYER_JOINED') {
          this.players.push(message.playerName);
        }
      }
    );
  }

  ngOnDestroy() {
    if (this.playerSubscription) {
      this.playerSubscription.unsubscribe();
    }
  }
}
LobbyComponent that uses the WebSocketService to handle the players' list in the lobby. It subscribes to the messages from the WebSocket to update the players' list in real-time.
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Multiplayer Game Lobby';
}
AppComponent is the root component of the Angular application that sets the title and includes the LobbyComponent into its template.