2014-09-01 3 views
0

Я делаю Javascript RPS Bot (рок, бумага, ножницы робота).
Все работает отлично, за исключением случаев, когда я попытался добавить раздел к коду, который отображает оценки пользователя, если они набирают «баллы» или «все баллы» в поле ввода игры.
Я просматривал свой код снова и снова за ошибки и даже пытался использовать http://jsfiddle.net/ для его отладки, но он говорит мне, что ошибок нет.Javascript массив не будет обновляться

Так вот мой HTML:

<!DOCTYPE html> 
<html id="html"> 
    <body id="body"> 
    <div align="center" class="main"> 
     <input class="username" id="username" placeholder="Username"></input> 
     <input class="input" id="input" placeholder="Rock, Paper or Scissors" autofocus><!--game input box--></input> 
     <input type="button" class="button" value="Play" onClick="play()"></input> 
    </div> 

    <div class="result" id="result"> 
     <!--Game results go here--> 
    </div> 

    <center> 
    <input type="button" class="scheme" id="scheme" onClick="toggleScheme()" value="Scheme: Light"></input> 
    </center> 

    <script src="/jquery/1.11.1/jquery.min.js"></script> 
    <script> 
     //JQuery below goes here. 
    </script> 

    <script> 
     //Javascript below goes here 
    </script> 
    </body> 
</html> 

Мой JQuery проверяет только для нажатия клавиши «Enter» в любом месте в документе, чтобы начать игру, но здесь это только в случае, если:

$(document).keypress(function(e) { 
    if(e.which == 13) { 
    play(); 
    } 
}); 

И главная игра Javascript, проблема, скорее всего, начинается отсюда:

var play = function() { 
//Ekatwikz RPS bot v1.0.3 
var randomINT = function (min, max) { 
    var random = Math.floor(Math.random() * (max - min)) + min; 
    if (random > max || random < min) { 
    random = "ERROR"; 
    } 
    return random; 
}; 

var capitalize = function (input) { 
    return input.charAt(0).toUpperCase() + input.substring(1); 
}; 

var reset = function() { 
    document.getElementById('input').value = ""; 
    document.getElementById('result').scrollTop = document.getElementById('result').scrollHeight; 
}; 

var getInput = document.getElementById('input').value.toLowerCase(); 
var username = document.getElementById('username').value; 
var getRandom = randomINT(1, 4); 
var output = ["", "", "", "", "", ""]; 

var scores = [0, 0, 0, 0, 0, 0]; 
/*^This^ is the scores array, scores[0] is the number of times the user has won, scores[1] is the number of times the user has lost, scores[2] is the number of draws for the user, scores[3] is the number of times the computer has won, scores[4] is the number of times the computer has lost, scores[5] is the number of draws for the computer*/ 
if (getInput === "" || getInput === null) { 
    getInput = "_Blank"; 
} 

if (username === "" || username === null) { 
    username = "user"; 
} 

if (getInput.substring(0, 5) == "clear" || getInput == "cls") { 
    document.getElementById('result').innerHTML = ""; 
    reset(); 
    return; 
} else if (getInput.substring(0, 2) == "my" || getInput.substring(0, 4) == "user") { 
    document.getElementById("result").appendChild(document.createElement("BR")); 
    document.getElementById("result").appendChild(document.createElement("SPAN").appendChild(document.createTextNode("Your total scores:"))); 
    document.getElementById("result").appendChild(document.createElement("BR")); 
    document.getElementById("result").appendChild(document.createElement("SPAN").appendChild(document.createTextNode("Wins: " + scores[0]))); 
    document.getElementById("result").appendChild(document.createElement("BR")); 
    document.getElementById("result").appendChild(document.createElement("SPAN").appendChild(document.createTextNode("Losses: " + scores[1]))); 
    document.getElementById("result").appendChild(document.createElement("BR")); 
    document.getElementById("result").appendChild(document.createElement("SPAN").appendChild(document.createTextNode("Draws: " + scores[2]))); 
    document.getElementById("result").appendChild(document.createElement("BR")); 
    reset(); 
    return; 
} else if (getInput.substring(0, 4) == "comp") { 
    document.getElementById("result").appendChild(document.createElement("BR")); 
    document.getElementById("result").appendChild(document.createElement("SPAN").appendChild(document.createTextNode("Computer's total scores:"))); 
    document.getElementById("result").appendChild(document.createElement("BR")); 
    document.getElementById("result").appendChild(document.createElement("SPAN").appendChild(document.createTextNode("Wins: " + scores[3]))); 
    document.getElementById("result").appendChild(document.createElement("BR")); 
    document.getElementById("result").appendChild(document.createElement("SPAN").appendChild(document.createTextNode("Losses: " + scores[4]))); 
    document.getElementById("result").appendChild(document.createElement("BR")); 
    document.getElementById("result").appendChild(document.createElement("SPAN").appendChild(document.createTextNode("Draws: " + scores[5]))); 
    document.getElementById("result").appendChild(document.createElement("BR")); 
    reset(); 
    return; 
} else if (getInput.substring(0, 3) == "all" || getInput.substring(0, 6) == "scores") { 
    document.getElementById("result").appendChild(document.createElement("BR")); 
    document.getElementById("result").appendChild(document.createElement("SPAN").appendChild(document.createTextNode("All total scores:"))); 
    document.getElementById("result").appendChild(document.createElement("BR")); 
    document.getElementById("result").appendChild(document.createElement("SPAN").appendChild(document.createTextNode("Your wins: " + scores[0]))); 
    document.getElementById("result").appendChild(document.createElement("BR")); 
    document.getElementById("result").appendChild(document.createElement("SPAN").appendChild(document.createTextNode("Your losses: " + scores[1]))); 
    document.getElementById("result").appendChild(document.createElement("BR")); 
    document.getElementById("result").appendChild(document.createElement("SPAN").appendChild(document.createTextNode("Your draws: " + scores[2]))); 
    document.getElementById("result").appendChild(document.createElement("BR")); 
    document.getElementById("result").appendChild(document.createElement("SPAN").appendChild(document.createTextNode("Computer's wins: " + scores[3]))); 
    document.getElementById("result").appendChild(document.createElement("BR")); 
    document.getElementById("result").appendChild(document.createElement("SPAN").appendChild(document.createTextNode("Computer's losses: " + scores[4]))); 
    document.getElementById("result").appendChild(document.createElement("BR")); 
    document.getElementById("result").appendChild(document.createElement("SPAN").appendChild(document.createTextNode("Computer's draws: " + scores[5]))); 
    document.getElementById("result").appendChild(document.createElement("BR")); 
    reset(); 
    return; 
} 

//Main game logic section 
if (getRandom == 1) { 
    //If computer picked rock 
    if (getInput == "rock") { 
    output[5] = "YES"; 
    output[0] = capitalize(username) + " picked: Rock"; 
    output[1] = "Computer picked: Rock"; 
    output[2] = "*CLUNK SOUND*: Rocks smash against each other"; 
    output[3] = "DRAW"; 
    scores[2] = scores[2] + 1; 
    scores[5] = scores[5] + 1; 
    } else if (getInput == "paper") { 
    output[5] = "YES"; 
    output[0] = capitalize(username) + " picked: Paper"; 
    output[1] = "Computer picked: Rock"; 
    output[2] = "Paper beats Rock"; 
    output[3] = capitalize(username) + " Wins"; 
    scores[0] = scores[0] + 1; 
    scores[4] = scores[4] + 1; 
    } else if (getInput == "scissors") { 
    output[5] = "YES"; 
    output[0] = capitalize(username) + " picked: Scissors"; 
    output[1] = "Computer picked: Rock"; 
    output[2] = "Rock beats Scissors"; 
    output[3] = "Computer Wins"; 
    scores[1] = scores[1] + 1; 
    scores[3] = scores[3] + 1; 
    } else { 
    output[5] = "NO"; 
    output[4] = 'ERROR: Computer does not understand what "' + getInput + '" is.'; 
    } 
} else if (getRandom == 2) { 
    //If computer picked paper 
    if (getInput == "rock") { 
    output[5] = "YES"; 
    output[0] = capitalize(username) + " picked: Rock"; 
    output[1] = "Computer picked: Paper"; 
    output[2] = "Paper beats Rock"; 
    output[3] = "Computer Wins"; 
    scores[1] = scores[1] + 1; 
    scores[3] = scores[3] + 1; 
    } else if (getInput == "paper") { 
    output[5] = "YES"; 
    output[0] = capitalize(username) + " picked: Paper"; 
    output[1] = "Computer picked: Paper"; 
    output[2] = "*SWISH SOUND* Papers brush against each other"; 
    output[3] = "DRAW"; 
    scores[2] = scores[2] + 1; 
    scores[5] = scores[5] + 1; 
    } else if (getInput == "scissors") { 
    output[5] = "YES"; 
    output[0] = capitalize(username) + " picked: Scissors"; 
    output[1] = "Computer picked: Paper"; 
    output[2] = "Scissors beats Paper"; 
    output[3] = capitalize(username) + " Wins"; 
    scores[0] = scores[0] + 1; 
    scores[4] = scores[4] + 1; 
    } else { 
    output[5] = "NO"; 
    output[4] = 'ERROR: Computer does not understand what "' + getInput + '" is.'; 
    } 
} else if (getRandom == 3) { 
    //If computer picked scissors 
    if (getInput == "rock") { 
    output[5] = "YES"; 
    output[0] = capitalize(username) + " picked: Rock"; 
    output[1] = "Computer picked: Scissors"; 
    output[2] = "Rock beats Scissors"; 
    output[3] = capitalize(username) + " Wins"; 
    scores[0] = scores[0] + 1; 
    scores[4] = scores[4] + 1; 
    } else if (getInput == "paper") { 
    output[5] = "YES"; 
    output[0] = capitalize(username) + " picked: Paper"; 
    output[1] = "Computer picked: Scissors"; 
    output[2] = "Scissors beats Paper"; 
    output[3] = "Computer Wins"; 
    scores[1] = scores[1] + 1; 
    scores[3] = scores[3] + 1; 
    } else if (getInput == "scissors") { 
    output[5] = "YES"; 
    output[0] = capitalize(username) + " picked: Scissors"; 
    output[1] = "Computer picked: Scissors"; 
    output[2] = "*CLINK SOUND*: Scissors hit each other"; 
    output[3] = "DRAW"; 
    scores[2] = scores[2] + 1; 
    scores[5] = scores[5] + 1; 
    } else { 
    output[5] = "NO"; 
    output[4] = 'ERROR: Computer does not understand what "' + getInput + '" is.'; 
    } 
} else { 
    output[5] = "NO"; 
    output[4] = "ERROR: Randomizer function seems to be broken"; 
} 

var finish = function (input) { 
    if (input === undefined) { 
    if (output[5] == "YES") { 
     document.getElementById("result").appendChild(document.createElement("BR")); 
     document.getElementById("result").appendChild(document.createElement("SPAN").appendChild(document.createTextNode(output[0]))); 
     document.getElementById("result").appendChild(document.createElement("BR")); 
     document.getElementById("result").appendChild(document.createElement("SPAN").appendChild(document.createTextNode(output[1]))); 
     document.getElementById("result").appendChild(document.createElement("BR")); 
     document.getElementById("result").appendChild(document.createElement("SPAN").appendChild(document.createTextNode(output[2]))); 
     document.getElementById("result").appendChild(document.createElement("BR")); 
     document.getElementById("result").appendChild(document.createElement("SPAN").appendChild(document.createTextNode(output[3]))); 
     document.getElementById("result").appendChild(document.createElement("BR")); 
    } else { 
     document.getElementById("result").appendChild(document.createElement("BR")); 
     document.getElementById("result").appendChild(document.createElement("SPAN").appendChild(document.createTextNode(output[4]))); 
     document.getElementById("result").appendChild(document.createElement("BR")); 
    } 
    } 
}; 

finish(); 
reset(); 
}; 

I apol ogize заранее для неопрятного кода.

+2

Возможно, вы захотите изучить один из доступных механизмов JavaScript. Это сделает ваш код таким же, как ваш ** много ** чище. – Pointy

+0

, пожалуйста, ссылку на ваш jsfiddle ... И ... Лучше работать с объектами –

+0

Ваш код будет намного легче читать и поддерживать, если вы использовали объекты вместо массивов, например. 'scores.wins',' scores.losses' и т. д. – Barmar

ответ

0

Проблема заключается в том, что scores является локальной переменной в вашей функции play, поэтому она получает повторный инициализацию каждый раз, когда пользователь запускает другую игру. Это должна быть глобальная переменная, вне функции, поэтому ее значение сохраняется от одного вызова к другому.

var scores = [0,0,0,0,0,0]; 
var play = function() { 
    ... 
} 

И было бы лучше, чтобы сделать его объект:

var scores = { 
    humanWin: 0, 
    humanLose: 0, 
    draw: 0 
}; 

Я не вижу, почему вам нужны дополнительные элементы для компьютерных побед, потерь, и рисовать; число компьютерных побед всегда совпадает с человеческими потерями и наоборот, и оба они имеют одинаковое количество ничьих.

+0

Ничего себе, так вот в чем проблема ... Прямо сейчас я чувствую себя совершенно как слепой noob. В любом случае спасибо! XD – Ekatwikz

Смежные вопросы