Why is this tetris piece not appearing fully on the grid when using arrays?

Below is the code snippet, and you can find a link to the jsfiddle below.

I'm facing an issue where the first row of the block is not being drawn, and dealing with these 2-dimensional loops is quite challenging for me. I am unable to figure out why the block is only starting from the second row instead of the beginning.

The purpose of the add_block function is to fetch array data from any block and position it on the grid based on the x and y coordinates.

If anyone knows how to rotate the block, that would be greatly appreciated. I've tried transposing and reversing each row to achieve a +90 degree rotation but haven't been successful in previous attempts.

I may not be the best at explaining things, but I'm willing to answer any questions you may have. Thanks in advance! I really want to understand how arrays and double for loops interact in my mind.

var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
canvas.width = 300;
canvas.height = 500;

var grid_columns = 10;
var grid_rows = 15;
var grid_cell_size = 10;

var grid = [];
function create_empty_grid(){
    for(var i=0;i<grid_columns;i++){
        grid[i] = [];
        for(var j=0;j<grid_rows;j++){
            grid[i][j] = 0;
        }
    }
}
function clear_grid(){
    for(var i=0;i<grid_columns;i++){
        for(var j=0;j<grid_rows;j++){
            grid[i][j] = 0;
        }
    }
}

var x = 0;
var y = 0;
var w = 2;
var h = 3;

var block = [];
block[0] = [
    [1,0,0,0],
    [1,1,0,0],
    [0,1,0,0],
    [0,0,0,0]
];
function add_block(num){
    var b = block[num];
    for(var i=0;i<w;i++){
        for(var j=0;j<h;j++){

            if(i >= x && j >= y && i <= w && j <= h){
                grid[i][j] = b[i][j];
            }
        }
    }
}

function draw(){
    for(var i=0;i<grid_columns;i++){
        for(var j=0;j<grid_rows;j++){
            ctx.fillStyle = "black";
            if(grid[i][j] === 1){
                ctx.fillStyle = "red";
            }else if(grid[i][j] === 0){
                ctx.fillStyle = "green";
            }
            ctx.fillRect(i*grid_cell_size,j*grid_cell_size,grid_cell_size-1,grid_cell_size-1);
        }
    }
}

function update(){

}
function tick(){
    clearRect(0,0,canvas.width,canvas.height);
    clear_grid();
    draw();
    update();
}

create_empty_grid();
add_block(0);
draw();

Check this out on jsfiddle

Answer №1

It appears that the variables i and j are being used to indicate coordinates within a "block", while x and y are indicating coordinates within a "grid". Based on this, it seems like the following condition is incorrect:

if(i >= x && j >= y && i <= w && j <= h){
                grid[i][j] = b[i][j];
            }

A more appropriate solution might be to replace the above if statement with something like:

 grid[i+x][j+y] = b[i][j];

However, @Arnauld has also pointed out some confusion regarding whether the values of i and j represent "row, column" or "column, row". It looks like your current usage is opposite to how the arrays are initialized. That is, you're utilizing:

grid[row][column] and b[row][column]

whereas it should actually be laid out as

grid[column][row] and b[column][row]

Therefore, some adjustments need to be made throughout the code in order for it to function correctly based on your intentions.

Answer №2

For some unknown reason, the "b" arrays appeared upside-down so I made a modification from grid[j+x][i+y] = b[j][i] to grid[j+x][i+y] = b[i][j]. This adjustment allowed me to view the complete block, although I still struggle to grasp the concept of arrays and how to avoid similar issues in the future.
Arrays continue to puzzle me.

I anticipate solving this dilemma eventually, even though it may take some time.

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

the session data is being mishandled

I have integrated express-session and express-mysql-session in my application to handle sessions and store them in a MySQL database. The session data is saved in a table named "sessions". const express = require('express'); const session = requir ...

Ways to retrieve the response object from an express application

I am currently working on developing a nodejs application with mysql and my objective is to have my controllers and messages separated into different files. Below are examples of what I am aiming for: First, here is a snippet from my auth controller file: ...

Position div elements randomly on the webpage when it first loads

I am trying to achieve a set of divs that will appear randomly on the page when it loads. Currently, I have the divs moving around the viewport in a random manner, but they all seem to load in the top left corner. This is the method I am currently using: ...

Loop through and display content on the webpage with a for loop

I'm attempting to create a loop that will display information in three different areas of the DOM. Essentially, I have an array of enemies and I want to randomly select three of them to display in separate HTML div classes (firstEnemy, secondEnemy, th ...

Create a downloadable document in AngularJS containing specific data

I need to collect user input values such as name, address, and phone number. Once the values are entered, I want to dynamically generate a downloadable MS Word document file on button click using AngularJS. How can I accomplish this task? Is it feasible t ...

Storing data with Laravel 5.3 using Storage::put and XMLHttpRequest

Attempting to send a file using DRAG & DROP with XMLHttpRequest. $images = $_FILES['images']; When I use foreach: foreach($images["name"] as $file => $name) and move_uploaded_file($images["tmp_name"][$file], $images_dir . $name it works ...

Tri-party class switch-up

I successfully implemented two radio buttons to toggle between alternative texts: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> ...

How can I ensure my game or website fits perfectly on the screen without any need

I have recently developed a fun Erase-A-Man game that is optimized for mobile devices. However, I am facing an issue where users need to scroll to view all the letters on their screens. My goal is to make the game fit perfectly on all phone screen sizes so ...

Is it possible to create an API directly within the URL of a React.js application, similar to how Next.js allows?

When using Next.js, I can access my application on localhost:3000, and also access my API from localhost:3000/api/hello. I'm curious if there is a way to achieve this same setup with React.js and another framework like Express.js? If Next.js is not ...

JavaScript code that functions similarly to VLOOKUP, allowing you to map input values from one field to

As a beginner in HTML and JavaScript, I am trying to create a simple form that automatically populates a specific "Customer Code" when a "Customer Name" is selected from a dropdown list (similar to an Excel VLOOKUP). However, the examples I found on Stack ...

Struggling with Implementing jQuery for Triggering Multiple Functions on a Single Change Event?

I am currently developing jQuery functions that create dependencies between the css classes of different inputs in a web form. For example, when a specific input has a certain value, the "hide" class is removed from another input. One working example of t ...

Issue with retrieving the positions of two numbers in an array

I encountered a challenge: I have an array of integers nums and an integer target. My goal is to find the indices of two numbers in the array that add up to the specified target. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Thi ...

What is the reason that self focus doesn't function in JavaScript?

Whenever an input element triggers a blur event, I want to focus on a specific element. The issue arises when I try to focus on the same element that caused the blur event. Why does this only work when the element I am focusing on is not the one triggeri ...

Methods to troubleshoot problem of angular component loading issue in firefox with ViewEncapsulation.Native

I am encountering a problem with loading an angular component using ViewEncapsulation.Native in firefox, edge, and ipad chrome. Interestingly, there is no issue on safari on mac, chrome on windows, or chrome on android. Error: hostEl.createShadowRoot is ...

Angular is programmed to detect any alterations

Upon detecting changes, the NgOnChanges function triggers an infinite service call to update the table, a situation that currently perplexes me. Any assistance on this matter would be greatly appreciated. Many thanks. The TableMultiSortComponent functions ...

Dealing with adding up optional values from v-model in Vue.js can be a challenging task

Within this function, I need to display the remaining amount. remainingAmount: function() { return parseFloat(this.sumAmount) - (parseFloat(this.cash) + parseFloat(this.kNet) + parseFloat(this.kNetOnline)); } The three parameters cash ...

Learn how to establish a state using an array and effectively utilize the setState() method in React

For my latest project, which is API based, I am working with arrays that contain sub-arrays. How can I define a state with an array and utilize the setState() method to work with the entire array? ...

The backend function of an aspx page is failing to execute when triggered by a $.ajax request

Currently, I am facing an issue with a web form IndexPage.aspx. The script in this front-end code makes an ajax call to a code-behind function. Take a look at the code snippet below: $.ajax({ type: "POST", url: &apos ...

There seems to be a contradiction in my code - I am returning a Promise but TypeScript is throwing an error saying that the

I currently have a function that retrieves a bot's inventory on the Frontend fetchBotInventory() { this.socket.emit('fetch bot inv'); this.socket.on('bot inv', (botInventory) => { return new Promise((resolve, re ...

Unable to select image inside linked container

I'm attempting to display a dropdown menu when the user clicks on the gear-img div using jQuery. However, because it's wrapped inside an a tag, clicking redirects me to a URL. I also want the entire div to be clickable. Any suggestions for a solu ...