0

currently I am making a mini game with angular, and I already have most functionalities working. I am currently struggling to implement to change picture every time either (not have decided yet):

  1. change from A->F whenever I have collision with an obstacle
  2. change from F-> whenever I have scored more than a certain score (say 200-300 : D 300-400: C === and so on...)

I have tried a lot of things, and seems to not work.

I have used ngSwitchCase in the html.

This is my Obstacle service `

import { Injectable } from '@angular/core';
import { Cords, Dimensions, playerCords,playerDms } from './player.service';

// global variables for use.
export let platCords:Cords = { xoffset:0, yoffset:0 };
export let platDms:Dimensions = { width:0, height:0 };
export let start:boolean = false;
export let score:number[] = [0,0];
export let grade:String;

export class Obstacle{
  height:number;
  width:number;
  left:number;
  bottom:number;
  type:number;
  xoffset:number = 0;
  yoffset:number = 0;
  life:number;



  constructor(h:number,w:number,b:number,t:number) {
    // init the members
    this.height = h;
    this.width = w;
    this.type = t;
    this.left = platDms.width;
    this.bottom = b;
    this.xoffset = this.left + w;
    this.yoffset = platCords.yoffset - h - b;
    this.life =4;


    // start the motion of this obstacle and check for collision
    this.moveLeft(t);
  }

  // moving the obstacle by subtracting the xoffset.
  moveLeft(t:number){

    let leftTimer = setInterval(()=>{
      // remove the obstacle from array when moves out of game screen and increase score
      if(this.left<=-(this.width)){
        clearInterval(leftTimer);
        score[0] += 10;
        obs.splice(0,1);
      }
      this.left -= 5;
      this.xoffset -= 5;


      // check for collision when its moving.
      if( (this.collision(t)) || !start){
        // stop the game
        clearInterval(leftTimer);
        start =  false;
      }

    },15);
  }

  // collision function for two floating and running obstacles.
  collision(t:number):boolean{

    let o_A:Cords,o_B:Cords,d_A:Cords,d_B:Cords;
    
    switch (t) {  
      case 1:
        // for running obstacles.
        d_B = {xoffset:playerCords.xoffset+20, yoffset:playerCords.yoffset+playerDms.height};
        d_A = {xoffset:playerCords.xoffset, yoffset:playerCords.yoffset+playerDms.height};
        o_A = {xoffset:this.xoffset, yoffset:this.yoffset};
        o_B = {xoffset:this.xoffset-this.width, yoffset:this.yoffset};

        if((o_B.xoffset <= d_B.xoffset  && o_B.xoffset >= d_A.xoffset) && (d_B.yoffset > o_A.yoffset)){
          return true
        }
        break;

      case 2:
        // for floating obstacles.
        d_B = {xoffset:playerCords.xoffset+20, yoffset:playerCords.yoffset};
        d_A = {xoffset:playerCords.xoffset, yoffset:playerCords.yoffset};
        o_A = {xoffset:this.xoffset, yoffset:this.yoffset+this.height};
        o_B = {xoffset:this.xoffset-this.width, yoffset:this.yoffset+this.height};

        if((o_B.xoffset < d_B.xoffset && o_B.xoffset >= d_A.xoffset) && (o_A.yoffset > (d_A.yoffset))){
          return true
        }
        break;
  }
return false
  }

};

// having array of obstacles
export let obs:Obstacle[] = [];

@Injectable({
  providedIn: 'root'
})
export class ObstacleService {

  playing:boolean = false;
  gameSpeed:number = 900;
  constructor() { }


  /**
    Actions
    1. Creating Obstable
    2. Removing off screeen obstacles
    3. Run left for every obstacle.
   */

  spawning(){
    start = this.playing = true;
    score[0] = 0;
    let spawnTime = setInterval(()=>{
      score[0]++;

      if(!start){
        clearInterval(spawnTime);
        console.log("Game Ended");
        this.playing = false;
        if(score[0]>score[1])
          score[1] = score[0];
        console.log("Score : "+score);
      }
      //create obstacle and add it to array
      let t = Math.floor(Math.random() * 5)
      if(t<=3){
        // type 1.
        let rh = Math.floor(Math.random() * (30 - 20) + 20);
        let rw = Math.floor(Math.random() * (30 - 20) + 20);
        obs.push(new Obstacle(rh,rw,-2,1));
      }
      else{
        // type 2
        let rw = Math.floor(Math.random() * (30 - 15) + 15);
        let rh = Math.floor(Math.random() * (40 - 30) + 30);
        let rb = Math.floor(Math.random() * (30 - 25) + 25);
        obs.push(new Obstacle(rh,rw,rb,2));
      }

    },this.gameSpeed);
  }

}


`

This is my html is game screen '

<div class="container">
  <div class="game-screen">
    <div class="logo">
      <img class = "panicIcon" src="assets/panic.png" alt="">
      <h2> {{username}}, RUN AND DON'T STOP</h2>
      <button style="margin-left: auto;margin-top: 20px;" [routerLink]="['/']">Home</button>
    </div>
    <div class="rules">
      <p *ngIf="!ob.playing && score[0]==0">
        Press <img src="assets/enter.png" alt=""> "Enter" to play.
      </p>
      <p *ngIf="!ob.playing && score[0]>0">
        <img src="assets/dead.png" alt=""><br>Game Over You Got Caught
      </p>
      <div class="score">
        <p>Highest Score : <strong> {{score[1]}} </strong></p>
        <p>Score : <strong> {{score[0]}} </strong></p>
      </div>
    </div>
    <div class="game">
      <div class="screen">
        <div class="platform" #platform>
          
          <div *ngIf="start == false">
            <div class="initbox">
              <img class="angrybubble" src="assets/angrybubble.png">
              <div class="normanText">Run For Your Life</div>
            </div>
          </div>
          <div class="norman" #norman [style.bottom.px]="ns.bottom" [style.height.px]="normanDMS.height">
            <img class="normanimg" src="assets/norman.png">
          </div>
          <div class="dino" #dino [style.bottom.px]="ps.bottom" [style.height.px]="playerDms.height">
            <img class="playerimg" src="assets/player.png">
          </div>

          <div class="obs" *ngFor="let i of obs" [style.height.px]="i.height" [style.width.px]="i.width"
            [style.bottom.px]="i.bottom" [style.left.px]="i.left"></div>
            <ng-container [ngSwitch]="grade">
              <img *ngSwitchCase="'a'" class="gradeimg" src="assets/letterA.png" />
              <img *ngSwitchCase="'b'" class="gradeimg" src="assets/letterB.png" />
              <img *ngSwitchCase="'c'" class="gradeimg" src="assets/letterC.png" />
              <img *ngSwitchCase="'d'" class="gradeimg" src="assets/letterD.png" />
              <img *ngSwitchCase="'f'" class="gradeimg" src="assets/flamingF.png" />
              
            </ng-container>
        </div>
      </div>
    </div>
    <div class="keypad">
      <div class="keypad-btn">
        <button [disabled]="ob.playing" (click)="startGame()">Play</button>
        <div>
          <button [disabled]="!ob.playing" (click)="ps.jump()">Jump</button>
          <button [disabled]="!ob.playing" (click)="ps.duck()">Duck</button>
        </div>
      </div>
    </div>
  </div>
</div>

'

Here is my gamescreen component just in case:

`

import { Component, ElementRef, HostListener, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Dimensions, PlayerService } from '../../services/player.service';
import { Obstacle, ObstacleService, score, start } from '../../services/obstacle.service';
import { obs,platCords,platDms, grade } from '../../services/obstacle.service';
import { playerCords,playerDms } from '../../services/player.service';
import { normanCords,normanDms, NormanService } from '../../services/norman.service';

@Component({
  selector: 'app-game-screen',
  templateUrl: './game-screen.component.html',
  styleUrls: ['./game-screen.component.scss']
})
export class GameScreenComponent implements OnInit{

  username:string | null = null;
  start:boolean = false;
  obs:Obstacle[]=obs;
  playerDms:Dimensions = playerDms;
  normanDMS:Dimensions = normanDms;
  score:number[] = score;
  grade:String = grade;

  @ViewChild('player') playerRef!: ElementRef;
  @ViewChild('norman') normanRef!: ElementRef;
  @ViewChild('platform') platformRef!: ElementRef;




  constructor(private route:ActivatedRoute,
              public ps:PlayerService,
              public ns: NormanService,
              public ob:ObstacleService,
              private router:Router) {

    // retrieving the data passed from route
    this.username = this.route.snapshot.paramMap?.get('user');
    if(this.username === null || this.username==""){
      this.router.navigate(['/']);
    }

  }


  // listening to the key down evnets
  @HostListener('document:keydown', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) {

    switch (event.key) {
      case ' ':
      case 'ArrowUp':
            if(this.ob.playing)
              this.ps.jump();
            break;

      case 'Enter':
            if(!this.ob.playing)
              this.startGame();
              this.start = true;
            break;

      case 'ArrowDown':{
              this.ps.duck();
            }
            break;
    }
  }


  ngOnInit(): void {
  }

  // start or restart the game on spacebar button.
  // start : clear all the obstacle and score and other stuff.
  startGame(){
    obs.splice(0,obs.length);
    this.ps.bottom = 0;
    playerDms.height = 30;
    playerCords.xoffset = 150;
    playerCords.yoffset = 328;
    this.ns.bottom = 0;
    normanDms.height = 60;
    normanCords.xoffset = 50;
    normanCords.yoffset = 600;

    let plCords = this.platformRef.nativeElement.getBoundingClientRect();
    platCords.xoffset = Math.floor(plCords.x + plCords.width);
    platCords.yoffset = Math.floor(plCords.y + plCords.height);

    platDms.width = Math.floor(plCords.width);
    platDms.height = Math.floor(plCords.height);

    this.ob.spawning();
  }


}

`

I have tried doing if statements and changing variable "grade" but it seems to not apply and just keep displaying initial "F" even when condition is met.

0 Answers0