Angular Snake Game glitch - Snake fails to appear

As I embark on the initial phase of developing a snake game, the following steps are required: 1- Establish the game board 2- Create the snake and fruit elements 3- Display the snake and fruit accordingly However, I encounter an issue where the board gets updated after spawning the snake and fruit, but they do not appear on the game board. Note: In each cell, 0 denotes emptiness, 1 represents a snake body, and 2 signifies a fruit.

HTML -> gameboard component:

<div class="gameB">
    <div *ngFor="let i of board" class="row"gt;
        <div *ngFor="let j of i" class="cell"
        [ngClass]="{'snake' : board[board.indexOf(i)][j] === 1, 'fruit': board[board.indexOf(i)][j] === 2}">
            {{ board[board.indexOf(i)][j] }}
        </div>
    </div>
</div>

TS -> gameboard component:

import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { NgModule } from '@angular/core';
import { Snake } from '../snake-iterface';


@Component({
  selector: 'app-game-board',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './game-board.component.html',
  styleUrl: './game-board.component.css'
})
export class GameBoardComponent implements OnInit{
  boardWidth:number = 20;
  boardHeight:number = 20;
  board:number[][] = [];
  snake:Snake = {} as Snake;
  fruit:number[] = [1,1];
  createBoard(){
    let temp:number[];
    for(let i = 0; i < this.boardHeight;i++){
      temp =[]
      for(let j = 0; j < this.boardWidth;j++){
        temp.push(0)
      }
      this.board.push(temp)
    }
  }
  spawnSnake():void{
    this.board[this.snake.headPositionY][this.snake.headPositionX] = 1;
  }
  updateBoard():void{
    for(let i = 0; i < this.boardHeight; i++){
      for(let j = 0; j < this.boardWidth;j++){
        if(this.snake.bodyPositions.includes([j, i]) ){
          this.board[i][j] = 1;
        }else if((j === this.fruit[0] && i == this.fruit[1])){
          this.board[i][j] = 2;
        }
      }
    }
  }


  ngOnInit(): void {
    this.createBoard()
    console.log("Before Snake creation", this.board)
    this.snake = {
      headPositionX: Math.floor(this.boardWidth / 2),
      headPositionY: Math.floor(this.boardHeight / 2),
      bodyPositions: [[Math.floor(this.boardWidth / 2), Math.floor(this.boardHeight / 2)]],
      length: 1,
      direction: 'right'
    };


    console.log("Before Spawn", this.board)
    this.spawnSnake()
    
    
    this.updateBoard()
    console.log("After Update 1", this.board)
    setTimeout(this.updateBoard, 1000)
    console.log("After Update 2", this.board)
  }

}

CSS -> gameboard component:


.gameB{
    margin: auto;
    padding:10px;
    display: flex;
    flex-direction: column;
    gap: 3px;
    background-color: black;
    width:fit-content;
}
.row{
    display: flex;
    flex-direction: row;
    gap: 3px;
}
.cell{
    width:20px;
    height:20px;
    background-color: grey;
}
.snake{
    background-color:red;
}
.fruit{
    background-color:purple;
}

Other Files:

HTML -> app component:

<app-game-board></app-game-board>

HTML -> index.html:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>SnakeGame</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>

Note: The first console log seems to indicate that the snake and fruit have been added to the board even before being created or updated (how?????) Subsequent logs reveal consistent results

Note: Angular 17 is being used

Please provide precise guidance in your response, as I am relatively new to Angular development

I have attempted to adjust the placement of the snake declaration within the ngOnInit method, but the issue persists

Answer №1

When looking at game-board.component.html, there seems to be a misunderstanding that j is the index of the row, when in fact it represents the content of the cell.

To correct this issue, you just need to adjust the code as follows:

<div class="gameB">
    <div *ngFor="let i of board" class="row">
        <div
            *ngFor="let j of i"
            class="cell"
            [ngClass]="{'snake' : j === 1, 'fruit': j === 2}"
        >
            {{j}}
        </div>
    </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An error occurred while defining props due to a parsing issue with the prop type. The unexpected token was encountered. Perhaps you meant to use `{`}` or `}`?

const dataProps = defineProps({ selectedData: <Record<string, string>> }); Under the closing bracket, there is a red line indicating: Error: Unexpected token. Consider using {'}'} or &rbrace; instead?eslint Expression expecte ...

Monitoring the current scroll position and updating other components on changes

Is there a way to easily monitor the scroll position of the browser and inform multiple components about it? For example, I would like to dynamically change the classes of different elements on the page as the user scrolls. In the past, with older version ...

"Dealing with cross-origin resource sharing issue in a Node.js project using TypeScript with Apollo server

I am encountering issues with CORS in my application. Could it be a misconfiguration on my server side? I am attempting to create a user in my PostgreSQL database through the frontend. I have set up a tsx component that serves as a form. However, when I tr ...

Issues with Angular2 causing function to not run as expected

After clicking a button to trigger createPlaylist(), the function fails to execute asd(). I attempted combining everything into one function, but still encountered the same issue. The console.log(resp) statement never logs anything. What could be causing ...

Guide to accessing a nested and potentially optional object property with a default value and specifying its data type

Just a simple query here... my goal is to extract data.user.roles, but there's a possibility that data may be empty. In such cases, I want an empty array as the output. Additionally, I need to specify the type of user - which in this instance is any. ...

Tips for restricting the date range selection in an Angular Kendo datepicker

Looking for a way to restrict the date range selection in Angular using Kendo-ui. Currently, I have implemented a datepicker in Angular with kendo-ui, as shown in the screenshot below: https://i.sstatic.net/oBWNu.png I want to limit the user to selectin ...

Initialize app by calling Angular 13 service loader

I'm currently using Angular 13 and attempting to connect with Angular's bootstrapping phase through the APP_INITIALIZER token. I need to create an Angular service that manages the retrieval of our remote configuration. However, I've run into ...

Separating HTML content and text from a JSON response for versatile use within various sections of an Angular 2 application using Typescript

Hello there! I am currently utilizing Angular 2 on the frontend with a WordPress REST API backend. I'm receiving a JSON response from the service, however, the WP rest API sends the content with HTML tags and images embedded. I'm having trouble s ...

Personalize ng-multiselect-dropdown in order to establish connections with multiple model fields

https://i.sstatic.net/iLUNf.png Is there a way to customize the ng-multiselect-dropdown control in order to include a CodeField? This would be helpful for persisting model values during selection. https://i.sstatic.net/JQgYM.png ...

What is the best way to assign ngModel to dynamically inserted input rows in Angular 4+ (specifically in a mat-table)?

Just a quick question - how can I add ngModel to dynamically added new input rows? I have a Mat table with multiple rows and an "add element" method that adds a new row every time a button is clicked. This way, I want to bind the user-entered values and se ...

What is the best way to filter out specific data fields from console.log in JavaScript?

When working with Java, I often use lombok to exclude certain fields from being printed. For instance, the @ToString.Exclude annotation can be used to prevent printing the user token. import lombok.ToString; public class TokenResponse { @ToString.Excl ...

The VSCode debugger is like a frozen statue, refusing to budge or take

Seeking assistance with configuring debugging for an Angular project using VSCode and Chrome. Despite reviewing numerous guides and tutorials, none of the solutions seem to work. The goal is to make the launch configuration function properly (not the attac ...

Highlighting the home page in the navigation menu even when on a subroute such as blog/post in the next.js framework

After creating a navigation component in Next JS and framer-motion to emphasize the current page, I encountered an issue. The problem arises when navigating to a sub route like 'localhost:3000/blog/post', where the home tab remains highlighted i ...

Does the Typescript compiler sometimes skip adding braces?

I am encountering a problem with compiling a specific section of code in my Angular2 project. public reloadRecords() { let step = (this.timeInterval.max - this.timeInterval.min) / this.recordsChartSteps; let data = new Array(this.recordsChartSteps ...

In TypeScript, fetch JSON data from a URL and gain access to an array of JSON objects

I'm struggling to find a solution and implement it in the correct format. An API returns a JSON file to me via a URL. The format is as follows: {"success":true, "data":[ { "loadTimestamp":"2022-07-20T ...

How to convert DateTime to UTC in TypeScript/JavaScript while preserving the original date and time

Consider the following example: var testDate = new Date("2021-05-17T00:00:00"); // this represents local date and time I am looking to convert this given Date into UTC format without altering the original date and time value. Essentially, 2021-0 ...

What is the reasoning behind exporting it in this manner in the index file?

As I was going through a tutorial about nests, there was this step where the instructor made a folder named "dtos" and inside it, they created two dto files (create-user.dto and edit-user.dto). Following that, they also added an index file in the same fold ...

Defining RefObject effectively in TypeScript

Greetings everyone, I am a newcomer to TypeScript and currently attempting to create a type for a RefObject that is of type HTMLAudioElement. However, I have encountered an error message. The error states: Type 'MutableRefObject<HTMLAudioElement> ...

Loading time for page style can be slow when using Next Js

When the user opens or reloads the page, there is a delay in loading the style of the page. I am relatively new to working with next js and still learning the core abilities of the framework. This GIF illustrates the slow loading time when opening or relo ...

Showing Information without NgFor Directives

I have successfully displayed data without using a ngFor loop. However, it is currently showing all the quote information from multiple customers. The CSS is arranged in such a way that the discount div is positioned next to the customerinfo div. Below is ...