html javascript (game) how to retrieve value of button point is added when a button is clicked

孤街浪徒 提交于 2020-12-15 07:18:58

问题


i am creating a game. the game should work this way: when user click on the button with target option that was chosen previously from the dropdown list, score will +2, else -1.

however, the code i have now is not working, the score is not adding, its always 0. i am guessing it is because i didn't retrieve the value of the button correctly, hence, the value of the button chosen and target option value never match. how can i solve this issue??

background information: the 3 options will refresh every 1/2/3 seconds depending on the difficulty level chosen. hence, the option will always be different, there will also be situation where none of the 3 options is the target option. user can choose to wait for 1/2/3 seconds OR click on any of the option and receive a -1 point.

here is my code for the part where the score is calculated

document.getElementById("TO1").addEventListener("click", clickScore);
        document.getElementById("TO2").addEventListener("click", clickScore);
        document.getElementById("TO3").addEventListener("click", clickScore);
        
        //score system
        function clickScore() {
            //when one option is clicked , all 3 options will change value
           var option1 = document.getElementById("TO1").value;
           var option2 = document.getElementById("TO2").value;
           var option3 = document.getElementById("TO3").value;
                
                var btn1 = document.getElementById("TO1");
                var btn2 = document.getElementById("TO2");
                var btn3 = document.getElementById("TO3");
            
            if (btn1.clicked && option1.hasAttribute(targetValue) == true ){
                    
                score = parseInt(document.getElementById("score").innerHTML);
                
                    score += 2;
                    //random10Opt;
  
                } 
                else if (btn1.clicked && option1.hasAttribute(targetValue) == false)
                {
                    score -=1;
                    //random10Opt;
                }
                
                if (btn2.clicked && option2.hasAttribute(targetValue) == true ){
                    
                score = parseInt(document.getElementById("score").innerHTML);
                
                    score += 2;
                    //random10Opt;
                    
                } 
                else if (btn2.clicked && option2.hasAttribute(targetValue) == false)
                {
                    score -= 1;
                    //random10Opt;
                }    
            
                if (btn3.clicked && option3.hasAttribute(targetValue) == true ){
                    
                score = parseInt(document.getElementById("score").innerHTML);
                
                    score += 2;
                    //random10Opt;
                    
                } else if (btn3.clicked && option3.hasAttribute(targetValue) == false)
                {
                    score -= 1;
                    //random10Opt;
                }
                
           document.getElementById("score").innerHTML = score; 
           

        }; //end of click

here is the entire code i have

<!DOCTYPE html>

<html>

    <body>
        <div>

                
                <form name="start" id="start">
                    
                    <table id="T">
                        <tr id="Ttitle"> <!-- Header -->
                            <th colspan="3"><h2>Assignment 3 Part 2: Game</h2></th>
                        </tr>

                        <tr id="Tplayer"> <!-- ROW 1 PLAYER NAME-->
                            <th>Player Name</th>
                            <td><!-- text box for Unique name -->
                                <input type="text" id="name" name="required name" placeholder="Enter your Name"><br> 
                                <span style="color:red;" id="nameError"></span>
                            </td> 

                            <td id="TS" rowspan="3"> <!-- TIMER AND SCORE -->
                                <h3>Time: </h3>
                                <div class="timeScore" ><span id="seconds">00</span>:<span id="tens">00</span> second(s)</div>
                                <h3>Score: </h3>
                                <div class="timeScore" ><span id="score">0</span></div> 
                            </td> <!-- Time and Score -->
                        </tr>

                        <tr id="Ttarget"> <!-- ROW 2 TARGET OPTION-->
                            <th>The Target Option: </th>
                            <td> <!-- list box with all option -->
                                <select name="target_Opt" id="target_Opt">
                                     <option value="">Choose your Target</option>                                
                                </select>
                                <span style="color:red;" id="TargetError"></span>
                            </td> 
                        </tr>

                        <tr id="Tdifficulty"> <!-- ROW 3 DIFFICULTY LEVEL-->
                            <th>The Difficulty Level: </th>
                            <td id="radio"> <!-- Radio button Low, Med, High -->
                                
                                <input type="radio" id="Low" name="difficulty" value="low" checked>
                                Low
                                
                                <input type="radio" id="Medium" name="difficulty" value="med">
                                Medium

                                <input type="radio" id="High" name="difficulty" value="high">
                                High
                                
                            </td> 
                        </tr>

                        <tr id="Tbutton"> <!-- ROW 4 START STOP Button-->
                            <td colspan="3">
                                <input type="button" id="startBtn" 
                                value="Start" >
                                
                                <input type="button" id="stopBtn"  value="Stop" >
                            </td>
                        </tr>

                        <tr id="Toptions"> <!-- ROW 5 CLICK Options -->
                            <td class="Opt">
                         
                                <input type="button" class="gameOpt" id="TO1" value="Option 1" >
                            </td>
                            <td class="Opt">
                                
                                <input type="button" class="gameOpt" id="TO2" value="Option 2" >
                            </td>
                            <td class="Opt">
                                
                                <input type="button" class="gameOpt" id="TO3" value="Option 3" >
                            </td>
                        </tr>
                                
                    </table>
                    
                    <div id="Tlist" >
                        <h4> Player Listing : </h4>
                        <ul id="myList">

                        </ul>
                    </div>    
            </form> <!--END OF FORM WHEN START IS CLICKED  --> 
        
        </div>
    </body>
    <script> 
        var score = 0; //for score
        
        var pn = []; //Array to contain PlayerName
        var ten = []; //Array for 10 Random Options
        
        var a = document.forms["start"]["name"].value; //get Player's name input
        var targetValue = document.getElementById("target_Opt").value; //selected target

        //ARRAY OF OPTIONS TO CHOOSE TARGET
        var Opt123 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
        var OptABC = ["A", "B", "C", "D", "E", "F", "G",
                     "H", "I", "J", "K", "L", "M", "O", 
                     "P", "Q", "R", "S", "T", "U", "V",
                     "W", "X", "Y", "Z"];
        

        
        //add options into dropdown list
        function PrepopulateOpt() {
                
                var selectTarget = document.getElementById("target_Opt");
                var i = 1;
                        //add Opt123 into dropdown list
                            for (var target_Opt in Opt123) {
                              selectTarget.options[i++] = new Option(target_Opt);
                            }
                        
                        //add OptABC into dropdown list
                            for (var i = 0; i < OptABC.length; i++) {
                                var opt = OptABC[i];
                                var el = document.createElement("option");
                                el.textContent = opt;
                                el.value = opt;
                                selectTarget.appendChild(el);
                              }
        }
        PrepopulateOpt();

       
        window.onload = function () {
            var seconds = 00; 
            var tens = 00 ; 
            var appendTens = document.getElementById("tens");
            var appendSeconds = document.getElementById("seconds");
            var buttonStart = document.getElementById('startBtn');
            var buttonStop = document.getElementById('stopBtn');
            var Interval ;
            
            var optionButton = document.getElementsByClassName('gameOpt'); //the options
            //var changeOpt = document.getElementsByClassName("gameOpt").value; //option value
            
    function ValidateEvent(){
        var name = document.getElementById("name").value;
        var target = document.getElementById("target_Opt").value;

            //CHECK IF PLAYER NAME IS UNIQUE  

                    if (name == null || name.trim() == "")
                    {
                        alert("Please enter your name");
                        return false;
                        
                    } else if (pn.includes(name) == true){
                        alert("Please enter a unique name");
                        return false;
                    } 

        //CHECK IF TARGET IS SELECTED
    
                    if (target == "")
                    {
                            alert("Please select a target!") ;
                            return false;
                    }
                    else
                        {
                            document.getElementById("TargetError").value = "";
                        }  
    return true;                   
}

/*        function removeDuplicates(data){
            return data.filter((value, index) => data.indexOf(value) === index);
        }
        
*/         
        function random10Opt(){
        
        //targetValue = selected target value;
        var target = document.getElementById("target_Opt").value;
        //var target123 = parseInt(document.getElementById("target_Opt").value);
        var index;
       
        const newArr = [];

                if (Opt123.includes(target) == true){

                    index = Opt123.indexOf(target);
                    Opt123.splice(index, 1);

                return Opt123;    
                    
                } else if (OptABC.includes(target) == true){
                    
                    index = OptABC.indexOf(target);
                    OptABC.splice(index, 1);
                
                return OptABC;
                }

        const a = Opt123.slice();
        const b = OptABC.slice();
        
                //select random 5 from digit add into newArr
                for(let i= 5; i >= 0; i--){
                    let arr = a[Math.floor(Math.random()*a.length)];

                    let index = a.indexOf(arr);

                    a.splice(index, 1 );

                    newArr.push(arr);
  
                }
                
                for(let i= 5; i >= 0; i--){
                    let arr = b[Math.floor(Math.random()*b.length)];

                    let index = b.indexOf(arr);

                    b.splice(index, 1 );

                    newArr.push(arr);
  
                }
                
                 newArr.push(target); //new array with randomized values : newArr
                 

        
        //enter random element into Option 1
        var index1 = newArr[Math.floor(Math.random()*newArr.length)];
        document.getElementById("TO1").value = index1;
        var Arr2 = newArr.splice(index1, 1);
        
        //enter random element into Option 2
        var index2 = newArr[Math.floor(Math.random()*newArr.length)];
        document.getElementById("TO2").value = index2;
        var Arr3 = newArr.splice(index2, 1);
        
        //enter random element into Option 3
        var index3 = newArr[Math.floor(Math.random()*newArr.length)];
        document.getElementById("TO3").value = index3;

        console.log(newArr)
        } //end of random10Opt
       

        function difficultylvl() {
            //TIME INTERVAL ACCORDING TO DIFFICULTY LEVEL

                         if (document.getElementById("Low").checked){

                            myVar =  setInterval(random10Opt, 3000);

                        } else if (document.getElementById("Medium").checked){

                            myVar = setInterval(random10Opt, 2000);

                        } else {

                           myVar =  setInterval(random10Opt, 1000);
                        } 
      
        } //end of difficulty level
       

        //stop timeInterval for difficulty level
        function stopInterval() {
            clearInterval(myVar);
        }
        
        document.getElementById("TO1").addEventListener("click", clickScore);
        document.getElementById("TO2").addEventListener("click", clickScore);
        document.getElementById("TO3").addEventListener("click", clickScore);
        
        //score system
        function clickScore() {
            //when one option is clicked , all 3 options will change value
           var option1 = document.getElementById("TO1").value;
           var option2 = document.getElementById("TO2").value;
           var option3 = document.getElementById("TO3").value;
                
                var btn1 = document.getElementById("TO1");
                var btn2 = document.getElementById("TO2");
                var btn3 = document.getElementById("TO3");
            
            if (btn1.clicked && option1.hasAttribute(targetValue) == true ){
                    
                score = parseInt(document.getElementById("score").innerHTML);
                
                    score += 2;
                    //random10Opt;
  
                } 
                else if (btn1.clicked && option1.hasAttribute(targetValue) == false)
                {
                    score -=1;
                    //random10Opt;
                }
                
                if (btn2.clicked && option2.hasAttribute(targetValue) == true ){
                    
                score = parseInt(document.getElementById("score").innerHTML);
                
                    score += 2;
                    //random10Opt;
                    
                } 
                else if (btn2.clicked && option2.hasAttribute(targetValue) == false)
                {
                    score -= 1;
                    //random10Opt;
                }    
            
                if (btn3.clicked && option3.hasAttribute(targetValue) == true ){
                    
                score = parseInt(document.getElementById("score").innerHTML);
                
                    score += 2;
                    //random10Opt;
                    
                } else if (btn3.clicked && option3.hasAttribute(targetValue) == false)
                {
                    score -= 1;
                    //random10Opt;
                }
                
           document.getElementById("score").innerHTML = score; 
           

        }; //end of click
 

    buttonStart.onclick = function() {

        if( ValidateEvent() == true) {
                //checkform();        //check name and target
            random10Opt();      //add random value into button
            difficultylvl();    //setInterval 
            addName();          //add player name into list
            
            if (seconds == 00 && tens == 00){
                clearInterval(Interval);
                Interval = setInterval(startTimer, 10);
            } else {
                clearInterval(Interval);
                    tens = "00";
                    seconds = "00";
                    appendTens.innerHTML = tens;
                    appendSeconds.innerHTML = seconds;
                clearInterval(Interval);
                Interval = setInterval(startTimer, 10); 

            }        
        }
    };
       
    buttonStop.onclick = function() {
           clearInterval(Interval); //stop stopwatch
           stopInterval();          //stop setInterval for options
           
           //default value when the game stop
           document.getElementById("TO1").value = "Option 1";
           document.getElementById("TO2").value = "Option 2";
           document.getElementById("TO3").value = "Option 3";
           
           
    };
    
    optionButton.onclick = function() {
           clickScore(); //click the options for score
    };
    
     
        //stopwatch
        function startTimer() {
             tens++; 
    
                if(tens < 9){
                  appendTens.innerHTML = "0" + tens;
                }

                if (tens > 9){
                  appendTens.innerHTML = tens;

                } 

                if (tens > 99) {
                  console.log("seconds");
                  seconds++;
                  appendSeconds.innerHTML = "0" + seconds;
                  tens = 0;
                  appendTens.innerHTML = "0" + 0;
                }

                if (seconds > 9){
                  appendSeconds.innerHTML = seconds;
                }
  
        }//end of startTimer()
        
        function addName(){ 
            
            //takes the value of player name             
            //pn is an empty array to contain to names 
            var newArray = document.getElementById("name").value;
            pn.push(newArray);
            
            var node = document.createElement("LI");
            var textnode = document.createTextNode(newArray);
         
                node.appendChild(textnode);
                document.getElementById("myList").appendChild(node);  
        } //end of addName function
        

};//end on onload
    
    </script>
</html>

回答1:


you have registered the click-event twice. just removed the onclick in the input

  ...
  <input type="button" class="gameOpt" id="TO1" value="Option 1">
  ...
  <input type="button" class="gameOpt" id="TO2" value="Option 2">
  ...
  <input type="button" class="gameOpt" id="TO3" value="Option 3">
</td>
...
<script>
  document.getElementById("TO1").addEventListener("click", clickScore);
  document.getElementById("TO2").addEventListener("click", clickScore);
  document.getElementById("TO3").addEventListener("click", clickScore);



回答2:


Have a look at the snippet below, which I think illustrates what you're trying to accomplish.

Your buttons will be randomized at the outset. Then you can choose the "target value" from the drop-down, and clicking the button w/the value that matches your selected "target value" will add points, whereas clicking a button that doesn't match the target value will subtract points.

Note how much simpler it becomes to attach the click event handler in a way that allows you to read the event target's value.

var score = 0;
var newArr = [1, 2, 3, 4, 5, "A", "B", "C", "D", "E"];
let scoreOutput = document.getElementById("scoreUpdate");
const gameButtons = document.querySelectorAll(".gameOpt");

//this code just creates the select dropdown, which you don't need to do
var select = document.getElementById("targetValue");
for (var i = 0; i < newArr.length; i++) {
  var opt = newArr[i];
  var el = document.createElement("option");
  el.textContent = opt;
  el.value = opt;
  select.appendChild(el);
}

randomizeButtonValues();

//attach the click for each button
[...gameButtons].forEach((btn) => {
  btn.addEventListener("click", (e) => {
     let correctValue = document.getElementById("targetValue").value;
     let clickedValue = e.target.value;  // <-- capture value of clicked element
     console.log(correctValue, clickedValue);
     if(correctValue == clickedValue) {
        score += 2;
     } else {
        score -= 1;
     }
     scoreOutput.innerHTML += `<br>New Score: ${score}`;
     randomizeButtonValues();
  });
});

function randomizeButtonValues() {
  [...gameButtons].forEach((btn) => {
    let rnd = Math.floor(Math.random() * newArr.length);
    btn.value = newArr[rnd];
  });
}
<select id="targetValue">
  <option>Choose target value</option>
</select>

<input type="button" class="gameOpt" id="TO1" value="Option 1">
<input type="button" class="gameOpt" id="TO2" value="Option 2">
<input type="button" class="gameOpt" id="TO3" value="Option 3">

<br>
<div id="scoreUpdate"></div>


来源:https://stackoverflow.com/questions/64766735/html-javascript-game-how-to-retrieve-value-of-button-point-is-added-when-a-but

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!