How to make sure user input is a valid string in js - javascript

I am very new to JS,
how do I make sure that the user input is a valid string?
If the string is inside of the array, the game should continue.
if the string is outside of the array, the game should ask user to input their guess again.
var color = ["AliceBlue","Black","FireBrick","GreenYellow","LightBlue","Ivory","MediumBlue","Indigo","SpringGreen","Moccasin"];
var target;
var guess_input_text;
var guess_input;
var finished = false;
var guesses = 0;
var rightAnswer;
var i = 0;
function do_game() {
var random_number = Math.random()* color.length;
var random_number_interger = Math.floor(random_number);
target = random_number_interger + 1;
rightAnswer = color[target];
while(!finished) {
guess_input_text = prompt("I am thinking of one of these colors:\n\n" + color.sort()+ "\n\n The right answer is\n" + rightAnswer);
guess_input = guess_input_text;
guesses +=1;
finished = check_guess();
}
}
function check_guess() {
if(guess_input < rightAnswer){
console.log("Hint: your color is alphabetically lower than mine")
return false;
}
else if( guess_input > rightAnswer) {
console.log("Hint: your color is alphabetically higher than mine ")
return false;
}
else (guess_input == rightAnswer)
{
console.log("Congrats!!!")
return true;
}
)
}

You can use indexOf to check the position of guess_input in the color array. It will return -1 if it is not present.
So:
function check_guess() {
if (color.indexOf(guess_input) < 0) {
console.log("Not a valid colour, try again.");
return false;
}
return true;
}

You can use Array.prototype.find function with ES6 arrow functions to make it even snappier.
if(color.findIndex(e => e === guess_input) === -1){
alert("Please guess again!);
}
The above code alerts the user to guess again if the guess_input isn't found in the array.

Related

JS code guessing game color NOT WORKING

I am a neophyte JS, I'm making a game where the user has to guess a randomly generated color.
I noticed that the code I tried to write results in errors, that is, when I go to enter a color in the prompt, even if it is wrong always says the right thing. I have something wrong in check_guess function where I wrote the conditions.
Another mistake I detected when the game ends, should be out in the background the color that guessed it, nor should you.
Can you help me figure out where I'm wrong?
while (!finished) {
guess_input_text = prompt("I am thinking of one of these colors:\n\n" +
colors_message + "\n\n What is the color am I thinking of?");
guess_input = guess_input_text.toLowerCase();
guesses += 1;
finished = check_guess();
}
}
function check_guess() {
if (guess_input == -1) {
alert("Sorry, I don't recognize your color. \n\n Please try again.");
return false;
} else if (guess_input > target) {
alert("Sorry, your guess is not correct!\n\nHint: Your color is alphabetically higher than mine.\n\nPlease try again.");
return false;
} else if (guess_input < target) {
alert("Sorry, your guess is not correct!\n\nHint: Your color is alphabetically lower than mine.\n\nPlease try again.");
return false;
} else {
alert("Congratulations! You have guessed the color!\n\nIt took you " + guesses + " guesses to finish the game!\n\nYou can see the colour in the background.");
var myBody = document.getElementsByTagName("body")[0];
myBody.style.background = target;
return true;
}
}
</script>
Referring to your code revisions I got the required data. There were few glitches that were found like:
You were checking guess_input with target, where guess_input holds a string value of the user input and target holds an integer value of the correct answer. None of the conditions will ever be satisfied in this case, and thus the last else part will be executed always. That is, alert("Congratulations! You ha..);
myBody.style.background = target; will set the background
property to an integer (index of answer in colors array). You need
to set it like myBody.style.background = colors[target];
Below is the working code:
var colors = ["antiquewhite", "blueviolet", "crimson", "deepskyblue", "forestgreen", "gold", "lawngreen", "magenta", "palegreen", "skyblue"];
var colors_message = colors.join(", ");
var target;
var guess_input_text;
var guess_input;
var finished = false;
var guesses = 0;
var ask_again = false;
function do_game() {
var target_index = Math.random() * colors.length;
var target_index_integer = Math.floor(target_index);
target = target_index_integer;
var answer = String(colors[target]).toLowerCase();
//Alert correct answer for testing purposes
alert("The correct answer is: " + answer);
guess_input_text = prompt("I am thinking of one of these colors:\n\n" + colors_message + "\n\n What is the color am I thinking of?");
while (!finished) {
if(ask_again){
guess_input_text = prompt("What is the color I was thinking of?");
}
guess_input = guess_input_text.toLowerCase();
guesses += 1;
finished = check_guess(colors.indexOf(guess_input));
}
}
function check_guess(guess_index) {
ask_again = true;
if (guess_index == -1) {
alert("Sorry, I don't recognize your color. \n\n Please try again.");
return false;
} else if (guess_index > target) {
alert("Sorry, your guess is not correct!\n\nHint: Your color is alphabetically higher than mine.\n\nPlease try again.");
return false;
} else if (guess_index < target) {
alert("Sorry, your guess is not correct!\n\nHint: Your color is alphabetically lower than mine.\n\nPlease try again.");
return false;
} else {
ask_again = true;
alert("Congratulations! You have guessed the color!\n\nIt took you " + guesses + " guesses to finish the game!\n\nYou can see the colour in the background.");
var myBody = document.getElementsByTagName("body")[0];
myBody.style.background = colors[target];
return true;
}
}
<body onload="do_game()"></body>

code stops looping

My code is not working properly. It is not continuing the loop. It is just showing that your value is low or high and stopping it there. Why doesn't it keep looping?
var target;
var count = 0;
var play;
var game;
function do_this() {
var choose = (Math.floor(Math.random() * 100));
target = choose + 1;
while (true) {
play = prompt("I am thinking of a no. between 1 and 100\n\n" + "enter the no.");
game = parseInt(play);
count = count + 1;
if (isNaN(game)) {
alert("Please enter integer value");
return false;
}
if ((game < 1) || (game > 100)) {
alert("Please enter the value between 1 and 100");
return false;
}
if (game < choose) {
alert("enter higher value");
return false;
}
if (game > choose) {
alert("enter lower value");
return false;
}
alert("You are correct\n\n" + "you took" + count + "to guess the game");
return true;
}
}
do_this()
You are using return false; when the value is higher or lower. Replace that with continue;

cancel button on javascript dialog to stop a loop

Greeting. When I open the following in Internet Explorer 11, the game would not stop when I hit the cancel button. How I can press the cancel button and the game stops. The current behavior is it just keep looping even with cancel ??
var target;
var guess_input_text;
var guess_input;
var finished = false;
var guesses = 0;
function do_game() {
var random_number = Math.random() * 100;
var random_number_integer = Math.floor(random_number);
target = random_number_integer;
while (!finished) {
guess_input_text = prompt("I am thinking of a number "+
"in the range 1 to 100.\n\n"+
"What is the number?");
guess_input = parseInt(guess_input_text);
guesses += 1;
finished = check_guess();
}
}
function check_guess() {
if (isNaN(guess_input)) {
alert("You have not entered a number.\n\n" +
"Please enter a number in the range 1 to 100.");
return false;
}
if ((guess_input < 1) || (guess_input > 100)) {
alert("Please enter an integer number in the range 1 to 100.");
return false;
}
if (guess_input > target) {
alert("Your number is too large!");
return false;
}
if (guess_input < target) {
alert("Your number is too small!");
return false;
}
alert("You got it! The number was " + target +
".\n\nIt took you " + guesses +
" guesses to get the number!");
return true;
}
When you press the Cancel button on prompt's prompt, it returns null. So
if (guess_input_text === null) {
break;
}
...will exit the loop.
Note that on quite old browsers, it would return "" rather than null. But anything vaguely modern (IE9+) should be fine.

Any way to restrict JQuery input to only unique characters that haven't been input previously

I have a simple JQuery/JS Hangman game and I've spent alot of time making it work and I've run into one issue that messes up my logic and running of the game - when the player enters repeated chars (either right or wrong).
The way I've made the game work, starting with empty arrays I'm pushing into, I thought that I could create a function to only push unique chars into the array function
unique(array) {
var result = [];
$.each(array, function(i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
return result;
}
var uniqueRightGuesses = unique(rightGuesses);
var uniqueWrongGuesses = unique(wrongGuesses);
But this doesn't work because w/the inner workings of my game, the repeated input chars are still getting displayed & messing up the way winning & loosing is input (even though I'm calculating winning w/the sum of an additional array I've created to take care of a letter that repeats multiple times in a word). I've tried alot of various things at various parts of the game/in various functions and I've figured out that the easiest way to take care of this issue would be to somehow prevent the player from inputing a char if they've already input in the course of the game, in this function:
$(".form-control").keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == 13) {
var space = $(this).val().toLowerCase();
play(space);
$(this).val('');
endGame();
return false;
}
});
I've searched online for a way to do this, I've found jQuery.unique() but I don't think that it'd work here as it's only on DOM objects in an array (& I just want the input to not register/not be allowed if the player has already entered that letter, if it's right or wrong guess- if I take care of this problem at this spot in the game, I won't have to mess w/my arrays or the variables I'm displaying but I don't know how to simply do this.
If anyone has any suggestions or knows if this is even possible, I'd really appreciate it- I've found alot online about restricting special chars & numbers in this way but nothing about ones that have already been entered & I don't know if this is even possible (this is the first time I've ever even used .keypress() so I'm sort of new to it. Any suggestions would be much appreciated. Thanks!
Here's my entire game code:
var wordBank = ["modernism", "situationalist", "sartre", "camus", "hegel", "lacan", "barthes", "baudrillard", "foucault", "debord", "baudrillard"];
var word = [];
var answer = [];
var wrongGuesses = [];
var rightGuesses = [];
var right = [];
var images = [gallows, head, body, armL, handL, armR, handR, legL, footL, legR, footR];
var y = 0;
var i = 1;
$(document).ready(function() {
function randomWord() {
var random = Math.floor(Math.random() * wordBank.length);
var toString = wordBank[random];
console.log(toString);
word = toString.split("");
console.log(word);
}
randomWord();
function wordSpaces() {
for (var i = 0; i < word.length; i++) {
$(".word-spaces > tbody > tr").append('<td data-idx=i>' + word[i] + '</td>')
}
}
wordSpaces();
function play(space) {
//indexOf()==inArray()
var rightCount = 0;
var lIndex = jQuery.inArray(space, word);
console.log(lIndex);
if (lIndex == -1) {
wrongGuesses.push(space);
var wrong = wrongGuesses.length;
console.log('wrong ' + wrong);
$('.wrongLetters tbody tr td:nth-of-type(' + wrong + ')').text(space);
// $(this).css("background-color", "#ff4500").fadeIn(300).delay(800).fadeOut(300);
$(images[i - 1]).hide();
$(images[i]).show();
i++;
$("html").css("background-color", "#ff4500").fadeIn(300).delay(300).fadeOut(300).fadeIn(100);
console.log(word);
} else {
var totalRight = 0;
console.log(word + "word");
console.log(space + "space");
function getInstances(word, space) {
var indexes = [],
w;
for (w = 0; w < word.length; w++)
if (word[w] === space)
indexes.push(w);
return indexes;
}
console.log(word + "word");
console.log(space + "space");
var indexes = getInstances(word, space);
console.log("indexes", indexes);
indexes.forEach(function(index) {
// answer[index] = space;
rightCount++
});
console.log(rightCount + "rightcount");
console.log("answer", answer);
// rightGuesses.push(space);
console.log(rightGuesses);
// var right = rightGuesses.length;
indexes.forEach(function(index) {
$(".word-spaces tbody tr td:nth-of-type(" + (index + 1) + ")").css('color', 'black');
});
rightGuesses.push(space);
right.push(rightCount);
console.log(right + "right");
// rightGuesses.push(space);
// totalRight = totalRight + rightCount;
// totalRight++;
// console.log(totalRight + 'totalRight');
}
}
console.log(right + "right");
$(".form-control").keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == 13) {
var space = $(this).val().toLowerCase();
play(space);
$(this).val('');
endGame();
return false;
}
});
function endGame() {
var sumRight = right.reduce(add, 0);
function add(a, b) {
return a + b;
}
if (sumRight == word.length) {
$(images[i]).hide();
$("#victory").show();
$("body").css("background-color", "#8AFBFF");
$(".form-control").prop('disabled', true);
$("body").animate({
backgroundColor: "#0C0D86"
}, 2000);
$("body").animate({
backgroundColor: "transparent"
}, 2000);
} else if (wrongGuesses.length >= 10) {
$("body").css("background-color", "#ff4500");
$(".form-control").prop('disabled', true);
$("body").animate({
backgroundColor: "#000000"
}, 2000);
$("body").animate({
backgroundColor: "transparent"
}, 2000);
}
}
});
Use Array.indexOf(). No need for jQuery.
Do a check to see if the key pressed is contained in the wrongGuess or rightGuess array and if it is alert the user.
$(".form-control").keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == 13) {
var space = $(this).val().toLowerCase();
if (!(wrongGuess.indexOf(space) > -1 || rightGuess.indexOf(space) > -1)) {
play(space);
$(this).val('');
endGame();
return false;
}
else
window.alert("You already guessed this letter.");
}
});

How do I get a toggle button to toggle an array back and forth from descending to ascending?

I am using bubbleSort, and I can get the array to toggle from its original order to descending, but I am having trouble getting it to go from descending back to ascending. Should I just copy the bubbleSort code and flip the greater than/less than signs? Any help is appreciated!
var myStuff = [];
function myfunctionA() {
var enteredvalue = document.getElementById("numbers").value;
// alert(typeof Number(document.getElementById('numbers').value));
if (enteredvalue == "") {
alert("Input is not a number");
} else if (isNaN(enteredvalue)) {
alert('You need to enter a valid number!');
}
var elementExists = false;
var x = document.getElementById('numbers').value;
for (var i = 0; i < myStuff.length; i++) {
if (myStuff[i] == Number(x)) {
elementExists = true;
}
}
if(elementExists != true) {
myStuff.push(Number(enteredvalue));
alert('Thank You for entering a valid number.');
} else {
alert('Element is here');
}
}
function myfunctionB() {
window.alert(myStuff.length);
}
function myfunctionC() {
var sum = 0;
for(var i = 0; i < myStuff.length; i++) {
sum+=myStuff[i];
}
alert(sum);
}
function myfunctionD() {
if (myStuff.length == 0) {
alert("already empty");
} else {
myStuff = [];
}
alert("Array Empty");
}
function myfunctionE() {
alert(myStuff.join('\n'));
{
if (myStuff == []) {
alert("Enter something into Array")
}
}
}
function bubbleSort() {
var sorted = true;
var temp;
while(sorted) {
sorted = false;
for(var i = 0; i < myStuff.length-1; i++) {
if(myStuff[i] < myStuff[i+1]) {
temp = myStuff[i];
myStuff[i] = myStuff[i+1];
myStuff[i+1] = temp;
sorted = true;
}
}
}
}
First you'll need a toggle to tell which way you are going.
var isAscending = false;
Then in your bubbleSort function inside the for-statement, above the if-statement.
var sortComparison;
if (isAscending) sortComparison = myStuff[i] > myStuff[i];
if (!isAscending) sortComparison = myStuff[i] < myStuff[i];
Then replace your if-statement with:
if (sortComparison)
Finally, once you have finished sorting, you can toggle your variable:
isAscending = !isAscending;
Though, I'd recommend using a toggled variable and simply using sort() and reverse() instead.
https://jsfiddle.net/ytcax0qc/

Categories

Resources