vendredi 27 février 2015

Need help in building a logic in Javascript . Array Logic

Below is the hard coded page of a game Master Mind. The user


I know I need to




  1. use Array to store RBGY and some thing to do with indexOf(array name) I need to define a right answer (like RRBY hard coded for now) I need to check each letter in that Array the user typed and compare it with RRBY.




    1. I need show 2 things as answers visually on page so that users know which


      CLOSE : Right color in the wrong spot EXACT : Right Color in the Right Spot


      For example : 2 close and 1 exact




    2. Also I need the user to play this game only 10 times after that display you lost.




    3. Victory condition is the user gets the right combination RRBY then display Congrats






How do I set all of this up. New to JS. First Goal is to to make it working and then maybe get complex with display (close and exact).


Can some one help me the structure / function so that I can understand the logic and then I can try and write the syntax (I dont know if this makes sense :)


Any help would be appreciated.





window.onload = init;

function init(){
var button = document.getElementById("usrButton");
button.onclick = sayHello;
}

// my attempt at putting this logic
var colors = ["R", "B", "Y", "G"];
var correctAnswer = ["R", "Y", "Y", "G"];
// maybe i thought I need to define what is the right answer in an array first




if () {
// check if all the index in array CorrectAnswer are same as what user typed. maybe using every method
// display success message
}

else
// just display what the user types in on the page with display logic

else if {
// if the user leaves the text box blank . Alert him to enter some values
}


function sayHello(){
var usrTxt = document.getElementById("usrTxt");
var usrName = usrTxt.value;
var display = document.getElementById("displayHere");

var currentOutput = display.innerHTML;

display.innerHTML = currentOutput + usrName '<br>';

var div = document.getElementById("total");
div.appendChild(p);

//display.innerHTML = usrName;

//var p = document.createElement("p");
//p.innerHTML = "looks good";


}



body { color: black; background-color: #d0e4fe; margin-left: 45px; padding: 0;}
h1 { color: black; text-align: center; text-transform: uppercase;}
p { font-family: arial, verdana; font-size: 12px;}



<html>
<head></head>
<body>
<h1> Master Mind</h1>
<p> <b>Game Rules</b>
<ul>
<li>The user gets 10 chances to enter their guess of 4 colors from RGBY. After which you lose</li>
<li>Right Answer is - Correct Color in the Right Spot </li>
<li>Close Answer is - Correct Color but in the wrong Spot</li>

<li></li>
</ul>

Enter your name and click Submit.</p>
<input type="text" id="usrTxt">
<input type="button" onclick="" id="usrButton" value="Submit">
<div id="total">
<p id="displayHere"></p>
</div>
</body>
</html>



Aucun commentaire:

Enregistrer un commentaire