Как я могу хранить и показывать данные в массиве одновременно? - PullRequest
1 голос
/ 30 апреля 2020

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

//here is the JS file

var a=[10];
let x=0;
function check()
{
    var num=Math.floor(Math.random()*5);
    var a= document.getElementById("inpt").value;
    if (num==a)
    {
        document.querySelector("#result").innerHTML="You are right in guess";
        a[x]=true;
    }
    else {
        document.querySelector("#result").innerHTML="You are Wrong in guess";
        a[x]=false;
    }}
if (a[x]==true)
{
    document.getElementById("finalize").innerHTML=x+1+": number turn is right";
}
else{
    document.getElementById("finalize").innerHTML=x+1+": number turn is wrong";
}
<!-- Here is the HTML file -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My gussing game</title>
    <script src="index.js"></script>
</head>
<body>
    <div style="width: 45%; float: left; background: gold; margin: 2px; text-align: center;">
        <H1>Game Input</H1>
        <hr>
        <input type="number" id="inpt" placeholder="Guess the number">
    <br>
    <button onclick="check()">Submit</button>
    <p id="result"></p>
    </div>
    <div style="width: 45%; float: left; background: rgb(42, 204, 177); margin: 2px; text-align: center;">
        <h1>Game Result</h1>
        <hr>
        <p id="finalize"></p>
    </div>    
</body>
</html>

Я не могу понять, почему мой код не работает !! не могли бы вы проинформировать меня обо всем?

Ответы [ 3 ]

0 голосов
/ 30 апреля 2020

Если вы отформатируете свой код, вы увидите, что поле, которое вы хотите обновить, находится за пределами функции check:

var a = [10];
let x = 0;

function check() {
    var num = Math.floor(Math.random() * 5);
    var a = document.getElementById("inpt").value;
    if (num == a) {
        document.querySelector("#result").innerHTML = "You are right in guess";
        a[x] = true;
    }
    else {
        document.querySelector("#result").innerHTML = "You are Wrong in guess";
        a[x] = false;
    }
}

if (a[x] == true) {
    document.getElementById("finalize").innerHTML = x + 1 + ": number turn is right";
}
else {
    document.getElementById("finalize").innerHTML = x + 1 + ": number turn is wrong";
}

Чтобы выполнять это действие каждый раз, когда вы отправляете предположение, вам необходимо переместить эти поля внутри этой функции:

var a = [10];
let x = 0;

function check() {
    var num = Math.floor(Math.random() * 5);
    var a = document.getElementById("inpt").value;
    if (num == a) {
        document.querySelector("#result").innerHTML = "You are right in guess";
        a[x] = true;
    }
    else {
        document.querySelector("#result").innerHTML = "You are Wrong in guess";
        a[x] = false;
    }

    if (a[x] == true) {
        document.getElementById("finalize").innerHTML = x + 1 + ": number turn is right";
    }
    else {
        document.getElementById("finalize").innerHTML = x + 1 + ": number turn is wrong";
    }
}
0 голосов
/ 30 апреля 2020

Вы хотите такого поведения? (Если это так, я сделаю комментарии в коде, чтобы объяснить)

Демо:

enter image description here

//here is the JS file

//array to hold each guess:
var guesses = [];
//number to hold current guess number (could also use guesses.length):
let x = 0;
//random number rounded to a whole number:
var num = Math.round(Math.floor(Math.random()*5),0);

function check(){    
    //for testing output the random num:
    console.log(num)
    if (x == 0){
      //rest our message log div:
      document.getElementById("finalize").innerHTML = ""
    }
    //get the current guess:
    var a = document.getElementById("inpt").value;
    //if guess equals random num:
    if (num==a){
        document.querySelector("#result").innerHTML="You are right in guess";
        //push the current guess onto the guesses array:
        guesses.push(a);
        //update the div (<div id="guessArr"></div>) to hold a stringified representation
        //of our array, such as ["1", "2", "3"] if the user guesses 1, then 2, then 3:
        document.querySelector("#guessArr").innerHTML = JSON.stringify(guesses);
        //create a p tag (<p></p>) to store our message
        var p = document.createElement('p')
        //add the message to that p tag:
        p.innerHTML = x+1+": number turn is right"
        //append it to the div:
        document.getElementById("finalize").appendChild(p)
        //reset our guess number/count:
        x = 0;
        //reset our guesses array:
        guesses = [];
        //reset our input field:
        document.getElementById("inpt").value = "";
        //generate a new random number to guess:
        num = Math.round(Math.floor(Math.random()*5),0);
    }
    //if guess was incorrect:
    else {        
        document.querySelector("#result").innerHTML="You are Wrong in guess";
        //push the current guess onto the guesses array:
        guesses.push(a);
        //update the div (<div id="guessArr"></div>) to hold a stringified representation
        //of our array, such as ["1", "2", "3"] if the user guesses 1, then 2, then 3:
        document.querySelector("#guessArr").innerHTML = JSON.stringify(guesses);
        //create a p tag (<p></p>) to store our message
        var p = document.createElement('p')
        //add the message to that p tag:
        p.innerHTML = x+1+": number turn is wrong"
        //append it to the div:
        document.getElementById("finalize").appendChild(p)
        //add one to our guess number/count:
        x += 1;
    }
}
<!-- Here is the HTML file -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My gussing game</title>
    <script src="index.js"></script>
</head>
<body>
    <div style="width: 45%; float: left; background: gold; margin: 2px; text-align: center;">
        <H1>Game Input</H1>
        <hr>
        <input type="number" id="inpt" placeholder="Guess the number">
    <br>
    <button onclick="check()">Submit</button>
    <p id="result"></p>
    </div>
    <div style="width: 45%; float: left; background: rgb(42, 204, 177); margin: 2px; text-align: center;">
        <h1>Game Result</h1>
        <hr>
        <div id="guessArr"></div>
        
        <div id="finalize">
        
        </div>
    </div>    
</body>
</html>
0 голосов
/ 30 апреля 2020

вы переопределяете переменную в функции проверки, поэтому назначение [x] для локальной переменной

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...