Tic Tac Toe is not functioning properly

Hey there! Can someone please help me figure out what's going on? I'm trying to create a Tic Tac Toe game, but instead of using "O" and "X" to mark the fields, I want to use different colors. Specifically, one player should be able to mark with blue and the other with red. The idea is that each time a player clicks on a field, the color should switch according to the player. Here's an example:

  • Player 1: click --> blue
  • Player 2: click --> red
  • Player 1: click --> blue
  • ...

But unfortunately, it's not working as expected!!! Any assistance or guidance on this issue would be greatly appreciated.

Source Code:

<html>
<head>
    <meta charset="utf-8" />
    <title>Tic Tac Toe |</title>
    <link rel="stylesheet" type="text/css" href="stylesheetTicTacToe.css">
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

        <table>
            <tr>
                <td><div id="field_7" class="gameBoard"></div></td>
                <td><div id="field_8" class="gameBoard"></div></td>
                <td><div id="field_9" class="gameBoard"></div></td>
            </tr>
            <tr>
                <td><div id="field_4" class="gameBoard"></div></td>
                <td><div id="field_5" class="gameBoard"></div></td>
                <td><div is="field_6" class="gameBoard"></div></td>
            </tr>
            <tr>
                <td><div id="field_1" class="gameBoard"></div></td>
                <td><div id="field_2" class="gameBoard"></div></td>
                <td><div id="field_3" class="gameBoard"></div></td>
            </tr>
        </table>

        <script type="text/javascript">

        var count = 1;

        $(document).click(function() {
            for(i = 0; i < 10;) {
                if(count % 2 == 1) {
                    $('.gameBoard').click(function() {
                        $(this).css("background-color", "pink");
                    })
                    count++;
                    i++;
                } else {
                    $('.gameBoard').click(function() {
                        $(this).css("background-color", "blue");
                    })
                    count++;
                    i++;
                }
            }
        })
        </script>

</body>
</html>

Answer №1

Utilize the power of event binding to streamline your code. By accessing event.target, you can easily determine which cell was clicked without having to loop through all potential cells. Here's an example:

var playCount = 0;

$(document).click(function(event) {
    var cell = $(event.target).closest('.gameBoard');
    if (!cell.hasClass("played")) {
        if (playCount % 2 == 1) {
            cell
                .css("background-color", "pink")
                .addClass("played");
            playCount++;
        } else {
            cell
                .css("background-color", "blue")
                .addClass("played");
            playCount++;
        }
    }
});

JSFiddle: http://jsfiddle.net/4hgr0wke/

You can also bind more selectively to the cells to ensure that a click event only applies when a cell is clicked. Here's an alternative approach:

var playCount = 0;

$(document).on('click', '.gameBoard', function(event) {
    var cell = $(event.target).closest('.gameBoard');
    if (!cell.hasClass("played")) {
        if (playCount % 2 == 1) {
            cell
                .css("background-color", "pink")
                .addClass("played");
            playCount++;
        } else {
            cell
                .css("background-color", "blue")
                .addClass("played");
            playCount++;
        }
    }
})

JSFiddle: http://jsfiddle.net/4hgr0wke/1/

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

Error encountered in Next.js when defining columns for a MUI data grid

Currently, I am integrating MUI Data Grid into a Next.js app under development. While attempting to define a more intricate column structure, I encountered an error: { field: 'home_address', valueGetter: (value, row) => { retur ...

I'm curious as to why window.opener is null in a popup when utilizing Google OAuth, and what is the most effective way to transfer the access token to the parent window

In my React application, I am working with Google OAuth and implementing it through a popup. The setup involves using Passport with my own custom backend. I start by supplying the initial URL to the popup window, which is the entry point on my backend that ...

What is the best way to store query responses in global.arrays without overwriting the existing values stored within the array elements of global.arrays?

QUESTION: I am struggling to efficiently assign results of MongoDB queries to global arrays. I attempted to store references to the global arrays in an array so that I could easily assign query results to all of them using a for loop. However, this appro ...

Uniform selection frame width across nested list elements

I want to ensure that the width of the selection frame for all nested ul li elements is consistent, just like in this example. When hovering over an element (making the entire line clickable), I don't want any space on the left. Currently, I am using ...

Including material-ui/core/Table produces a data error before it has even been connected

My Initial Redux Saga Setup In my Redux Saga code, I have a generator function that fetches data from a mock API: function* fetchPickingScans({orderReference}){ try{ const response = yield call( scanningMockApi.getPickingScans, orderReference ...

Retrieving a result from the reduce function in Angular

Is there a way to use the reduce function in order to return a list of objects? I am currently only able to return a single object with keys as project names and values as hours: { Name1: 9, Name2: 10, Name3: 30, } What changes can I make to my code to ac ...

Creating a jQuery selector that is not case-sensitive

I have a query where I want to ensure it is case-insensitive: var matches = $(this).find('div > span > div#id_to_find[attributeName ^= "filter"]'); if (matches.length > 0) { } Is there a way to make the selector ^= case-insensitive? Pe ...

The issue arises when HTML tables with unique IDs are all displaying the same value from an AJAX callback

This situation has been incredibly frustrating for me!! Let me explain what's going on - I have a callback data coming from my AJAX post method that needs to be passed to seven different HTML tables. Although I successfully received the data from the ...

Having trouble implementing table row selection with semantic-ui table

I am currently in the process of adopting Semantic-UI, but I am encountering some issues. Specifically, I am struggling to make row selection work in a table. Below is the sample HTML I am using from Semantic-UI: <table class="ui selectable celled tab ...

Guide to dynamically setting the title and background color of the navigation bar in React Navigation 5

In my current project, I am utilizing React Navigation Bar version 5 and have successfully set the title in App.js. However, I now need to change this title dynamically when the screen is rendered. I attempted to use this.props.navigation.navigate('Ex ...

Error: Unable to submit data as the function this.submitData is not recognized

Having trouble calling an async function in the mounted() lifecycle hook of Vue.js? Keep getting the error message: Uncaught TypeError: this.submitData is not a function. Here's the code snippet in question: <template> <section class=&quo ...

Please move the scroll down and then back up after an Ajax request because the scroll position has been reached

When I click a button, I am loading results using ajax. Every time I click, the page scrolls to a specific position with the following code: success: function(data) { $("#test").html(data).fadeIn("slow&quo ...

Tips for positioning the popup ul in relation to its parent li

How can the pop-up ul be positioned in the center of the parent li using CSS? * { margin: 0; padding: 0; } #track-nav { margin-left: 50px; margin-top: 50px; float: left; width: 100%; list-style: none; font-weight: bold; margin-bottom: ...

jquery has a strange behavior where the dialog window will cover up the scrollbar when the main

Currently, I am utilizing jQuery dialog to display a dialog window. I have managed to position it at the bottom left corner as desired. However, when the main window contains a scrollbar, the dialog ends up overlapping with the scrollbar instead of alignin ...

Retrieve the HTML element by providing its specific index within the DOM structure of the document

I am working with the HTML source of a document stored as a string and have the index i which indicates where an element starts within this string. I am looking to create a function called getElementByIndex(i) that will return the appropriate JavaScript D ...

Anticipating the resolution of one promise before tackling the next in Angular.js

Is it possible in Angular.js to ensure that a given promise is resolved before another dependent promise? Consider the following code snippet: User.getAllUsers().then(function(users) { $scope.users = users; for (var i = 0; i < users.length; i+ ...

Discover the pixel width of a Bootstrap grid row or container using JavaScript

How can I calculate the width of a Bootstrap grid row or container in pixels using JavaScript? I am working with Aurelia for my JavaScript project, but I'm open to solutions in standard JS (no jQuery, please). Looking at the Bootstrap documentation, ...

Cassandra encountered a TypeError stating that the "value" argument is exceeding the bounds

I keep encountering the error message below. Any thoughts on what might be causing it? TypeError: "value" argument is out of bounds at checkInt (buffer.js:1041:11) at Buffer.writeInt32BE (buffer.js:1244:5) at Encoder.encodeInt (/ ...

The data retrieved by jQuery AJAX is empty when accessed outside of the success handler

Here is a code snippet to consider: let source = null; fetch('https://example.com/data') .then(response => response.json()) .then(data => { source = data; console.log(source); }); console.log(source) When the fetch request ...

How can I customize the variables in Webpack for Sass and Foundation?

Currently, I am in the process of using webpack to manage all of my project assets. In my app.js file, I am loading and concatenating my assets with the help of ExtractTextPlugin: import 'foundation-sites/scss/normalize.scss'; import 'foun ...