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

Is it best to remove trailing/leading whitespace from user input before insertion into the database or during the input process?

There's something I've been pondering that pertains to MVC platforms, but could also be relevant to any web-based platform that deals with user input forms. When is the best time and method to eliminate leading/trailing whitespace from user inpu ...

How to dynamically load a file based on the chosen option value in React

Two select textboxes on my page are named Choose City and Choose District. I also have some files related to cities and districts: // cities.js const cities = { "01": { "name": "City 1", "code": "01" }, ...

Tomcat hosting a dynamic duo: Spring Boot and React!

Exploring the world of Spring Boot application development with a React client using Gradle is an exciting journey for me as I navigate through these new technologies. My current progress includes successfully creating a WAR file that encompasses several i ...

Issue with Vue.js: Difficulty sending an array of values to an endpoint

I am currently in the process of learning Vue in order to complete my project, which has a Java Spring backend. The endpoint I am working with expects an object with the following values: LocalDate date; Long buyerId; Long supplierId; List<OrderDetails ...

Experiencing a problem with a loop in iMacros/JS?

I have an iMacros/JS script for Facebook that logs into a FB account from a CSV file, then it has a second loop j which sends 20 friend requests from each account. The issue arises when switching accounts and encountering a popup message requiring phone n ...

What are some solutions for resolving an infinite loop of axios requests?

I am currently in the process of developing a web app for Spotify using its API. I have encountered an issue where the handleClick function in Albums.js is being called repeatedly when trying to make a get request for specific artist album data. Could this ...

Tips for utilizing SSR data fetching in Next.js with Apollo Client

Trying to integrate the apollo-client with Next.js, I aim to fetch data within the getServerSideProps method. Let's consider having 2 components and one page- section.tsx represents component-1 const Section = () => { return ( <div& ...

Best practice for filling an array using a promise

I am completely new to the world of modern JavaScript. My goal is to fill an array with data that I receive from a promise in a helperService. export class PeopleTableComponent implements OnInit { people: Array < Person > = []; constructor( ...

Is it possible to send notifications via email prior to reaching a particular deadline?

I'm trying to figure out a way to notify users one day before dates of events stored in the database. I'm stumped and could really use some help with this. Can someone please assist me? ...

Sending the selected object from a dropdown in React back to its parent component

I have encountered a few issues with my React dropdown component. My main goal is to pass the selected object from the dropdown back to the Parent component. Currently, the dropdown list is functional and I am able to pass {this.state.selectedUser} back to ...

In AngularJS, enhance pagination loading by appending a $resource queried array to the end of another

I'm currently working on implementing a loading feature for my Angular application. The goal is to preload page 3 when a user navigates to page 2. Utilizing $resource, I'm querying the Posts resource using Post.query(). By calling Post.query({pa ...

Has Angular been assimilated into the window object by webpack?

I'm encountering a puzzling issue with webpack that I can't seem to resolve. Here is the link to my webpack.config file: https://github.com/saike/maluvich-browser/blob/master/webpack.config.babel.js In my project, I import angular using ES6 mo ...

Deactivating Touchable Opacity Sounds in React Native

Currently, I am in the process of developing an application, utilizing TouchableOpacity instead of a button. I am looking to disable the auditory feedback that occurs when the TouchableOpacity component is pressed. <TouchableOpacity activeOpacity={1} to ...

Is it possible for me to develop a mobile application using JavaScript, HTML, and CSS and distribute it for sale on the App Store, Google Play Store, and Microsoft Mobile App Store at

I have a keen interest in web standards such as Javascript, HTML, and CSS. My goal is to utilize these languages to develop applications for mobile devices like phones and tablets. I am also considering selling these applications on various platforms inclu ...

Automatically close Bootstrap 4 modal popups

I am using Bootstrap 4 and trying to make my modal automatically close after 3 seconds. I attempted a solution but it seems to not be functioning correctly. The modal itself works fine, but the auto-closing feature is not working as expected. Below is the ...

Disabling Firebase error logging for unsuccessful signInWithEmailAndPassword attempts

My current project involves setting up a login system using Firebase auth in NextJS. Strangely, when I call the login function with incorrect credentials, an error is logged to the console even though my catch statement for handling errors is empty. Is the ...

Utilize the v-for second argument in VueJS 2 to showcase the index and index+1

For a VueJS 2 project, I am tasked with enhancing the display of the first and second elements in an array by making them stand out from the rest. To achieve this, I am utilizing the v-for syntax to iterate over a child component within a parent component. ...

What are the steps to achieve consistent response behavior in POSTMAN that matches that of a web browser?

Below is an example of my code: const express = require('express'); const app = express(); app.get('/', function (req, res) { res.setHeader('Content-Type', 'text/html'); res.write("First \n"); set ...

Currently I am developing a Minimax Algorithm implementation for my reversi game using react.js, however I am encountering a RangeError

I've been implementing a Minimax Algorithm for my reversi game to create a strong AI opponent for players. However, I ran into the following error message: "RangeError: Maximum call stack size exceeded" How can I go about resolving this issue? Here ...

Tips for incorporating a spinner during content loading within AngularJS

When the user clicks on the "Search" button, content will load and the button label will change to "Searching" with a spinner shown while the content is loading. Once the content has loaded (Promise resolved), the button label will revert back to "Search" ...