Я начинающий программист. Я начал преподавать JavaScript. Я сделал рудиментарный боевой корабль. Проблема заключается в том, что если пользователь входит в одно и то же место (если он попал), то 3 раза линкоры поглощаются. Чтобы избежать этого, я добавил массив "userchoices" для записи пользовательских входов, а затем перекрестно проверил путем итерации через цикл for. цикл for, в свою очередь, содержит оператор If, который должен предупредить пользователя, если он уже был запущен в этом месте раньше. Проблема в том, что оператор if выполняется каждый раз.
Ознакомьтесь с приведенным ниже кодом и предложите исправления. Спасибо.
var randomloc = Math.floor(Math.random() * 5);
var location1 = randomloc;
var location2 = location1 + 1;
var location3 = location2 + 1;
var guess;
var userchoices = [];
var hits = 0;
var guesses = 0;
var issunk = false;
function battleship() {
while(issunk == false)
{
guess = prompt("Ready,Aim,Fire! (Enter a number 0-6):");
console.log("users input = " + guess);
if (guess == null)
break;
if (guess < 0 || guess > 6){
alert("Please enter a valid cell number. No of guesses has been
incremented.")
}
else{
guesses++;
userchoices[guesses] = guess;
console.log("users choices = " + userchoices);
}
/* for(var i = 0; i <= guesses; i++)
{
if(userchoices[guesses] = guess)
console.log("you have already fired at this location");
} */
if (guess == location1 || guess == location2 || guess == location3){
alert("Enemy Battleship HIT");
hits = hits + 1;
if (hits == 3){
issunk = true;
alert("Enemy battleship sunk")
}
}
else{
alert("You Missed");
}
}
if (issunk){var stats = "you took " + guesses + " guesses to sink the battleship. You accuracy was " + (3/guesses);alert(stats);}
else{alert("You Failed!"); issunk = false;}
}
Это та часть, которая вызывает ошибку
for(var i = 0; i<=guesses; i++)
{
if (userchoices[guesses] = guess){
console.log("you have fired at this location already");
}}
Оператор if должен выполняться только тогда, когда пользователь вводит номер сетки, на который у него уже есть огонь, независимо от того, попали ли они или пропустили.
Вы получаете доступ к массиву по неверному индексу. Попробуйте userchoices[i]
вместо userchoices[guesses]
. Также сравнение равенства выполняется с использованием двух равных знаков ==
:
for(var i = 0; i<=guesses; i++)
{
if (userchoices[i] == guess){
console.log("you have fired at this location already");
}
}
Это также можно выразить как:
if (userchoices.includes(guess)){
console.log("you have fired at this location already");
}
Кроме того, догадки должны быть увеличены после добавления первого значения:
else{
userchoices[guesses] = guess;
guesses++;
console.log("users choices = " + userchoices);
}
Здесь существует логическая ошибка, так как вы проверяете массив для элемента после его вставки в массив, выполняйте проверку в инструкции else перед вставкой элемента. Объединив все вышесказанное:
else if (userchoices.includes(guess)){
console.log("you have fired at this location already");
} else {
userchoices[guesses] = guess;
guesses++;
console.log("users choices = " + userchoices);
}
После столь необходимой помощи от Авина Кавиша и немного потрудившись, я теперь могу представить ответ на свой вопрос для будущих зрителей.
Изменение: больше похоже на мою последнюю программу
function battleship()
{
var guess; //Stores user guess
var userchoices = []; //records user guess until ship is sunk or user chickens out
var issunk = false; //status of ship
var hits = 0; //number of hits
var guesses = 0; //number of guesses
var randomloc = Math.floor(Math.random() * 5); //Random Number Generator
var location1 = randomloc;
var location2 = location1 + 1;
var location3 = location2 + 1;
while(issunk == false)
{
guess = prompt("Ready,Aim,Fire! (Enter a number 0-6):");
console.log("users input = " + guess);
if(guess == null) // If users presses 'OK' without entering anything or the 'Cancel' this would break the loop.
break;
if (guess < 0 || guess > 6){
alert("Please enter a valid cell number. No of guesses has been incremented.");
guesses++; //Gotta punish the player.
}
else if (userchoices.includes(guess) == false) /*instead of doing what i did yo u
can change this line to "else if (userchoices.includes(guess)) and then put the
following oprations in its else clause. */
{
guesses++;
userchoices[guesses] = guess;
console.log("User choices = " + userchoices);
if (guess == location1 || guess == location2 || guess == location3)
{
alert("Enemy Battleship HIT");
hits = hits + 1;
if (hits == 3)
{
issunk = true;
alert("Enemy battleship sunk");
}
}
else
{
alert("You Missed");
}
}
else
{
alert("you have already fired at this location.")
}
if (issunk) //writing issunk == true is overkill
{
var stats = "you took " + guesses + " guesses to sink the battleship. You
accuracy was " + (3/guesses);
alert(stats);
}
}
if(guess == null && issunk == false)
console.log("You failed"); //Humiliate the user for chickening out.
userchoices = []; //Empties the array so user can start over again without relaoding the page
issunk = false; //sets issunk to false for a new game
var randomloc = Math.floor(Math.random() * 5); //creates new random numbers for ship coordinates
}
Версия 2D 7X7 скоро появится. Будет опубликован здесь.