sea battle game / prevent typing the same thing twice - javascript

such a problem is that if I enter the same number 3 times and it counts for me as a win, but I need to prohibit it so that I cannot enter the same number a second time, can you tell me how to do this?
let randomLocation = Math.floor(Math.random() * 6)
let location1 = randomLocation
let location2 = location1 + 1
let location3 = location2 + 1
let guess
let hits = 0
let guesses = 0
let isSunk = false
while (isSunk == false) {
guess = prompt('Enter the coordonation: ')
let secondTime = guess
if (guess < 0 || guess > 6) {
alert('Your number is incorrect')
} else {
guesses++
if (guess == location1 || guess == location2 || guess == location3) {
alert('SHOT')
hits++
if (hits == 3) {
isSunk = true
alert('The ship was wrecked')
}
} else {
alert('you missed')
}
}
}
let stats = 'You wrecked from ' + guesses + ' attempts ' + ' which means you have statistics ' + (3 / guesses)
console.log(stats)

Here's one way to check to see if the user has entered the same thing before. Use a Set.
let answers = new Set();
while(true) {
let input = prompt('Enter something')
if (input == null) break;
if (answers.has(input)) {
alert('You already entered that.');
} else {
alert('That is new!')
answers.add(input); // Remember this input for later.
}
}

Related

can not display the dialog when load both file .js or .html?

I am having trouble with this problem. When I coded this very simple javascript code from head first javasript book, they said to me that I must saved it as the name battle.js and run it, but after that, they said to me that I must run it as the name battle.html. Here is the code
var location1 = 3;
var location2 = 4;
var location3 = 5;
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
while (isSunk == false) {
guess = promt("Ready, aim, fire! (enter a number from 0-6):")
if (guess < 0 || guess > 6) {
alert("Please enter a valid cell number!");
} else {
guesses = guesses + 1;
if (guess == location1 || guess == location2 || guess == location3) {
alert("HIT!");
hits = hits + 1;
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
}
} else {
alert("MISS");
}
}
}
var stats = "You took " + guesses + " guesses to sink the battleship, " +
"which means your shooting accuracy was " + (3/guesses);
alert(stats);
As they described, it must appear a dialog and we can enter something into that, but when I ran it, nothing appeared.
I just a newbie with javascript, could you please give me some ideas ? Thank you very much.
Your code has typing mistake. replace promt to prompt
var location1 = 3;
var location2 = 4;
var location3 = 5;
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
while (isSunk == false) {
guess = prompt("Ready, aim, fire! (enter a number from 0-6):")
if (guess < 0 || guess > 6) {
alert("Please enter a valid cell number!");
} else {
guesses = guesses + 1;
if (guess == location1 || guess == location2 || guess == location3) {
alert("HIT!");
hits = hits + 1;
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
}
} else {
alert("MISS");
}
}
}
var stats = "You took " + guesses + " guesses to sink the battleship, " +
"which means your shooting accuracy was " + (3 / guesses);
alert(stats);

Javascript battleship game - prompt not responding

I'm trying to follow along with my javascript book "headfirst javascript programming"....
the assignment is to make a simplified battleship game. It was working until I added more code... Now the prompt is not showing. Im sure im doing something wrong with the curly brackets. I just want the prompt "Ready, aim, fire! (enter a number from 0-6):" to appear when launching the browser and for it to respond to numerical inputs.
Can anyone quickly tell me why im screwing up? thank you! here is my simple code --->>>
//declare variables
var location1 = 3;
var location2 = 4;
var location3 = 5;
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
//loop
while (isSunk == false) {
//get
guess = prompt("Ready, aim, fire! (enter a number from 0-6):");
if (guess < 0 || guess > 6) {
alert("Please enter a valid cell number!");
} else {
//add
guesses = guesses + 1;
//if
if (guess == location1 || guess == location2 || guess == location 3) {
alet("HIT!");
hits = hits + 1;
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
}
} else {
alert("MISS");
}
}
}
var stats = "You took " + guesses + "guesses to sink the battleship, " +
"which means your shooting accuracry was " + (3/guesses);
alert(stats);
Your lines
if (guess == location1 || guess == location2 || guess == location 3) {
and
alet("HIT!");
have errors, a extra space in location3 variable name and missing r from alert, they should be
if (guess == location1 || guess == location2 || guess == location3) {
and
alert("HIT!");

Parameter being set to undefined

I am working on a school project which is based on the game Wheel of Fortune. Currently, I am working on having the computer differentiate between a consonant and vowel, and adding to the player's balance if they correctly guess a letter. As of now, I have encountered two problems.
First, when checking if a letter is a vowel, it correctly says which is which, and also checks if a vowel CAN be guessed (player needs to have at least a certain amount of money). If they can, it will deduct the necessary amount and move on normally. If not, however, it should disregard the guess and have the player guess again. This works until the player guesses a different letter. What happens is the second guess that the player tries is checked, but the first guess, the vowel which they could not afford, is also checked.
Here is what it looks like:
The word is CANADA
Basically, the player guessed A at first, but when asked to guess another letter (because they did not have enough money), they guessed C. When updating, the computer updated both for letter A and letter C, which I do not want.
Second, I am trying to have the player's balance update if they correctly guess a letter. For this, I have a separate function setup to update a balance based on the type of guess, but somewhere, the variable becomes undefined. This is the related code that I have for that part:
I am using parameters to do this, what is going wrong?
function spinWheel() {
spinAmount();
ask();
}
function spinAmount() {
var luck = randomNum(0, rewards.length);
var multiplier = rewards[luck];
if (multiplier == undefined) {
spinAmount();
} else {
alert("You spun $" + multiplier);
return multiplier;
}
updateBalance(multiplier);
}
function ask() {
console.log("Prompting");
var guess = prompt("What letter would you like to guess?");
var playerGuess = guess.toUpperCase();
console.log(playerName1 + " guessed " + playerGuess);
checkGuessType(playerGuess);
}
function checkGuessType(checkMe) {
console.log("Checking type...");
if (checkMe.length > 1) {
console.log(playerName1 + " guessed a word.");
} else if (checkMe == "A" || checkMe == "E" || checkMe == "I" || checkMe == "O" || checkMe == "U" && balance1 < 100) {
console.log(playerName1 + " tried to guess a vowel.");
alert("You cannot spin the wheel and guess a vowel!")
alert("You do not have enough money to buy a vowel. Guess a different letter.");
ask();
} else if (checkMe == "A" || checkMe == "E" || checkMe == "I" || checkMe == "O" || checkMe == "U" && balance1 > 100) {
console.log(playerName1 + " guessed a vowel.");
alert("You cannot spin the wheel and guess a vowel!")
alert("Since you guessed a vowel, you do not get any money added to your account. Instead, $100 was deducted.");
isVowel = true;
} else if (checkMe !== "") {
console.log(playerName1 + " guessed a consonant.");
} else if (checkMe == "") {
console.log(playerName1 + " did not guess.");
alert("Please guess a letter or word.")
ask();
}
checkForGuess(checkMe);
}
function checkForGuess(amIThere) {
console.log("Checking if letter is present...");
for (x = 0; x < magicyMagic.length; x++) {
if (amIThere == magicyMagic.charAt(x)) {
console.log("Ding ding ding!");
lettersMatched = lettersMatched + 1;
isCorrect = true;
output[x] = amIThere;
if (isVowel == false) {
updateBalance();
} else if (isVowel == true && nowGoing == 1) {
balance1 = balance1 - 100;
} else if (isVowel == true && nowGoing == 2) {
balance2 = balance2 - 100;
}
lettersMatched = 0;
document.getElementById("mysteryWord").innerHTML = output.join("");
document.getElementById("pl1Messages").innerHTML = "Player 1 - " + playerName1 + " has $" + balance1;
}
}
if (isCorrect == false && amIThere !== "") {
console.log("Player did not guess correctly...");
document.getElementById("mysteryWord").innerHTML = output.join("");
document.getElementById("pl1Messages").innerHTML = "There are no " + amIThere + "'s in the word.";
lettersMatched = 0;
document.getElementById("lastMessage").innerHTML = "Player 2 (" + playerName2 + ") will now go.";
}
hasBeenGuessed.push(amIThere);
console.log(hasBeenGuessed[0] + " has been added to the list. Players cannot guess this letter again.");
}
function updateBalance(totalMoneySpun) {
alert(totalMoneySpun)
if (nowGoing == 1) {
balance1 = balance1 + (lettersMatched * totalMoneySpun);
document.getElementById("pl1Messages").innerHTML = "Player 1 - " + playerName1 + " has $" + balance1;
}
}

Random Number Guessing Game - Limit the Number of guesses

I'm trying to make a program that generates a random number which the user guesses. It also limits the number of guesses the user can make (or is supposed to.)
var highLimit = 5;
var randNum = Math.floor((Math.random() * highLimit) + 1);
var allowedGuesses = 2;
var numGuesses = 0;
function guessingGame() {
if (numGuesses <= allowedGuesses) {
do {
inputNum = document.numForm.number.value;
inputNum = parseInt(inputNum);
if (inputNum < randNum && inputNum > 1) {
document.numForm.gameResults.value = "Sorry, your guess was too low.";
numGuesses++;
}
else if (inputNum > randNum && inputNum < highLimit) {
document.numForm.gameResults.value = "Sorry, your guess was too high.";
numGuesses++;
}
else if (inputNum == randNum) {
document.numForm.gameResults.value = "Congratulations! You guessed correctly.";
numGuesses++;
}
else {
document.numForm.gameResults.value = "Your guess was out of the desired parameters. Please guess again.";
numGuesses--;
}
} while(numGuesses < allowedGuesses && inputNum != randNum);
}
else {
document.numForm.gameResults.value = "Sorry, you have reached the allowed number of guesses, which is " + allowedGuesses + "." + " Click 'New Game' to try again.";
}
return false;
}
numGuesses = 0;
function newGame() {
randNum = Math.floor((Math.random() * highLimit) + 1);
guessingGame();
return false;
}
And the HTML:
<form name = "numForm">
<fieldset>
<label for = "randNum">Enter a number between 1 and 5: </label>
<input type = "text" name = "number" value = "" id = "randNum" size = "1" maxlength = "1" />
</fieldset>
<input class = "button" type = "button" name = "submit" onclick = "guessingGame()" value = "Submit Number" />
<input class = "button" type = "reset" name = "newGame" onclick = "newGame()" value = "New Game" />
<fieldset>
<textarea name = "gameResults" onclick = "" readonly = "true" value = "" rows = "5" cols = "40" ></textarea>
</fieldset>
</form>
Right now, the program is stuck in a infinite loop since highLimit is set at 5. But if I set it at ten, the program works. How can I fix it so it works at any value? I would also appreciate other suggestions for improvement.
Thanks in advance!
I think you don't need a loop in this one. You can simple say:
function guessingGame() {
if (numGuesses < 0){numGuesses=0;}
if ((numGuesses < allowedGuesses) && (inputNum != randNum)) {
inputNum = document.numForm.number.value;
inputNum = parseInt(inputNum);
if (inputNum < randNum && inputNum > 1) {
document.numForm.gameResults.value = "Sorry, your guess was too low.";
numGuesses++;
}
else if (inputNum > randNum && inputNum < highLimit) {
document.numForm.gameResults.value = "Sorry, your guess was too high.";
numGuesses++;
}
else if (inputNum == randNum) {
document.numForm.gameResults.value = "Congratulations! You guessed correctly.";
numGuesses++;
}
else {
document.numForm.gameResults.value = "Your guess was out of the desired parameters. Please guess again.";
numGuesses--;
}
}
else {
document.numForm.gameResults.value = "Sorry, you have reached the allowed number of guesses, which is " + allowedGuesses + "." + " Click 'New Game' to try again.";
}
return false;
}
the if (numGuesses < 0){numGuesses=0;} will help also. for negative cases.
This is an update for:
Ran the Snippet and answeared in "0 tries"
This is how I did it: But you're going to have to replace the 'prompts' and 'alerts' with your specified inputs and outputs, if you still need it after 4 years:
let maximum = parseInt(prompt('Enter the maximum number!') );
while(!maximum) {
maximum = parseInt (prompt('Please enter a valid number') )
}
const targetNum = Math.floor(Math.random()*maximum)+1;
let attempts =0;
let maxAttempts = Math.ceil(maximum/2);
// ==== Uncomment the line below to cheat --> ======
// console.log(targetNum)
let guess = parseInt(prompt(`Enter your first guess!, you have ${maxAttempts} attempts (press 'q' anytime to escape from this hellish nightmare)`));
while(parseInt(guess) !==targetNum && attempts < maxAttempts-1) {
if (typeof(guess) === 'string' && guess.toLowerCase() ==='q') {break;}
attempts++;
if(guess>targetNum) {
guess = (prompt(`Too High! Enter new guess! attempts left: ${maxAttempts- attempts} (press 'q' anytime to escape from this hellish nightmare)`))
}else {
guess= (prompt(`Too low! Entere a new Guess! attempts left: ${maxAttempts- attempts} (press 'q' anytime to escape from this hellish nightmare)`))
}
}
if(typeof(guess) === 'string' && guess.toLowerCase() ==='q') {
alert(`You gave up after ${attempts} attempts`);
}
else if(attempts >= maxAttempts-1) {alert(`Oops, your ${maxAttempts} attempts ran out, the number was ${targetNum}: Verification : ${targetNum==guess}`);}
else {
alert(`Good job, you got it ${attempts+1} attempts!, the number was ${targetNum}: Verification : ${targetNum==guess}`) ;
}

Can't save the value of JavaScript prompt() function

I'm new to JavaScript and I'm building a very basic battleship program, but I've noticed that the prompt() function doesn't seem to bring up a dialog box if I try to save it's value to a variable. Here's my code:
var location1 = 3;
var location2 = 4;
var location3 = 5;
var hits = 0;
var guesses = 0;
var guess;
var isSunk = false;
while (isSunk == false){
guess = prompt("Ready, aim, fire! Enter a number 0-6");
if (guess < 0 || > 6){
alert("PLease enter a valid cell number!");
}
else{
guesses = guesses + 1;
if (guess == location1 || guess == location2 || guess == location3){
alert("Hit!");
hits = hits + 1;
if (hits == 3){
isSunk = true;
alert("You sank my battleship!");
}
else{
alert("Miss!");
}
}
}
}
var stats = "You took " + guesses + " guesses to sink the battleship, " + "which means your shooting accuracy was " + (3/guesses);
alert(stats);
Now, the reason that I think my prompt not appearing when I load the browser is due to the fact that I'm trying to set the value of the prompt to the variable guess is because the following code executes without issue:
var location1 = 3;
var location2 = 4;
var location3 = 5;
var hits = 0;
var guesses = 0;
var guess;
var isSunk = false;
while (isSunk == false){
prompt("Ready, aim, fire! Enter a number 0-6");
isSunk = true;
}
var stats = "You took " + guesses + " guesses to sink the battleship, " + "which means your shooting accuracy was " + (3/guesses);
alert(stats);
Can someone help me understand what the issue with my code is please? Thanks in advance :)
You are using prompt() correctly.
The problem is in the line below :
if (guess < 0 || > 6) {
should be
if (guess < 0 || guess > 6){
This error was stopping the JS before prompt() was called.
In the future, you should use the browser console to debug your code. You would have seen this error.
If you use Firefox, you can open it with Ctrl+Shift+K. With Chrome it's Ctrl+Shift+J.
When you will have resolved this issue, you will see that the rest of the code has no syntax error but is not doing exactly the right thing (for example I can hit the same location several times). Logic errors are not as easy to fix (you have no debugger to help you). So... good luck !
Well, don't worry in your case it won't be hard to fix.
+1 to the above comment.
Furthermore Kiyana, when you run your code, you'll notice that as long as the user's input is not <0 or >6, the alert("Hit!") and the alert("Miss!") are both appearing.
This has to do with the ordering of your code:
if (guess == location1 || guess == location2 || guess == location3){
alert("Hit!");
hits = hits + 1;
if (hits == 3){
isSunk = true;
alert("You sank my battleship!");
}
else{
alert("Miss!");
}
}
Here is the order in which you want the above code to appear.
Pseudo Code:
If user's guess is 3, 4, or 5 (location1, location2, or location3), then we want to alert a "Hit"
Then, add 1 counter to the hit variable (hit = hit + 1)
ELSE - then we want to alert a "Miss."
After this guess is evaluated, we want to check to see if the hit counter has reached 3.
a) If it hasn't, then we loop back through all the code.
b) If it has, then we want to make isSunk equal to true (to stop the loop) and alert a "You sank my battleship!"
The code should look like this:
var location1 = 3;
var location2 = 4;
var location3 = 5;
var hits = 0;
var guesses = 0;
var guess;
var isSunk = false;
while (isSunk === false){
guess = prompt("Ready, aim, fire! Enter a number 0-6");
if (guess < 0 || guess > 6){
alert("Please enter a valid cell number!");
} else{
guesses = guesses + 1;
if (guess == location1 || guess == location2 || guess == location3){
alert("Hit!");
hits = hits + 1;
}else{
alert("Miss!");
}
if (hits == 3){
isSunk = true;
alert("You sank my battleship!");
}
}
}
var stats = "You took " + guesses + " guesses to sink the battleship, " + "which means your shooting accuracy was " + (3/guesses);
alert(stats);
Hope this helps!

Categories

Resources