I'm struggling with my project called "Number TSP" and I can't seem to figure out why it's not working properly

Upon reaching the end of my code, I am encountering an issue where instead of seeing the expected output of "Done!", it displays undefined.

This is the code in question:

const container = document.querySelector(".container")
const table = document.querySelector('table')
const numbers = []
var chosenNum
var chosenLength;

initialize()

function initialize() {
    userChoice()
}

function playGame() {
    var counter = 0
    if (counter === cells.length) {
        console.log('Done!')
    } else {
        const cells = document.querySelectorAll('td')
        chosenNum = drawNum()
        console.log(`The selected number is ${chosenNum}! Tap it!`)
        // cells[idxOfEl].style.backgroundColor = 'yellow'
        const idxOfCell = numbers.indexOf(chosenNum)
        if (cells[idxOfCell].style.backgroundColor === 'red') {
            counter++
        }
        numbers.splice(idxOfCell, 1)
    }
}

function cellClicked(cell) {
    const numInsideCell = parseInt(cell.innerText)
    if (numInsideCell === chosenNum) {
        console.log('Awesome!')
        cell.style.backgroundColor = 'red';
        playGame();
    } else {
        console.log('You tapped the wrong number.')
    }
}


function drawNum() {
    const idxOfEl = Math.floor(Math.random() * (numbers.length))
    return numbers[idxOfEl]
}

// More functions and logic can be added here

Your feedback and suggestions for improvement are highly valuable. Feel free to share any insights you may have!

Answer №1

If you're running into issues where counter === gCells.length is being checked before initializing gCells in the playGame function, here's a solution for you. Make sure to move the declaration of gCells outside of the if statement. This will ensure that everything works correctly.

const gContainer = document.querySelector(".container")
const gTable = document.querySelector('table')
const gNumbers = []
var chosenNum
var chosenLength;


onInit()

function onInit() {
    userChoice()
}

function playGame() {
const gCells = document.querySelectorAll('td')//move this here
    var counter = 0
    if (counter === gCells.length) {
        console.log('Done!')
    } else {
        
        chosenNum = drawNum()
        console.log(`The chosen number is ${chosenNum}! Tap it!`)
        // gCells[idxOfEl].style.backgroundColor = 'yellow'
        const idxOfCell = gNumbers.indexOf(chosenNum)
        if (gCells[idxOfCell].style.backgroundColor === 'red') {
            counter++
        }
        gNumbers.splice(idxOfCell, 1)
    }
}

function cellClicked(cell) {
    const numInsideCell = parseInt(cell.innerText)
    // const timestamp = new Date().toLocaleTimeString();
    if (numInsideCell === chosenNum) {
        console.log('Awesome!')
        cell.style.backgroundColor = 'red';
        playGame();
    } else {
        console.log('You tapped the wrong number.')
    }
}


function drawNum() {
    const idxOfEl = Math.floor(Math.random() * (gNumbers.length))
    return gNumbers[idxOfEl]
}


function addNumbers(numOfCells) {
    var randNum = 0
    var counter = 0
    while (counter < numOfCells) {
        randNum = Math.floor(Math.random() * (50 - 1) + 1)
        if (!gNumbers.includes(randNum)) {
            gNumbers.push(randNum)
            counter++
        } else continue
    }
}

// ------------

function userChoice() {
    var strHTML = ''
    strHTML += `
    <h1 style="text-align:center;margin:30px">Tap the numbers!</h1>
    <p>Please choose how many cells would you like to have:</p>
    <ul>
    <li onclick="displayBoard(this)">16</li>
    <li onclick="displayBoard(this)">25</li>
    <li onclick="displayBoard(this)">36</li>
    </ul>`
    gContainer.innerHTML = strHTML
}

function displayBoard(numOfCells) {
    chosenLength = parseInt(numOfCells.innerText)
    gTable.style.display = 'table'
    var chosenLength = parseInt(numOfCells.innerText)
    addNumbers(chosenLength)
    var counter = 0
    var strHTML = ''
    strHTML += `<tbody>`
    for (var i = 0; i < Math.sqrt(chosenLength); i++) {
        strHTML += `<tr>`
        for (var j = 0; j < Math.sqrt(chosenLength); j++) {
            strHTML += `<td data-location="${i}${j}" onclick="cellClicked(this)">${gNumbers[counter]}</td>`
            counter++
        }
        strHTML += `</tr>`
    }
    strHTML += `</tbody>`
    gTable.innerHTML = strHTML
    playGame()
}
<div class="container"></div>
<table></table>

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

Stop tooltips from appearing on hyperlinks in Internet Explorer

Is there a solution to disabling the pesky tooltips that appear in the bottom left corner of IE when hovering over links? Alternatively, is there a method to customize the text that appears instead of the default tooltip when hovering over a link (I attem ...

What is the best way to implement a day timer feature using JavaScript?

I am looking for a timer that can automatically change the rows in an HTML table every day. For example, if it is Day 11, 12, or 25 and the month is February at 8 AM, the rows should display "Hello!". function time() { var xdate = new Date(); var ...

The scale configuration for scale: x is not valid for creating a time scale chart using chart.js

I am currently utilizing VueJS and attempting to integrate a time scale chart using Chart.js. However, I encountered the following error: Invalid scale configuration for scale: x Below is my configuration : First, I have a component named Chart.vue with ...

Having Trouble Importing a Dependency in TypeScript

My experience with using node js and typescript is limited. I attempted to include the Paytm dependency by executing the following code: npm install paytmchecksum or by inserting the following code in package.json "dependencies": { ... & ...

Tips on personalizing the FirebaseUI- Web theme

Can someone help me find a way to customize the logo and colors in this code snippet? I've only come across solutions for Android so far. if (process.browser) { const firebaseui = require('firebaseui') console.log(firebaseui) ...

Retrieve HTML content from Vuetify components without displaying it on the webpage

I have a project where I need to retrieve the HTML code from various Vuetify components. Instead of just as a HTML string, I actually need it as a DOM element that can be easily added to the body. This is necessary for me to be able to utilize these compon ...

I am struggling to grasp the concept of how the g flag in JavaScript's string.match(regexp) method operates

In the JavaScript book "The Good Parts", there is an explanation of the method string.match(regexp): The match method works by comparing a string with a regular expression. Its behavior varies based on whether or not the g flag is present. Without the g ...

What is preventing the listener from activating?

I came across some HTML code that looks like this: <form id="robokassa" action="//test.robokassa.ru/Index.aspx" method="post"> <input type="text" id="OutSum" name="OutSum" value="" placeholder="Сумма пополнения"> ...

Dealing with Unwanted Keys When Parsing JSON Objects

Struggling with parsing a list of Objects, for example: After running the code JSON.parse("[{},{},{},{},{}]"); The result is as follows: 0: Object 1: Object 2: Object 3: Object 4: Object 5: Object Expecting an array of 5 objects like this: [Object,Ob ...

When using NodeJS and MongoDB together, a POST request may receive a 404 error code

Despite having all the routes set up correctly, I'm encountering a 404 error when trying to send a POST request. I've searched through numerous similar questions but haven't come across a solution that addresses my specific issue. Below is ...

Utilizing ng For in a personalized directive to fill a selection menu

I encountered an issue while trying to populate a selected dropdown using ngRepeat inside a custom directive. I came across this example that seemed similar to what I wanted to achieve here. Although it worked for the example, it didn't work for me. ...

"I encountered an error while sorting lists in Vue 3 - the function this.lists.sort is not

Creating a Vue 3 front-end template: <template> <div class="container"> <router-link to="/user/create" class="btn btn-success mt-5 mb-5">Add New</router-link> <table class=" ...

Displaying data-table with only the values that are considered true

Right now, I am utilizing the AgReact table to exhibit data fetched from my endpoints. The data-table is functioning properly, however, it seems to be unable to display false values received from the endpoints on the table. Below are the snippets of my cod ...

The Battle: AJAX FormData vs encodeURI

When utilizing jQuery's encodeURI(), the data transmitted through AJAX appears in this format: key1=true & key2=34 & ... In order to send an image via AJAX, I employ the FormData() method, resulting in the AJAX data without an image looking ...

How to show or hide a textbox in JavaScript?

Within my user control, there is a panel with two controls: ddlType, a drop-down list, and txtOthers, a text box. Initially, txtOthers is set to be invisible. The goal is for txtOthers to become visible when the user selects an option in ddlType that corr ...

Attempting to align my navigation bar beside my logo

I've been attempting to position my navigation menu next to my logo, but it keeps displaying below it. Although my coding skills are not top-notch, I am aiming to have the nav element positioned alongside the logo, as shown in my design: HTML: <b ...

What strategies can be used to scale up a website's images in proportion to their page views or traffic?

The situation: On my simple HTML website, I have a group of images placed side by side. Each image is connected to a specific article, and when you hover over the image, a detailed description of the linked article pops up in the center of the page. The o ...

Adjusting the height of a Jquery Fancybox to allow for scrolling down

I've implemented fancybox to display certain pages on my website, but I'm struggling with setting a fixed height and enabling scrolling for content that exceeds this height within the fancybox. Here are the parameters I have used: <script> ...

Struggling to display the sorted array items on the screen?

Within the realm of my jsfiddle experiment, my aim is to organize items based on price from highest to lowest by utilizing the following function: function mySortingFunction() { var elements = [].slice.call(document.getElementsByClassName("price")); e ...

Passing a Typescript object as a parameter in a function call

modifications: { babelSetup?: TransformationModifier<babel.Configuration>, } = {} While examining some code in a React project, I came across the above snippet that is passed as an argument to a function. As far as I can tell, the modifications p ...