Troubleshooting a Simple JavaScript Game: Mastermind Edition

Currently, I am working on a JavaScript version of the well-known board game "Mastermind".

I have been facing some fundamental issues, mainly with JavaScript arrays and how to reference their values or elements. Despite spending quite a bit of time trying to solve these problems on my own, I have decided to seek help.


Key Points:

  • The game pegs and the game board are created using an HTML table. Each row consists of 4 pegs and a td element containing the results image, implemented in the following manner:

    <td>
        <a href="javascript:void(0)"
           onClick="changePegColor('0','0'); return false"
           onFocus="this.blur()">
            <img src="img/void.png" width=22 height=22  name="peg_0_0">
        </a>
    </td>
    
  • My attempts at declaring default arrays have not been successful so far, as shown in the examples below:

    var pegsAI = ['pegAI_0', 'pegAI_1', 'pegAI_2', 'pegAI_3'];
    var pegsAI = new Array('pegAI_0', 'pegAI_1', 'pegAI_2', 'pegAI_3');
    
  • The process for setting AI's pegs, which the player needs to guess, is functioning correctly without any array-related issues:

    pegsAI[position] = Math.floor((Math.random() * possibleColorsNumber));
    

However, here are the specific issues I am encountering:

  1. Upon clicking the Submit button, there is a check to ensure that every peg in a row has a color assigned. The current implementation is not yielding the desired result and does not throw errors in Chrome Developer Tools:

    ...
    for (var position = 0; position <= 3; position++) {
        if (document["peg_" + currentRow + "_" + position].src === "img/void.png") {
                alert('Finish color picking!');
            return false;
        }
    }
    ...
    
  2. Following this check, there is a function intended to convert the players' pegs into numbers, which should then be saved in an array. However, this conversion process seems to be faulty as the array ends up with 'undefined' values:

    function convertToNumbers() {
        for (var position = 0; position <= 3; position++) {                                         
            if (document["peg_" + currentRow + "_" + position].src === possibleColors[index]) {  
                pegsPlayer[position] = index;                                                       
            }
        }
    }  
    

///added for explanation

A snippet from my score calculation function:

var goodPegPlayer = [false, false, false, false];
var goodPegAI = [false, false, false, false];

function calcSkore() {
convertToNumbers();
alert("array values" + pegsPlayer[0] + "_" + pegsPlayer[1] + "_" + pegsPlayer[2] + "_" + pegsPlayer[3]);
// more code follows here
// Please note the usage of alert() after convertToNumbers()
}

To summarize, the challenges I'm facing primarily revolve around array manipulation and referencing within the context of my Mastermind game project.

Answer ā„–1

Your DOM access needs adjustment. Consider utilizing the id attribute instead of name when selecting your images and make the necessary changes in your JavaScript like so:

for (var index = 0; index <= 3; index++) {
    var id = "peg_" + currentRow + "_" + index;
    if (document.getElementById(id).src === "img/void.png") {
            alert('Finish color picking!');
        return false;
    }
}

Answer ā„–2

In the year 2004, I created my own version of Mastermind.

Although the code is a bit outdated, it still functions well on modern web browsers. Whether it will be useful to you or not, feel free to examine it!

The code is licensed under MIT, granting you the freedom to utilize it (or its components) in any way you see fit!


Additional References

https://i.sstatic.net/WFaAK.png

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

Utilize Launchdarkly in React by incorporating it through a custom function instead of enclosing it within

Currently, I am adhering to the guidelines outlined by launchdarkly. Following the documentation, I utilized the following code snippet: import { asyncWithLDProvider } from 'launchdarkly-react-client-sdk'; (async () => { const LDProvider = a ...

Retrieve all items from the firebase database

I have a query. Can we fetch all items from a particular node using a Firebase cloud function with an HTTP Trigger? Essentially, calling this function would retrieve all objects, similar to a "GET All" operation. My next question is: I am aware of the onW ...

I would like to modify the text color of a disabled input field

I need to adjust the font color of V1, which is a disabled input field. I want to make it darker specifically for Chrome. Any suggestions on how I can achieve this? https://i.sstatic.net/kioAZ.png Here's my HTML code: <mat-form-field appearance= ...

The majority of my next.js website's content being indexed by Google consists of JSON and Javascript files

Iā€™m facing an issue with Google indexing on Next.js (utilizing SSR). The challenge lies in ensuring that .HTML files are effectively indexed for SEO purposes. However, it seems that Googlebot predominantly indexes JSON and JavaScript files. To illustra ...

Is it possible to customize the selected color of the Chip component?

Is there a way to change the clicked color of a Chip component without modifying the theme.js file? I attempted to override the classes with the desired colors, but it still defaults to primary/secondary colors. This information was found in the source co ...

Expand and collapse dynamically while scrolling

// Closing Button for Main Navigation $('button#collapse-button').click(function () { $('nav#main-nav').toggleClass('closed'); }); $(window).on('scroll', function () { if ($(wind ...

Is there a Google Maps feature that displays clusters in a dropdown

Currently, I am utilizing Google Maps to place pins all over the world and implementing markercluster.js to cluster those pins when they are nearby. One feature I am trying to incorporate is the ability to hover over a cluster of pins and have a dropdown d ...

Determine the RGB color values for specific coordinates within Adobe Illustrator

Currently exploring ExtendScript for JavaScript in Adobe Illustrator 2015. Is there a method to retrieve RGB values based on coordinates within the code below? // initializing document var doc = app.activeDocument; // defining x and y coordinates for colo ...

How to reposition the Bootstrap navbar Logo from the left to the center

I am looking to change the ordering of Bootstrap 4 Navbar. Currently, the logo is on the left side, but I want it in the center with menus on both sides. Can someone help me with changing this order? Check out the current Navbar layout below: <nav c ...

Load the React component asynchronously while waiting for the data to be fetched

My ReactJS component looks like this: import React, {useState} from 'react'; import Plot from 'react-plotly.js'; import {utility} from "./utility"; function Chart() { const [use_data, setData] = useState([]); c ...

Creating an App on Shopify

After working on Shopify development for a little bit, I have encountered a specific requirement from my client that is not currently available in the app store. The task involves: Creating two discount tiers based on the total value of the cart (e.g. 1 ...

Change the attribute to read-only upon modification of the dropdown value

I have a dropdown menu with four options. My goal is to make the "number" input field readonly if the user selects either "option3" or "option4" from the dropdown. <select id="dropdown"> <option value="option1">option1</option> ...

The Textfield component in Material UI now automatically sets the default date to the current date when using the "date" type

I am using Material UI's textfield with the type set to "date" and I'm experiencing an issue where the date defaults to the current date instead of mm/dd/yyyy. Is there a way to prevent this behavior and display mm/dd/yyyy when the user loads the ...

Singling out a particular navigation tab

When attempting to link specific table IDs so that the corresponding tab is active when opened (i.e. www.gohome.com/html#profile), I am facing an issue where the active tab remains unchanged. Even after specifically calling out tab IDs, there seems to be n ...

Is there a way to tally ng-required errors specifically for sets of radio buttons?

Currently, I am working on a form in AngularJS that includes groups of radio buttons. One of my goals is to provide users with an error count for the form. However, I have encountered a peculiar issue: After implementing this code to keep track of errors ...

Dynamic fade effect with GSAP on scroll

Currently, I am attempting to implement a fade out animation with GSAP Scroll Trigger. The aim is for the page to first scroll across the X axis of the title before scrolling up and fading out. While I have made some progress, I am facing an issue where th ...

What is the formula for determining the percentage of transparent area on a canvas?

In my Ionic 4 drawing app, I have incorporated an image of the number 1 on the canvas using drawImage and made the background transparent. If users (typically kids) draw outside the number 1 image, the accuracy percentage will decrease. While searching for ...

Learn how to transform an object into an array consisting of multiple objects in TypeScript

The car's details are stored as: var car = {model: 'Rav4', Brand: 'Tayota'} I need to convert this information to an array format like [{model: 'Rav4', Brand: 'Tayota'}] ...

How can I vertically align a photo or image on Facebook?

Can anyone explain how Facebook manages to vertically align its photos without using padding or margins? I've looked into their img tag and its parent, but neither seem to have any spacing properties. Although there is a vertical-align attribute prese ...

Implementing Default Language in Next.js 14 for Static Export without URL Prefix: A Step-by-Step Guide

Currently, I am in the process of developing a website using Next.js 14, with the intention of exporting it as a static site for distribution through a CDN (Cloudflare Pages). The website I am working on requires support for internationalization (i18n) to ...