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

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!

Related

sea battle game / prevent typing the same thing twice

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.
}
}

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!");

Alert not working

My alert at the end of my JavaScript doesn't work, and I don't know why. I think that I have concatenated properly, but I don't know why the code doesn't do anything when it reaches the alert.
Here is the code for the HTML:
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/style.css">
<title>Play Battleship Free Online!</title>
</head>
<body>
<h1>Play Battleship!</h1>
<script src="battleship.js"></script>
<button onclick="startGame()">Play!</button>
</body>
here is the code for CSS (might not be needed):
body {
font-family: sans-serif;
text-align: center;
background-color: mediumseagreen;
}
h1 {
margin-top: 48px;
margin-bottom: 48px;
color: black;
}
and here is the code for my JavaScript:
var randomLoc = Math.floor(Math.random() * 5);
var location1 = randomLoc;
var location2 = location1 + 1;
var location3 = location2 + 1;
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
function startGame() {
while (isSunk == false){
guess = prompt("Ready, aim, fire! (Enter a number between 1 and 6): ")
if (guess < 0 || guess > 6){
alert("Please enter a valid number!");
}else{
guesses = guesses + 1;
}
if (guess == location1 || guess == location2 || guess == location3) {
hits++;
alert("HIT!");
} 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);
return;
}
Any help appreciated.
FTFY.
A few things to note:
Math.random generates a number between 0 and 1, inclusive of 0 but not 1. In your original code you wrote Math.random() * 5. This will get a number from 0 to 5, but not inclusive of 5. Flooring this number will get you 0 to 4. So, location1 could get the value of 0. This may not be desirable.
Proper code formatting is important. In the "Hit"/"Miss"/"Sank" chunk of code, the else should be match with the "Hit" block, but due to the formatting, it erroneously matched with the "Sank" block. The formatting makes this hard to be spotted.
For boolean variable checking, it is better to just use the variable in your condition without the comparison operator. while (isSunk == false) is better written as while (!isSunk). You don't have to worry about mistyping the double equal sign and it is easier to read. In fact, in your code, you do not even need a flag. while (hits < 3) works equally well.
Declare global variables sparingly. In your example, it is better to put the variables into the startGame method. This localize your variable to where they are used, while also have the added benefit of able to "restart the game" when you click the Play! button for the second time.
function startGame() {
// Randomly generate a number between 0 to 3, and
// add 1, 2, 3 to it to get 1 to 6.
var randomLoc = Math.floor(Math.random() * 4);
var location1 = randomLoc + 1;
var location2 = location1 + 1;
var location3 = location2 + 1;
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
while (!isSunk){
guess = prompt("Ready, aim, fire! (Enter a number between 1 and 6): ")
if (guess < 0 || guess > 6){
alert("Please enter a valid number!");
} else {
guesses = guesses + 1;
}
if (guess == location1 || guess == location2 || guess == location3) {
hits++;
alert("HIT!");
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);
return; //Optional
}
body {
font-family: sans-serif;
text-align: center;
background-color: mediumseagreen;
}
h1 {
margin-top: 48px;
margin-bottom: 48px;
color: black;
}
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/style.css">
<title>Play Battleship Free Online!</title>
</head>
<body>
<h1>Play Battleship!</h1>
<script src="battleship.js"></script>
<button onclick="startGame()">Play!</button>
</body>
</html>
Main problem in your javascript code, check following :
var randomLoc = Math.floor(Math.random() * 5);
var location1 = randomLoc;
var location2 = location1 + 1;
var location3 = location2 + 1;
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
function startGame() {
while (isSunk == false) {
guess = prompt("Ready, aim, fire! (Enter a number between 1 and 6): ")
if (guess < 0 || guess > 6) {
alert("Please enter a valid number!");
} else {
guesses = guesses + 1;
}
if (guess == location1 || guess == location2 || guess == location3) {
hits == hits + 1;
alert("HIT!");
}
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);
return;
}
body {
font-family: sans-serif;
text-align: center;
background-color: mediumseagreen;
}
h1 {
margin-top: 48px;
margin-bottom: 48px;
color: black;
}
<h1>Play Battleship!</h1>
<button onclick="startGame()">Play!</button>
I found some errors in your JavaScript code, see comments below:
var randomLoc = Math.floor(Math.random() * 5);
var location1 = randomLoc;
var location2 = location1 + 1;
var location3 = location2 + 1;
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
function startGame() {
while (isSunk == false){
guess = prompt("Ready, aim, fire! (Enter a number between 1 and 6): ")
if (guess < 0 || guess > 6){
alert("Please enter a valid number!");
}else{
guesses = guesses + 1;
}
if (guess == location1 || guess == location2 || guess == location3) {
hits == hits + 1;
alert("HIT!");
} if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
// Missing a closing curly brace
else {
alert("MISS!");
}
} // End of while-loop
} // End of startGame()
Outside of startGame():
var stats = "You took " + guesses + "guesses to sink the battleship, " + "which means your shooting accuracy was " + (3/guesses);
alert(stats);
return;
}

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.

Categories

Resources