I have a game hangman. But I tried to make the logic, that if a user enters the wrong letter, then the user will get a message that he/she has to try again.
But now even if the user has chosen the correct letter, the user will get the message that he/she has to try it again.
This is the code:
<script>
var words = [
"ha",
"pe",
"jaa"
];
var word = words[Math.floor(Math.random() * words.length)];
var answareArray = [];
for (var i = 0; i < word.length; i++) {
answareArray[i] = "_";
}
var remainingLetters = word.length;
while (remainingLetters > 0) {
//gaming code
alert(answareArray.join(" "));
//Get a gues from the user:
var guess = prompt("Guess a letter, or click cancel to stop");
if (guess === null) {
break;
} else if (guess.length !== 1) {
alert("Please enter a single letter");
} else {
for (var j = 0; j < word.length; j++) {
if (word[j] !== guess) {
debugger;
alert("try again");
}
if (word[j] === guess) {
if (answareArray[j] !== "_") {
alert("Letter already be guessed");
break;
} else {
answareArray[j] = guess;
remainingLetters--;
}
}
}
}
}
alert(answareArray.join(" "));
alert("Good Job the answare was: " + word);
</script>
And in this part:
if (word[j] !== guess) {
debugger;
alert("try again");
}
I try to return the message to the user.
So what do I have to correct?
You have to show the alert after you checked all the letters, you're currently showing it at each iteration.
You can do that by using a flag (a boolean variable).
Here is an example:
var goodGuess = false;
for (var j = 0; j < word.length; j++) {
if (word[j] === guess) {
goodGuess = true;
if (answareArray[j] !== "_") {
alert("Letter already be guessed");
break;
} else {
answareArray[j] = guess;
remainingLetters--;
}
}
}
if(!goodGuess){
alert("try again");
}
What this does, is to first set the goodGuess variable to false, then go through all the letters and if the user's guess is equal to any of them, set goodGuess to true.
At the end of the loop (after all the letters were checked), if goodGuess is false, the alert is shown.
Related
I am trying to do a pop-up warning before the sales order is saved if the exact same item is entered twice when the order is created/modified on Netsuite. However, there is no window popping up and I am not sure what is wrong with the script. Here is what I got:
function validateitem (type){
var flag = true;
var numLine = nlapiGetLineItemCount('item');
itemArr = [];
if (type == 'item' && numLine > 0) {
for(var i = 0; i < numLine; i++) {
var itemSO = {};
itemSO.id = nlapiGetLineValue('item','item',i);
if (itemSO.id != null && itemSO.id !=''){
for (var j = 0; j < numLine; j++){
if(itenArr.indexOf(itemSO[i].id) === -1) {
itemArr.push(itemSO[i].id);}
else{
if (!confirm('You have entered a duplicate item for this sales order. Continue?'))
{
flag = false;
}
}
}
}
}
}
return flag;
}
Can somebody help, please?
Here is a slightly edited version:
function validateitem (){
var flag = true;
var numLine = nlapiGetLineItemCount('item');
itemArr = [];
if (numLine > 0) {
for(var i = 1; i <= numLine; i++) {
var itemSO = nlapiGetLineItemValue('item','item',i);
if (itemSO != null && itemSO !=''){
for (var j = 1; j <= numLine; j++){
if(itemArr.indexOf(itemSO[i]) === -1) {
itemArr.push(itemSO[i]);}
else{
flag = false;
}
}
}
}
}
if (flag == false){
alert('You have entered the same item twice.Continue?');
}
return flag;
}
This is the complete after-edit code that works:
function validateitem (){
var flag = true;
var numLine = nlapiGetLineItemCount('item');
itemArr = [];
if (numLine > 0) {
for(var i = 1; i <= numLine; i++) {
var itemSO = nlapiGetLineItemValue('item','item',i);
if (itemSO != null && itemSO !=''){
for (var j = i+1; j <= numLine; j++){
var itemSOplus = nlapiGetLineItemValue('item','item',j);
if(itemSO === itemSOplus) {
flag = false;
}
}
}
}
}
if (flag == false){
alert('You have entered the same item twice.Continue?');
}
return flag;
}
Thanks to Krypton!!
As per SuiteAnswers ID 10579, there are no paramters passed to the saveRecord client event. Therefore when your code checks the following:
if (type == 'item' && numLine > 0)
it finds that type equals undefined, so the condition is not met and the code will jump straight down to return flag which has been set to true.
Also note that in SuiteScript 1.0, line indexes start from 1 - not 0 as your code seems to assume.
EDIT - adding comment to form part of this answer:
I'd like to understand your logic behind itemSO[i] - as itemSO is not an array. Why not just compare the item from the current line of the inner loop with the current line of the outer loop and set the flag false if they match? Also, the inner loop need only start from j = i + 1 as the previous lines would have already been compared.
I am currently making a hangman game with javascript and I am struggling with how to remove and replace the previously selected word, with a new word. Currently I ahve my code set up so that when the player guesses the word correctly, a message pops up and asks the user if they want to play again. If they press Y, I call the function that randomly selects a word from and array and also uses the push method to fill and empty array with blank lines the same length of the chosen word. But when I call this function after Y has been pressed, the previous word doesnt go away and key presses also do not register.
var hangmanObject = {
randomWords: ['rock','paper','modular synthesizer', 'led zeppelin'],
chosenWord: "",
numWins: 0,
numLives: 10,
empty: [],
incorrect: [],
splitArray: []
}
function startFunction()
{
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
displayChosenWord();
}
function displayChosenWord()
{
hangmanObject.chosenWord = hangmanObject.randomWords[Math.floor(Math.random()*hangmanObject.randomWords.length)]
hangmanObject.splitArray = hangmanObject.chosenWord.split("");
for (x = 0; x < hangmanObject.chosenWord.length; x++)
{
if (hangmanObject.chosenWord.charAt(x) === " ")
hangmanObject.empty.push(" ");
else
hangmanObject.empty.push(" _ ");
}
document.getElementById("blanks").innerHTML = hangmanObject.empty.join("");
}
document.onkeyup = function(event)
{
var userGuess = String.fromCharCode(event.keyCode).toLowerCase();
for (x = 0; x < hangmanObject.chosenWord.length; x++)
{
if (hangmanObject.chosenWord.charAt(x) === userGuess)
{
hangmanObject.empty[x] = userGuess;
document.getElementById("blanks").innerHTML = hangmanObject.empty.join("");
}
}
if (hangmanObject.splitArray.indexOf(userGuess) === -1) //checking to see if wrong letter chosen
{
hangmanObject.numLives--;
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
hangmanObject.incorrect.push(userGuess);
document.getElementById("LettersGuessed").innerHTML = hangmanObject.incorrect;
}
console.log(hangmanObject.empty);
if (hangmanObject.empty.indexOf(" _ ") === -1)
{
hangmanObject.numWins++;
// console.log("i won");
document.getElementById("wins").innerHTML = hangmanObject.numWins;
document.getElementById("Play").innerHTML = "Play Again? Y/N";
document.onkeyup = function(event)
{
// Determines which exact key was selected. Make it lowercase
var Choice = String.fromCharCode(event.keyCode).toLowerCase();
if (Choice === 'y')
{
hangmanObject.numLives = 10;
displayChosenWord();
}
}
}
if (hangmanObject.numLives <= 0)
{
document.getElementById("lose").innerHTML = "You Lose";
}
}
You are setting the document.onkeyup callback inside the callback, effectively disabling it for letter guesses.
Also, the empty array is never emptied so the next word is appended to the empty letters array from the previous word. Here's a simpler approach, by using a gameState flag, you can decide whether the user is entering letters to guess, or they are deciding to play again. Also, a single div for status can be used ;)
var hangmanObject = {
gameState: 'playing',
randomWords: [
'rock',
'paper',
'modular synthesizer',
'led zeppelin'
],
chosenWord: "",
numWins: 0,
numLives: 10,
empty: [],
incorrect: [],
splitArray: []
}
function startFunction() {
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
chooseNewWord();
}
function chooseNewWord() {
hangmanObject.chosenWord = hangmanObject.randomWords[Math.floor(Math.random() * hangmanObject.randomWords.length)]
hangmanObject.splitArray = hangmanObject.chosenWord.split("");
// Reset guesses and misses
hangmanObject.empty = [];
hangmanObject.incorrect = [];
for (x = 0; x < hangmanObject.chosenWord.length; x++) {
if (hangmanObject.chosenWord.charAt(x) === " ")
hangmanObject.empty.push(" ");
else
hangmanObject.empty.push("_");
}
document.getElementById("blanks").innerHTML = hangmanObject.empty.join(" ");
}
document.onkeyup = function(event) {
var userGuess = String.fromCharCode(event.keyCode).toLowerCase();
// Game status is "playing"
if (hangmanObject.gameState === 'playing') {
for (x = 0; x < hangmanObject.chosenWord.length; x++) {
if (hangmanObject.chosenWord.charAt(x) === userGuess) {
hangmanObject.empty[x] = userGuess;
document.getElementById("blanks").innerHTML = hangmanObject.empty.join(" ");
}
}
// checking to see if wrong letter chosen
if (hangmanObject.splitArray.indexOf(userGuess) === -1) {
hangmanObject.numLives--;
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
hangmanObject.incorrect.push(userGuess);
document.getElementById("LettersGuessed").innerHTML = hangmanObject.incorrect.join(",");
}
// Some debug
console.log(hangmanObject.empty);
// WIN situation
if (hangmanObject.empty.indexOf("_") === -1) {
hangmanObject.numWins++;
// Set status message and game state
document.getElementById("status").innerHTML = "You won " + hangmanObject.numWins + " times";
hangmanObject.gameState = 'finished';
}
// LOSE situation
if (hangmanObject.numLives <= 0) {
// Set status message and game state
document.getElementById("status").innerHTML = "You Lose";
hangmanObject.gameState = 'finished';
}
// Set message if game finished
if (hangmanObject.gameState === 'finished') {
document.getElementById("Play").innerHTML = "Play Again? Y/N";
}
// Game status is "finished"
} else {
// If user selects play again
if (userGuess === 'y') {
// Set status back to "playing"
hangmanObject.gameState = 'playing';
// Reset lives and messages
hangmanObject.numLives = 10;
document.getElementById("status").innerHTML = "";
document.getElementById("LettersGuessed").innerHTML = "";
document.getElementById("Play").innerHTML = "";
// Choose new word
chooseNewWord();
} else {
// Set message
document.getElementById("status").innerHTML = "Goodbye!";
// Disable key handler
document.onkeyup = null;
}
}
}
startFunction();
<div id="numLives"></div>
<div id="blanks"></div>
<div id="LettersGuessed"></div>
<div id="status"></div>
<div id="Play"></div>
words joining - You need to clear the array.
no keyup - you replaced it with the 'y/n' keyup, you need to reset it.
also worth clearing the wrong letters and lives too on a new game.
see working example below:-
var hangmanObject = {
randomWords: ['rock', 'paper', 'modular synthesizer', 'led zeppelin'],
chosenWord: "",
numWins: 0,
numLives: 10,
empty: [],
incorrect: [],
splitArray: []
}
function startFunction() {
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
displayChosenWord();
}
function displayChosenWord() {
hangmanObject.empty = []; // empty the array
hangmanObject.incorrect = [];
hangmanObject.chosenWord = hangmanObject.randomWords[Math.floor(Math.random() * hangmanObject.randomWords.length)]
hangmanObject.splitArray = hangmanObject.chosenWord.split("");
for (x = 0; x < hangmanObject.chosenWord.length; x++) {
if (hangmanObject.chosenWord.charAt(x) === " ")
hangmanObject.empty.push(" ");
else
hangmanObject.empty.push(" _ ");
}
document.getElementById("blanks").innerHTML = hangmanObject.empty.join("");
document.getElementById("LettersGuessed").innerHTML = '';
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
document.onkeyup = gameKeyUp;
}
function gameKeyUp(event) {
var userGuess = String.fromCharCode(event.keyCode).toLowerCase();
for (x = 0; x < hangmanObject.chosenWord.length; x++) {
if (hangmanObject.chosenWord.charAt(x) === userGuess) {
hangmanObject.empty[x] = userGuess;
document.getElementById("blanks").innerHTML = hangmanObject.empty.join("");
}
}
if (hangmanObject.splitArray.indexOf(userGuess) === -1) //checking to see if wrong letter chosen
{
hangmanObject.numLives--;
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
hangmanObject.incorrect.push(userGuess);
document.getElementById("LettersGuessed").innerHTML = hangmanObject.incorrect;
}
console.log(hangmanObject.empty);
if (hangmanObject.empty.indexOf(" _ ") === -1) {
hangmanObject.numWins++;
// console.log("i won");
document.getElementById("wins").innerHTML = hangmanObject.numWins;
document.getElementById("Play").innerHTML = "Play Again? Y/N";
document.onkeyup = function(event) {
// Determines which exact key was selected. Make it lowercase
var Choice = String.fromCharCode(event.keyCode).toLowerCase();
if (Choice === 'y') {
hangmanObject.numLives = 10;
displayChosenWord();
}
}
}
if (hangmanObject.numLives <= 0) {
document.getElementById("lose").innerHTML = "You Lose";
}
}
displayChosenWord();
document.onkeyup = gameKeyUp;
<div id="numLives"></div>
<div id="blanks"></div>
<div id="LettersGuessed"></div>
<div id="wins"></div>
<div id="Play"></div>
<div id="lose"></div>
var text = "some text jjke kjerk jker helmi kjekjr helmi ekjrkje helmi";
var myName = "helmi";
var hits = [];
for (var i = 0; i < text.length; i++) {
if (text[i] === 'h') {
for (var j = i; j < text[i] + myName.length; j+=1) {
}
hits.push('text[j]');
}
};
if (hits.length === 0) {
console.log("Your name wasn't found!");
}
else {
console.log(hits);
}
I want it to find "myName" in the "text", and push it. But it only pushes whatever I put in the parenthesis after hits.push. What is wrong with this code?
But it only pushes whatever I put in the parenthesis after hits.push
Exactly, which is why you don't want to put a string in there:
hits.push('text[j]');
but a variable value:
hits.push(text[j]);
for (var i = 0; i < text.length; i++) {
if (text[i] === 'h') {
for (var j = i; j < text[i] + myName.length; j+=1) {
hits.push(text[j]);
}
}
your code has bracket problem and in some case you're doing wrong .
You can use split function. It gives you an opportunity to check your name word by word instead of checking your name character by character.
var text = "some text jjke kjerk jker helmi kjekjr helmi ekjrkje helmi";
var myName = "helmi";
var hits = [];
var texts = text.split(" ");
for (var i = 0; i < texts.length; i++) {
if (texts[i] === myName) {
hits.push(texts[i]);
}
}
if (hits.length === 0) {
console.log("Your name wasn't found!");
}
else {
console.log(hits);
}
Simple example for what you are trying to do is
if(text.indexOf(myName)!=-1)
console.log(myName);
else
console.log("Your name wasn't found");
I am trying to make a simple JavaScript guessing game, and my for loop keeps getting skipped! Here is the part of my code that is getting skipped:
for (i = 0; i === tries; i += 1) {
isSkipped = false;
var guessedNumber = prompt("Guess your number now.");
console.log("User guessed number " + guessedNumber);
//check if number is correct
if (guessedNumber === numberToGuess) {
confirm("Hooray, you have guessed the number!");
break;
} else if (guessedNumber > numberToGuess) {
confirm("A little too high...");
} else {
confirm("A little too low...");
}
}
and here is the full code:
//declaring variables
var numberToGuess;
var tries;
var i;
var isSkipped = true;
var confirmPlay = confirm("Are you ready to play lobuo's guessing game? The number for you to guess will be a number ranging from 1 to 25."); //does the user want to play?
if (confirmPlay === true) {
console.log("User wants to play");
} else {
window.location = "http://lobuo.github.io/pages/experiments.html";
} //if user wants to play, let them play, else go to website homepage
numberToGuess = Math.floor((Math.random() * 25) + 1); //sets computer-generated number
tries = prompt("How many tries would you like?"); //gets amount of tries
tries = Math.floor(tries); //converts amount of tries to integer from string
for (i = 0; i === tries; i += 1) {
isSkipped = false;
var guessedNumber = prompt("Guess your number now.");
console.log("User guessed number " + guessedNumber);
//check if number is correct
if (guessedNumber === numberToGuess) {
confirm("Hooray, you have guessed the number!");
break;
} else if (guessedNumber > numberToGuess) {
confirm("A little too high...");
} else {
confirm("A little too low...");
}
}
if (isSkipped === true) {
console.log("Oh no! The for loop has been skipped!");
}
If you need any further details, just ask.
Shouldn't the for be like this?:
for (i = 0; i < tries; i += 1) {
When you write:
for (i = 0; i === tries; i += 0) {
the loop repeats as long as the condition i === tries is true. If tries is 3, for instance, this condition is not true on the first iteration, and the loop ends immediately.
You should write:
for (i = 0; i < tries; i++) {
Also you need to use parseInt() function on user's input.
var guessedNumber = parseInt(prompt("Guess your number now."), 10);
instead of
var guessedNumber = prompt("Guess your number now.");
I'm creating a simple tic-tac-toe game and I have a boolean called winAlert that if it is true it should alert the player that they have won. This works correctly for the most part, but there is one instance where it does not. If the game is won and all of the cells are filled, the console logs that winAlert's value is false, but it still alerts the player that they have won, as if it were true. Could someone look over this code and see why this is behaving in this way? http://jsfiddle.net/Z5c9P/3/
This function is where I think the problem lies, but I don't know for sure.
var determineWin = function (pMoves) {
for (var i = 0; i < winConditions.length; i++) {
if (winConditions[i].length > pMoves.length) {
continue;
}
for (var j = 0; j < winConditions[i].length; j++) {
winAlert = false;
for (var k = 0; k < pMoves.length; k++) {
if (pMoves[k] === winConditions[i][j]) {
winAlert = true;
break;
}
}
if (!winAlert) break;
}
if (winAlert) {
alert(currentPlayer + " wins!");
break;
}
}
};
Here's the code that calls this function:
$('td').one('click', function () {
turnCount += 1;
setCurrentPlayer();
$(this).text(currentPlayer);
cellTracker = $(this).attr('id');
storeMoves();
determineWin(xMoves);
determineWin(oMoves);
if(turnCount === 9 && winAlert === false) {
alert("Tie game!");
}
console.log(turnCount, xMoves, oMoves, winAlert);
});
This is happening because your code does the following:
storeMoves();
determineWin(xMoves);
determineWin(oMoves);
if(turnCount === 9 && winAlert === false) {
alert("Tie game!");
}
console.log(turnCount, xMoves, oMoves, winAlert);
So if X ever wins the game, determineWin(xMoves) will set the variable to true, and determinWin(oMoves) will set it back to false, all before the console.log()
One way to solve this would be to only check for a win for the current player's moves:
storeMoves();
determineWin(currentPlayer == 'X' ? xMoves : yMoves);
if(turnCount === 9 && winAlert === false) {
alert("Tie game!");
}
console.log(turnCount, xMoves, oMoves, winAlert);
You have called determineWin on each player. so if x wins, determineWin(oMoves); will make winAlert false. Is this the problem?
Maybe you should create a new determineWin which only called once to determine who is the winner.
this code will just skip another user(so winAlert is still true) when his cell is less than 3, so this problem doesn't need fill all cells but just each player has more than 3 cells.
if (winConditions[i].length > pMoves.length) {
continue;
}
i change a little your code Fiddle
var determineWin = function (pMoves) {
for (var i = 0; i < winConditions.length; i++) {
if (winConditions[i].length > pMoves.length) {
continue;
}
winAlert = false;
matches = 0;
for (var j = 0; j < winConditions[i].length; j++) {
for (var k = 0; k < pMoves.length; k++) {
if (pMoves[k] === winConditions[i][j]) {
matches++;
}
}
}
if (matches == 3) return true;
}
return false;
};
and then
$('td').one('click', function () {
turnCount += 1;
setCurrentPlayer();
$(this).text(currentPlayer);
cellTracker = $(this).attr('id');
storeMoves();
if (determineWin(xMoves)){ // this is changed
alert("X Win")
return;
};
if (determineWin(oMoves)){
alert("O Win")
return;
};
if(turnCount === 9 && winAlert === false) {
alert("Tie game!");
}
console.log(turnCount, xMoves, oMoves, winAlert);
});
** Updated to clarify