What could be causing my program to not generate a list of dashes with an "X" in the specified column?

I am working on a game board where I need to replace arrays with new ones that have changes in specific spots.

Here is the initial game board structure:

var gameBoard = [
    ["-","-","-","-","-","-"],
    ["-","-","-","-","-","-"],
    ["-","-","-","-","-","-"],
    ["-","-","-","-","-","-"],
    ["-","-","-","-","-","-"],
    ["-","-","-","-","-","-"]
];

Players can choose their attack spot using prompts:

var playerChoiceRow = prompt("Please select row of attack. (0 through 5)") - "";
var playerChoiceColumn = prompt("Please select column of attack. (0 through 5)") - "";

However, there seems to be an issue with the attack function that only outputs an array of "X"s instead of updating the chosen spot correctly.

function attack(playerChoiceRow, playerChoiceColumn) {
    var array = [];
    for (i = 0; i < gameBoard.length; i++){
        if (array[i] === playerChoiceColumn) {
            array[i] = "X";
        } else {
            array[i] = "-";   
        }
    }
    console.log(array);
}

console.log(gameBoard);
attack();

Answer №1

To solve this problem, consider using the following code snippet:

gameBoard[playerPositionX][playerPositionY] = 'X';

The issue with your current code is that you are not correctly handling the two-dimensional nature of the gameBoard. To fix this, you should incorporate a nested loop structure: one loop for iterating over the rows and another for iterating over the columns.

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

Angular country selection dropdown featuring national flags

Can anyone help me find an Angular Bootstrap dropdown list of countries with flag icons and country codes? For example: United Kingdom - UK Please take a look at this reference image: https://i.sstatic.net/UEfvW.png I want the dropdown to resemble the o ...

Can you provide advice on retrieving the position (row, column) of an element housed within a table?

Currently, I am delving into learning jquery for the purpose of posting input tables. The challenge lies in ensuring that all inputs are posted with their corresponding indexes. Given that input tables are dynamically generated based on user responses, it ...

Traversing through an array within a Fetch request

My JSON object looks like this: [{"user": "poetry2", "following": ["Moderator", "shopaholic3000"]}] I have implemented a Fetch API in this way: fetch (`/profile/${username}/following`) .then(respon ...

Issues with a JavaScript dropdown menu that adapts to different screen sizes

After reading through this informative tutorial on Webdesigntuts+, I have decided to incorporate a responsive JavaScript menu that can handle sub menus and drop downs. An issue arises, however, as the sub menu and drop down functionality does not kick in ...

Unable to resize div element using the change size function

When I click on a div, it should change size, and I want to write the onclick command in an external .js file instead of directly in the html page. Currently in html: <div id="box1" class="kaesten" onclick="changeSize('box1')"> Title 1 &l ...

Avoiding double tapping to zoom on Chrome Android while using the desktop version of a website

Is there a way to disable zooming when double clicking in Google Chrome with the desktop site enabled? I attempted to use <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"> without success. I al ...

In my Laravel Vue JS project, every Put and Delete route method triggers a 302 error

I'm encountering an issue with my Laravel Vue JS application where the PUT and DELETE methods are throwing a 302 error. Here is the response from my localhost: And this is the response from my server: While everything works perfectly on my lo ...

What is the best way to simulate a specific file from an external package using Jest?

Currently, I am developing a project in Typescript that relies on an external package (written in JavaScript) through npm. During testing, I only want to mock one specific JS file from that package. Is there a way to achieve this using Jest? The package. ...

The style property is returned as null by the React Hook useRef

I am currently working on a modal that requires me to access the id property of an HTML element in order to modify its display property. I attempted to achieve this using the useRef Hook, but encountered the following errors. TypeError: Cannot read propert ...

Creating a new array with unique values for each number in Java

I'm working on a program that takes a user input string containing numbers and converts them into an integer. However, my goal is to create a new array where each individual number is a separate value. For example, if the user inputs "15623," I want t ...

Is it normal for the protractor cucumber tests to pass without observing any browser interactions taking place?

Having recently started using protractor cucumber, I have created the following feature. Upon launching protractor protractor.conf.js, the browser opens and immediately closes, displaying that my tests have passed. Is this the expected testing behavior? Sh ...

Netbeans lacks compatibility with JavaScript

Recently, I've been encountering code errors in my .js files while attempting to edit JavaScript using Netbeans 6.9. Even after upgrading to Netbeans 7.01 and enabling the JAVA plugin, the issue persists. I'm unable to create a new JavaScript tem ...

What is the fastest method for slicing a Python list using a NumPy array of indices?

I am dealing with a standard list named a, alongside a set of indices in a NumPy array called b. (Unfortunately, I cannot convert a into a NumPy array.) Is there a more efficient way to achieve the equivalent of "a[b]" without individually extracting ea ...

Create a new 2D array with a specific number of elements

I have a 2-dimensional array of double numbers that is 48 by 48. Currently, I am attempting to create a method that allows the user to specify a particular amount, for example, 7 by 7, and then transfer that data to a new 2-dimensional array. public stati ...

make changes to the current selection in the drop-down menu

Imagine I have a select list with 3 options: <select> <option>1</option> <option>2</option> <option>3</option> </select> My goal is to create a textfield and button that will allow me to upd ...

Ensure that the form button remains disabled until all text input fields have been completed

I've encountered a challenge with a form that contains multiple text inputs. Since these inputs are dynamically generated from server-side code and the number of fields can vary, I'd prefer not to assign individual IDs to each one. My main object ...

Tips for retrieving the value of a tag within a modal popup

I am trying to extract the value from an 'a' tag using the code below. <div class="modal fade show" id="myModal" tabindex="-1" role="dialog" aria- labelledby="myModalLabel" style="display: block;"> <div class="modal-d ...

"The height of the text on the y-axis in jqplot was causing clipping

Within the y-axis, I used text for 2 lines with "/n" but my text is getting clipped. How can I expand the text line height? axesDefaults: { tickRenderer: $.jqplot.CanvasAxisTickRenderer, tickOptions: { angle: 0, ...

What is the most effective method for preserving RichText (WYSIWYG output)?

I am currently using a JavaScript-based rich text editor in my application. Could you suggest the most secure method to store the generated tags? My database is MySQL, and I have concerns about the safety of using mysql_real_escape_string($text);. ...

Error: Looking for guidance on how to handle undefined or null values in an object. Lead me towards the correct solution

I've come across several solutions online for this issue, but being new to this, I haven't been successful in making it work. It may sound trivial, but I could really use some help :) The error: TypeError: Cannot convert undefined or null to ob ...