spot-mlb game logic

 avatar
FadadOussama
typescript
23 days ago
5.9 kB
1
Indexable
Never
import { Component, OnInit, ViewEncapsulation } from "@angular/core";
import { ActivatedRoute, NavigationStart, Router } from "@angular/router";
import { CountdownConfig } from "ngx-countdown";
import { Subject, takeUntil } from "rxjs";
import { LasService } from "../../../core/services/las.service";
import { environment } from "src/environments/environment";

@Component({
	selector: "spot-mlb-game",
	templateUrl: "./game.component.html",
	styleUrl: "./game.component.scss",
	encapsulation: ViewEncapsulation.None,
})
export class GameComponent implements OnInit {
	unsubscriber: Subject<any> = new Subject<any>();
	backendURL = environment.backendURL;
	ngStyle: any;
	levelTime!: number;
	levelTheme!: any;
	config: CountdownConfig = { leftTime: this.levelTime, notify: 0, format: "mm:ss" };
	clickCount: number = 0;
	remainingTime: number = 0;
	isUserWinner: boolean = false;

	// Backend Values
	spotMlbData: any;
	HeaderTextLocal: string;
	spotMlbPack: string;
	spotMlbObject: number;
	outputImg: string;
	gameImageData: any;
	footerBtnText = "Suivant";

	// LocalStorage
	levelTimeLocal: string;
	levelThemeLocal: string;

	constructor(
		private router: Router,
		private activatedRoute: ActivatedRoute,
		private lasService: LasService
	) {
		if (this.router.getCurrentNavigation() && this.levelTime !== 0) {
			this.levelTime = Number(this.router.getCurrentNavigation()?.extras.state["levelValue"]);
			// Save the levelTime value in localStorage.
			localStorage.setItem("levelTime", `${this.levelTime}`);
		} else {
			this.levelTime = 0;
		}

		if (this.router.getCurrentNavigation()) {
			this.levelTheme = this.router.getCurrentNavigation()?.extras.state["levelTheme"];
			// Save the levelTheme value in localStorage.
			localStorage.setItem("levelTheme", `${this.levelTheme}`);
		}

		// Reset clickCount when navigating back.
		this.router.events.subscribe((event) => {
			if (event instanceof NavigationStart) {
				if (event.navigationTrigger === "popstate") {
					this.clickCount = 0;
					localStorage.setItem("clickCount", `${this.clickCount}`);
				}
			}
		});
	}

	// --------------------------------------------------------------------------------------------
	// @ Lifecycle hooks
	// --------------------------------------------------------------------------------------------
	ngOnInit(): void {
		let value = +localStorage.getItem("time");
		if (value <= 0) value = this.levelTime;
		this.config = { ...this.config, leftTime: value };

		this.levelTimeLocal = localStorage.getItem("levelTime");
		this.levelThemeLocal = localStorage.getItem("levelTheme");
		this.clickCount = +localStorage.getItem("clickCount") || 0;

		this.lasService.campaignSubject.pipe(takeUntil(this.unsubscriber)).subscribe((data: any) => {
			if (data != null) {
				this.spotMlbData = data.campaign.steps.filter((e) => e.__component === "game-spot-mlb.spot-mlb")[0];

				this.HeaderTextLocal = this.spotMlbData.ambiances[this.levelThemeLocal].headerTitle;
				this.spotMlbPack = this.spotMlbData.pack.url;
				this.spotMlbObject = this.spotMlbData.ambiances[this.levelThemeLocal].spotObjects.length;
				this.outputImg = this.spotMlbData.ambiances[this.levelThemeLocal].outputImg.url;
				this.gameImageData = this.spotMlbData.ambiances[this.levelThemeLocal].spotObjects;
				this.footerBtnText = this.spotMlbData.ctaText;

				// Set theme --------------------
				const theme = data.campaign.theme;
				this.ngStyle = { color: theme.textColor, "background-color": theme.bgColor, "background-image": "url(" + this.backendURL + theme.bgImg.url + ")" };
				if (this.spotMlbData.bgImg != null) {
					this.ngStyle["background-image"] = "url(" + this.backendURL + this.spotMlbData.bgImg.url + ")";
				}
			}
		});
	}

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

		// Remove saved countdown time from local storage.
		localStorage.removeItem("time");
	}

	// --------------------------------------------------------------------------------------------
	// @ Events
	// --------------------------------------------------------------------------------------------
	onFooterBtnClick() {
		this.router.navigate(["../final"], { relativeTo: this.activatedRoute });
	}

	handleEvent(event) {
		if (event.action === "notify") {
			localStorage.setItem("time", `${event.left / 1000}`);
			this.remainingTime = event.left / 1000;
		}
	}

	// Restart the game when the user loses
	handleGameReset() {
		if (this.clickCount < this.spotMlbObject && this.remainingTime === 0) {
			this.remainingTime = 1;
			this.isUserWinner = false;
			this.config = { leftTime: +localStorage.getItem("levelTime"), notify: 0, format: "mm:ss" };
			this.clickCount = 0;
		}

		// Reset the box image display
		const boxImages: NodeListOf<HTMLImageElement> = document.querySelectorAll(".box-img");

		if (boxImages) {
			boxImages.forEach((boxImage) => {
				boxImage.style.display = "inline-block";
			});
		}
	}

	handleBoxImg(event: MouseEvent) {
		const image = event.target as HTMLImageElement;

		this.clickCount++;
		localStorage.setItem("clickCount", `${this.clickCount}`);

		if (this.clickCount === this.gameImageData.length && this.remainingTime) {
			// Show modal when the user wins the game and reset the clickCount to 0.
			this.isUserWinner = true;
			localStorage.setItem("clickCount", "0");
			this.config = { leftTime: 0, notify: 0, format: "mm:ss" };
			this.clickCount = 0;
		}

		// Hide the image when it is clicked
		image.style.display = "none";
	}

	// --------------------------------------------------------------------------------------------
	// @ Function
	// --------------------------------------------------------------------------------------------
}
Leave a Comment