简体   繁体   中英

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> 

==================================================

  window.onload = init; function init(){ var button = document.getElementById("usrButton"); button.onclick = submitAnswer; } // global counter variable //var i = 0; function submitAnswer(){ var usrTxt; var answers = []; //define a new variable and make a empty array answers.push(document.getElementById('usrTxt').value); // push the content the user types as array in a variable called answers //defined a new variable so that I can display what the user entered as it is var display = document.getElementById("displayHere"); display.innerHTML = usrTxt; } 
  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 Guess and click Submit.</p> <input type="text" id="usrTxt"> <input type="button" onclick="submitAnswer()" id="usrButton" value="Submit"> <div id="total"> <p id="displayHere"></p> </div> </body> </html> 

try something like this:

answer='RYYG'
function haveAguess(){
    guess=textBox.value
    guessDiv.innerText=guess
    if(!guess){
        alert('No Guess Entered!')
        return
    }
        else if(guess==answer){
            alert('Congratulations')
            return
        }
            else{
                result=[]
                x='Wrong'
                y='Wrong'
                for(i in guess){
                    if(guess[i]==answer[i]){
                        x='Correct';    y='Right'
                    }
                        else if(answer.indexOf(guess[i])>=0)    x='Correct';
                    result.push('Color ['+i+'] is the: '+x+' Color in the '+y+' Spot');
                }
                displayDiv.innerText=result.join('\n')
            }
}

I think it meets all your needs...

EDITED

This is how it works...

  1. guess=textBox.value ; retrieves the users guess from the text box.
  2. guessDiv.innerText=guess ; displays the guess on screen.
  3. if(!guess) ; !guess is the same as guess=='' , or no guess entered, so alert the user and return/end the function.
  4. else if(guess==answer) ; if the guess is the same as the answer variable, the congratulate the user and end the function.
  5. else ; if the user entered some text ie: guess!='' and the guess does not match the answer ie: guess!=answer , then:
    5.1. result=[] ; ready an array to return the results.
    5.2. x='Wrong'; y='Wrong' x='Wrong'; y='Wrong' ; set x & y defaults to 'Wrong'.
    5.3. for(i in guess) ; loop through every character in the guess string.
    5.3.1. if(guess[i]==answer[i]) ; if the character at [i] in guess matches the character at [i] in answer ie: guess[i]=='R' && answer[i]=='R' , then the result is 'Correct color in Right place' so change x & y to match.
    5.3.2. else if(answer.indexOf(guess[i])>=0) ; if the character at [i] in guess does not match the character at [i] in answer ie: guess[i]=='Y' && answer[i]=='R' , then answer.indexOf() checks answer to see if it contains the value guess[i] , if false it returns -1 , if true it returns the index of guess[i] . >=0 if the returned value (-1 or index ) is greater than or equal to 0 then guess[i] is present in answer so change x as the result is 'Correct color in Wrong place'.
    5.3.3. result.push(...) ; now x & y are modified to display correctly, append the display string to the end of the results array using .push() .
    5.4. displayDiv.innerText ; now the loop has finished, results contains a string for ever character in the users guess and you just need to display it in your display div .
    5.4.1. result.join('\\n') ; joins the results array together with '\\n' , before it displays as innerText ...

Need more help?! Try these:
http://www.w3schools.com/
https://developer.mozilla.org/en-US/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM