Angular Component for Handling Game Logic

This snippet showcases an Angular component that handles the logic for a game.
 avatar
FadadOussama
typescript
2 months ago
6.1 kB
3
Indexable
import { Component, ElementRef, ViewChild, ViewEncapsulation } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { Subject, takeUntil } from "rxjs";
import { environment } from "src/environments/environment";
import { RouteOrderGameGuard } from "../../../core/guards/route-game.guard";
import { RouteGameService } from "../../../core/services/route.game.service";
import { LasService } from "../../../core/services/las.service";
import { ThemeService } from "../../../core/services/theme.service";
import { RoutingOrderService } from "src/app/core/services/routing-order.service";
import { JourneyOfflineService } from "../../../core/services/journey.offline.service";

@Component({
	selector: "instruction-game",
	templateUrl: "./instruction.component.html",
	styleUrl: "./instruction.component.scss",
	encapsulation: ViewEncapsulation.None,
})
export class InstructionComponent {
	unsubscriber: Subject<any> = new Subject<any>();
	backendURL = environment.backendURL;

	// Campaign Variables
	campaignHeader: any;
	footerText: string;

	// LAS Variables
	ngStyle: any;
	lasData: any;

	// Global Variables
	gameData: any = null;
	gameHeaderOpt: boolean;
	gameFooterOpt: boolean;
	gameCTAOpt: boolean;
	gameLogVerfication: any;

	// Component Varibales
	stepName: string;
	backgroundImageUrl: string;
	footerBtnText: string;

	// Final Step
	isFinalStep: boolean = false;

	constructor(
		private router: Router,
		private activatedRoute: ActivatedRoute,
		private routeGuard: RouteOrderGameGuard,
		private routeGameService: RouteGameService,
		private lasService: LasService,
		private themeService: ThemeService,
		private routingOrderService: RoutingOrderService,
		private journeyOfflineService: JourneyOfflineService
	) {}

	// --------------------------------------------------------------------------------------------
	// @ Lifecycle hooks
	// --------------------------------------------------------------------------------------------
	ngOnInit() {
		// Initial game logic
		this.initialGameLogic();
	}

	ngOnDestroy(): void {
		this.unsubscriber.next(null);
		this.unsubscriber.complete();
	}

	// --------------------------------------------------------------------------------------------
	// @ Events
	// --------------------------------------------------------------------------------------------
	onFooterBtnClick() {
		const gamesType = localStorage.getItem("gamesType");

		if (gamesType === "multi") {
			this.routingOrderService.navigateToNext("game-chooser");
		} else if (gamesType === "mono") {
			// Enter the name of the next step
			this.routingOrderService.navigateToNext("tobacco");
		}
	}

	// --------------------------------------------------------------------------------------------
	// @ Functions
	// --------------------------------------------------------------------------------------------
	initialGameLogic() {
		// Mark route as visited ( enter the name of the game )
		this.routeGuard.markRouteAsVisited("find-your-passion");

		// Check if this route is the final step ( enter the name of the game )
		this.isFinalStep = this.routeGameService.isFinalStep("find-your-passion");

		// Add step to the journey offline ( enter the name of the game )
		this.journeyOfflineService.addStep("find-your-passion", this.isFinalStep);

		// Initialize log verfication ( Call this once )
		this.initializeLogVerfication();

		// Subscribe to the campaign subject
		this.lasService.campaignSubject.pipe(takeUntil(this.unsubscriber)).subscribe((data: any) => {
			if (data != null) {
				this.campaignHeader = data.campaign?.theme?.header;
				this.footerText = data.campaign?.theme?.footer;

				// Start getting the data of the game, ex: "game-{name of the game in backend}.{name of the game in backend}"
				this.gameData = data.campaign?.steps.filter((e) => e.__component === "game-find-your-passion.find-your-passion")[0];

				this.gameHeaderOpt = this.gameData?.isHeaderEnabled;
				this.gameFooterOpt = this.gameData?.isFooterEnabled;
				this.gameCTAOpt = this.gameData?.isCTAEnabled;

				// Log step ( Call this once )
				const stepLebelFormated = this.removeSpacesBetweenWords(this.gameData.stepLabel);
				if (!this.gameLogVerfication[stepLebelFormated]) {
					this.stepName = this.gameData.stepLabel;
					this.lasService.lasSubject.pipe(takeUntil(this.unsubscriber)).subscribe((data) => {
						if (data != null) {
							this.lasData = data;
							this.logStep(this.lasData.journey, this.stepName, { ...(this.isFinalStep && { isFinalStep: true }) });
						}
					});

					this.updateLogVerfication(this.removeSpacesBetweenWords(this.stepName), "true");
				}

				// Set CTA text
				this.footerBtnText = this.gameData?.ctaText;

				// Set theme --------------------
				const theme = data.campaign?.theme;
				const { ngStyle, backgroundImageUrl } = this.themeService.getThemeStyles(theme, this.gameData);
				this.ngStyle = ngStyle;
				this.backgroundImageUrl = backgroundImageUrl;
			}
		});
	}

	// Log step ( Call this once )
	logStep(lasJourney: number, stepLabel: string, additionalData = {}) {
		this.lasService
			.logStep(lasJourney, stepLabel, additionalData)
			.pipe(takeUntil(this.unsubscriber))
			.subscribe({
				next: (response) => {
					// Enter the name of the game here to debug
					console.log("Journey find your passion game created:", response);
				},
				error: (error) => {
					console.error("Error creating journey:", error);
				},
			});
	}

	private initializeLogVerfication() {
		const storedState = localStorage.getItem("logVerfication");
		this.gameLogVerfication = storedState ? JSON.parse(storedState) : {};
	}

	private updateLogVerfication(key: string, value: any) {
		this.gameLogVerfication[key] = value;
		localStorage.setItem("logVerfication", JSON.stringify(this.gameLogVerfication));
	}

	removeSpacesBetweenWords(text: any) {
		return text.replace(/(\S)\s+(\S)/g, "$1$2");
	}
}
Editor is loading...
Leave a Comment