prompting the JavaScript hangman game to identify the letters in the "selected word"

Currently, I am on a mission to teach myself Javascript and have taken on the challenge of creating a simple hangman game. This type of project is commonly used in interviews or tests, so it seemed like a great opportunity for practice. My approach involves using Math.random to select a word from a list of options, then utilizing the prompt feature to guess the letters of the chosen word. However, I have hit a roadblock as I am struggling to get the prompt to recognize my input correctly. Any assistance you can provide would be greatly appreciated.


var secretWords = ["batman", "Donkey kong", "ninja", "programming"];
var chosenWord = secretWords[Math.floor(Math.random() * secretWords.length)];
var guesses = 8;
var letters = chosenWord.length
var guess = prompt("GUESS A LETTER");

alert(chosenWord);

for (var i = 0; i <= letters; i++) {
letters[i] = chosenWord.substring(i, i++)
}
if (guess = i) {
alert("nice")
} else {
alert("Wrong");
}

Answer №1

Your loop variable, denoted as i, represents the position in the chosen word being compared with the guessed letter. Once the loop finishes iterating through all the letters, i will hold the final value of the last letter index. Instead of comparing against this final value, it is essential to continuously compare throughout the looping process.

var secretWords = ["apple", "banana", "orange", "kiwi"];
var chosenWord = secretWords[Math.floor(Math.random()*secretWords.length)];
var guesses = 6;
var letters = chosenWord.length;
var guess = prompt("GUESS A LETTER");

var found = false;
for (var i = 0; i < letters; i++){
    if (guess == chosenWord.substring(i, i + 1))
        found = true;
}
if (found) {
    alert("Correct!");
}
else {
    alert("Incorrect");
}

Answer №2

Presently, you are iterating from 0 to the length of the chosen word inclusive. It seems like you are attempting to verify if the provided letter is in the selected word, but unfortunately, the logic is incorrect.

To determine if a string contains a letter or part of a word, you can utilize the String.includes() method. This method is available for every string and allows you to check if a specific substring is present within your string, returning true or false accordingly. For instance:

var example = 'hello';
example.includes('h'); // true
example.includes('i'); // false

Keep in mind that JavaScript is case-sensitive. To ensure that your game accommodates user input without ambiguity regarding uppercase or lowercase characters, make sure all your secretWords are either in lowercase or uppercase. Then, when receiving user input, convert it to the desired case using the String.toUpperCase() and String.toLowerCase() methods.

var secretWords = ["batman", "donkey kong", "ninja", "programming"];
var chosenWord = secretWords[Math.floor(Math.random()*secretWords.length)];
var guesses = 8;
var letters = chosenWord.length

alert(chosenWord);

var guess = prompt("GUESS A LETTER");
var guessLowerCase = guess.toLowerCase();
var isGuessedLetterInWord = chosenWord.includes(guessLowerCase);

if (isGuessedLetterInWord) {
  alert('nice');
} else {
  alert('wrong');
}

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

How can one easily retrieve the callback function arguments from outside the function?

Here is a snippet of my code: var jenkins = require('jenkins')('http://192.168.1.5:8080'); var job_name = undefined; jenkins.job.list(function doneGetting(err, list) { if (err) throw err; job_name = list[0].name; }); jenkins. ...

Extracting Querystring Value in C#

When using the code below to set the iframe src with JavaScript, everything works as expected. However, in the C# code behind, I am receiving the query string in a format like this: id=Y&amp%3bcust_id=100&amp%3. Is there a way to simplify this? v ...

Create beautiful PDF documents using the KNP Snappy Bundle, seamlessly converting dynamically modified Twig templates

Currently, I am attempting to create a PDF from a tweaked Twig on the client side. My approach involves sending the modified HTML document to the server via AJAX. However, this method is proving ineffective as the server is returning a binary document that ...

The data in AngularJS is not being successfully incorporated into the service

Utilizing angularjs and ajax, I am attempting to retrieve data from a webservice and pass it to the controller. To accomplish this, I am using a holder (a factory method or service). The setup works fine without the webservice, but when trying to fetch dat ...

Learn how to successfully upload an image using React and Node without having to rely on

I am currently exploring file uploading in react/node. Instead of passing files directly into the API request, I am passing them within the body of the request. Here is a snippet of my react code: import React, { Component } from 'react'; import ...

Having issues with Facebook's login API for JavaScript?

Apologies for the improper formatting. I am encountering errors in my JavaScript compiler while working with the Facebook Login API... Error: Invalid App Id - Must be a number or numeric string representing the application id." all.js:53 "FB.getL ...

The combination of Array.pop and Array.indexOf is not functioning as expected

I'm having an issue with using Array.pop(Array.indexOf(value)). It seems to always delete the last element in the index, even if the value of that index is not what I intended. Can someone provide some guidance on how to resolve this? CheckBoxHandle ...

Looking to add some random circle markers to your SVG map?

I currently have a single marker displayed on an SVG Map. My goal is to scatter markers randomly across the map within the path itself. I would greatly appreciate some assistance in implementing this feature. svg { border: 1px solid; overflow: visib ...

Automated scrolling within a div when an li element overflows

Looking to implement automatic scrolling in a div. I have a list of elements within a fixed height div, and now I want the div to scroll automatically when I press the down key after highlighting the 3rd li element (i.e Compt0005). Can anyone help me solve ...

default choice in dropdown menus

I need to populate my option fields with data retrieved from a database. I encountered an error in the console: Error: [$compile:ctreq] Controller 'select', required by directive 'ngOptions', can't be found! I am confident that t ...

Display PDF in Forge Viewer using PDF Extension - warning generated by pdf.worker.js

Whenever we attempt to display a PDF file using our own API, the pdf.worker.js generates a warning message and the PDF always appears completely white. https://i.stack.imgur.com/IqGML.png All I can see is this (it's a wide PDF that renders fine in t ...

Navigating with Anchors, Styling and jQuery

Firstly: Apologies in advance for any language errors as English is not my native tongue. :) The Scenario Here's the deal: I'm attempting to create a single button that, when clicked by the user, automatically scrolls down to the next DIV. Each ...

Tailored design - Personalize interlocking elements

I am currently working on a custom theme and I am trying to adjust the font size of Menu items. In order to achieve this, I have identified the following elements in the tree: ul (MuiMenu-list) MuiListItem-root MuiListItemText-root If I want to modify th ...

Issue with jQuery's outerHeight() function persisting despite attempting to fix it with jQuery(window).load()

Once the content is loaded using AJAX, I need to retrieve the outerHeight of the loaded elements. Ajaxload file: $('#workshop').submit(function(event){ $.ajax({ url: URL, type: 'POST', data: $(' ...

What are some ways to implement Node.js within Netsuite?

Recently, I've been exploring Netsuite and I'm curious to learn about the feasibility of integrating Node.js or npm modules into a SuiteScript or Suitelet. Is it possible? I have a specific aim in mind - to utilize some npm modules within Netsui ...

Tips for creating row grouping in React JS

Currently, I am working on a React application and I would like to incorporate grouping similar to what is shown in the image. I have looked into row grouping but it doesn't seem to be exactly what I need. How can I go about implementing this feature? ...

Unbinding or undoing an 'onclick' event when another 'onclick' event is triggered

I am facing an issue where clicking on elements with 'onclick' functions works as expected, but when I click on a different element with another 'onclick' function, the first one remains active. What I actually want is for the previous ...

What are the steps to ensure that this iframe adjusts perfectly to the page in terms of both vertical and horizontal dimensions

I have a sandbox from Material UI that you can view at this link: https://codesandbox.io/s/material-demo-forked-c8e39?file=/demo.js Upon loading the page, an iframe displays some HTML content. Although the width fits perfectly, there are two vertical scro ...

Custom div element obstructs information window on map due to lack of auto panning feature

I created a unique div that is absolutely positioned on a Google Map. You can view the image below to see it. My issue is that the info window is being covered by this custom div element, as demonstrated in the picture. https://i.stack.imgur.com/1TgyQ.jpg ...

jQuery fails to locate class following AJAX reply

In my application, there is a cart feature where users can remove items from their cart, triggering a refresh of the contents using AJAX. However, I noticed that after removing an item from the cart, the response switches from asynchronous to synchronous m ...