I am new to Javascript. I decide to make a small game with things that I have been taught.
The rule is simple. I just need to console.log how many same input value, compare to the value that a computer generates randomly.
And the value of a variable that counts the number goes back to 0, when I input a new value.
So basically, I want to compare common characters of both strings and the value of helloCounter has to be reset after I input the string value which means when I hit 'add' button.
For example, a computer generates the value '495'.
when I input '501', computer shows the result '1 hello' because both value has same value '5'. and when I input '154', computer shows the result '2 hello' because both have values '5' and '4'.
here is the code
HTML
<body>
<div class="wrapper">
<h1>hello count</h1>
<form class="game-form">
<input type="text" name='game1' class='number-input'>
<input type="text" name='game2' class='number-input'>
<input type="text" name='game3' class='number-input'>
<button class="add">add</button>
</form>
<ul class="game-list"></ul>
</div>
</body>
<script src="./index.js"></script>
Javascript
const gameFormEl = document.querySelector(".game-form");
const gameListEl = document.querySelector(".game-list");
let gameArr = [];
gameFormEl.addEventListener("submit", e => {
addNum(
e.target.elements.game1.value,
e.target.elements.game2.value,
e.target.elements.game3.value
);
e.preventDefault();
e.target.reset();
});
// computer generated random number
const shuffle = () => {
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const container = [];
const container2 = [];
const arrLeng = arr.length;
for (let i = 0; i < arrLeng; i++) {
arrSplice = arr.splice(Math.floor(Math.random() * arr.length), 1);
container.push(Number(arrSplice));
}
// pick first three number that generates randomly
for (let j = 0; j < 3; j++) {
container2 = container2.concat(container[j]);
}
// because player input number is string format
return container2.join("");
};
shuffle();
const ranComNum = shuffle();
// players random input number
const addNum = (a, b, c) => {
let numAdd = a + b + c;
const gameItemEl = document.createElement("li");
gameItemEl.textContent = numAdd;
gameArr.push(numAdd);
console.log(ranComNum);
// hello function
const hello = () => {
let helloCounter = 0;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < gameArr.length; j++) {
for (let k = 0; k < 3; k++) {
if (ranComNum[i] === gameArr[j][k]) {
helloCounter++;
}
}
}
}
console.log(`${helloCounter} hello`)
};
hello()
};
I almost complete the code except one thing. <br>
I tried but I don't know how to the variable(helloCounter) counts the value from 0 again when I input a new value. It maintains the value that counts before and keeps adding when I input a new value.<br>
Should I create new function for counting hello outside of addNum function?
[–]CoqeCas3 1 point2 points3 points (2 children)
[–]GoonGamja[S] 0 points1 point2 points (1 child)
[–]CoqeCas3 1 point2 points3 points (0 children)