Unable to see the tokens on the connect four board when using Javascript and HTML

I'm currently developing a game of connect four using javascript, html, and css. I'm encountering an issue with the refreshGrid() function in game.js. At the moment, when I run my html file, I only see an empty board. The function is meant to enable a chip to appear on the board when a user clicks on an empty space. I'm unsure why this function isn't functioning correctly and would appreciate any assistance. I suspect there may be an issue with how I'm iterating through the rows and columns.

var player=1; 
var grid = [
  [0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0]
];

function selectColumn(col) {
  if(player==1){
    grid[5][col]=1;
    player=2;
    document.getElementById("box1").innerHTML="Player 1's Turn";
  }else{
    grid[5][col]=2;
    player=1;
    document.getElementById("box1").innerHTML="Player 2's Turn";
  }
  refreshGrid();
}

function refreshGrid() {
  for (var row = 0; row < 6; row++) {
    for (var col = 0; col < 7; col++) {
      if (grid[row][col]==0) { 
                document.getElementById("cell"+row+col).style.backgroundColor="#FFFFFF";
      } else if (grid[row][col]==1) { //1 for yellow
                document.getElementById("cell"+row+col).style.backgroundColor="#FFFF00";
      } else if (grid[row][col]==2) { //1 for yellow
                document.getElementById("cell"+row+col).style.backgroundColor="#FF0000";
       }
    }
  }  
}
<div id="box1"><h1>Player 2's turn.</h1></div>
<div id="grid">
  <div class="column" id="column-0" data-x="0">
    <svg height="75" width="75" stroke="black" stroke-width="5" class="row-5" onclick="selectColumn(5)">
          <circle cx="45" cy="45" r="30"   class="free" />
        </svg>
    ...
    ...
    ...
  </div>
  ...
  ...
  ...
</div>

Answer №1

Your code needs some significant improvements. I will provide some suggestions and tips to help you rectify the issues.

var player=1; 
var grid = [
  [0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0]
];

function selectColumn(col) {
  for (let row = 0; row < 7; ++row) {
    if(grid[row][6-col]){
      continue;
    }
    if(player==1){
      grid[row][6-col]=1;
      player=2;
      document.getElementById("box1").innerHTML="Player 1's Turn";
    }else{
      grid[row][6-col]=2;
      player=1;
      document.getElementById("box1").innerHTML="Player 2's Turn";
    }
    break;
  }
  refreshGrid();
}

function refreshGrid() {
  for (var row = 0; row < 6; row++) {
    for (var col = 0; col < 7; col++) {
      const htmlElement = document.querySelector(`#column-${6-col} .row-${row}`);
      if (grid[row][col]==0) { 
                htmlElement.style.backgroundColor="#FFFFFF";
      } else if (grid[row][col]==1) { //1 for yellow
                htmlElement.style.backgroundColor="#FFFF00";
      } else if (grid[row][col]==2) { //1 for yellow
                htmlElement.style.backgroundColor="#FF0000";
       }
    }
  }  
}
.column {
  display: grid;
  grid-auto-flow: row;
}

#grid {
  display: grid;
  grid-auto-flow: column;
}
<div id="box1"><h1>Player 2's turn.</h1></div>
<div id="grid">
    <div class="column" id="column-0" data-x="0">
        <svg height="75" width="75" stroke="black" stroke-width="5" class="row-5" onclick="selectColumn(0)">
          <circle cx="45" cy="45" r="30"   class="free" />
        </svg> 
        ... //rest of the SVG elements
    </div>
    ... //rest of the columns
</div>
    <script src="game.js"></script>
</div>

Your code lacks organization and clarity. I took the liberty to improve it because I found the concept interesting and wanted to see it in action.

Key points to note:

Your HTML structure had inverted columns and rows, causing confusion.

You were calling the selectColumn function with the same index inside the same column.

Avoid using magic numbers; define constants for values like the number of rows and columns.

You can generate an array with JavaScript and dynamically create HTML elements based on that array.

You were referencing a non-existent board variable in your code.

Ensure to properly define IDs for rows and columns when selecting elements in your script.

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

It can be frustrating to have to refresh the page twice in order to see changes when utilizing the revalidate feature in Next

When I make the REST call to fetch data for my page using the code below: // src/app/page.js const Home = async () => { const globalData = await getGlobalData(); return ( <main'> <SomeComponent data={globalData} /> < ...

Using Selenium with Python to extract text from an element excluding any text within its nested tags

There is a specific element in question '<div class="ProductVariants__PriceContainer-sc-1unev4j-9 jjiIua">₹199 <span class="ProductVariants__MRPText-sc-1unev4j-10 jEinXG">₹690</span></div>' The goa ...

Convert a single object into a JSON string representation on each line

Can you convert the following data into the desired format through stringification? Data: let result = JSON.stringify([ { "Color": "Red", "Type":"Fast" }, { "Color": "Blue&quo ...

2-panel accordion interface

Hello there, I've encountered a problem that seems to be related to CSS. Here is the project I'm currently working on: My main focus is on the News accordion menu. The goal is to display a small image (50x50 with padding) next to a large headlin ...

What exactly are Node.js core files?

I recently set up my Node.js application directory and noticed a presence of several core.* files. I am curious about their purpose - can these files be safely removed? The setup involves installing Node.js alongside Apache using mod_proxy to host one of ...

Manipulation of CSS DOM elements for achieving responsive design

I am working with a div field that contains an input element and a label element, both set to display:block <div class="cf-full"> <input id="a" > <label class="helptext"></label> </div> In the standard view, the inpu ...

Discovering the Authentic Page upon Completion of Load using PhantomJS

I am facing an issue while automatically downloading a theme on Wordpress using PhantomJS. The problem arises because the page is not fully evaluated even after it appears to be done loading. When trying to interact with elements on the page, such as clic ...

How can you efficiently manage Access & Refresh tokens from various Providers?

Imagine I am allowing my users to connect to various social media platforms like Facebook, Instagram, Pinterest, and Twitter in order to use their APIs. As a result, I obtain access tokens for each of these providers. Based on my research, it seems advisa ...

Implementing automatic line breaks in Bootstrap

When setting the "overflow scroll able" option, I want it to only allow scrolling in the y direction and if x content overflows, a line break should occur. I tried applying 'white-space', but it didn't work as expected. <ul class="s ...

Calculate the occurrences of numbers within a string in an array of objects containing a specific string each time an object is removed

I am facing an issue where I need to re-number strings based on their type, regardless of their previous number. For example, if I delete Oranges 2 from [Oranges 1, Oranges 2, Oranges 3], it should become [Oranges 1, Oranges 2]. This means the numbers shou ...

"Problem with the Hide/Show Load feature: it's not functioning

After a user submits a form, my script shows 2 divs and hides 1 div. The form's target is an Iframe on the same page. I am looking to delay the Hide/Show events until the Iframe loads. I was successful in accomplishing this with a loading animation, ...

Eliminating fillers dashes from a text

Imagine having a string filled with soft hyphens like the one below: T-h-i-s- -i-s- -a- -t-e-s-t-.- The goal is to eliminate these soft hyphens and get back the clean string: This is a test. Attempting this task in JavaScript, here's how far I&apo ...

Make a request to the local API in a React Native mobile app by sending a GET request

Currently, I am working on a mobile application using React Native and utilizing SQL Server and NodeJS. The API for this project is located in my localhost. Upon running the application on an emulator, I encountered an issue when attempting to make a reque ...

Shader material for border and overlay effects in THREE.js

Can a sphere in THREE.js be given a material shader to achieve a unique visual effect like the one shown here? (I'm specifically interested in replicating the border, glow, and streak on the red sphere.) https://i.sstatic.net/rjfkm.png If this is po ...

My mongoose sort function doesn't seem to be functioning properly. What could be the issue?

Hey there! I've got a simple API up and running on Node.js, using MongoDB as my database with Mongoose for querying. The issue I'm facing is related to sorting data using the mongoose 'sort' method. Instead of behaving as expected, it s ...

Troubleshooting problems with CSS menus and submenus, along with addressing browser pixel issues specific to Web

Find my custom css menu here: Custom CSS Menu On hovering over "about us", the "our clergy" sub-menu appears automatically. I need it to show only when hovering over "our clergy". This screenshot is from Firefox, but webkit browsers like Chrome show a sl ...

Struggling to eliminate excess white space on my site

I am in the process of creating a website using react-bootstrap. However, I have encountered an issue where there is excessive white space on the right side of the website. It seems that the default width of my website has expanded unintentionally. Current ...

Including an Authorization header with a GET request is crucial for accessing protected

I am currently working on developing an Alexa skill utilizing the latest SDK 2.0 but I have encountered a challenge in implementing a basic HTTP GET request. Can someone guide me on how to include an authorization header to the getRemoteData URL request? T ...

jQuery Mishap - Creating an Unspecified Issue

At the moment, my website displays a list of registered users in one column and their email addresses with checkboxes next to them in another column. Users can check the boxes and then click a submit button to generate a list of the selected emails separat ...

Adjusting the devicePixelRatio in Three.js to optimize rendering with CSS3DRenderer

I am looking to display a <div> element (specifically, one from the ECharts library) using the Three.js CSS3DRenderer and combine it with WebGL content. However, I have noticed that when the <div> has fixed width and height, the rendering qua ...