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