executing the wrong function in if statement - javascript

/*
GAME FUNCTION:
- player must guess a number beetween min and max
- player gets a certain amount of guesses
- notify player of guesses remaining
- notify the player with a correct number if he loose
- let player choose to play again
*/
// variabels
//game values
let min = 1,
max = 10,
winningNum = 2,
guessesLeft = 3;
// UI elements
const game = document.getElementById('game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessBtn = document.getElementById('guess-btn'),
guessInput = document.getElementById('guess-input'),
message = document.querySelector('.message');
// assign ui min and max
minNum.textContent = min;
maxNum.textContent = max;
// event listener
function loadEventListener() {
// listen for guess
guessBtn.addEventListener('click' , checkGuess );
};
loadEventListener();
// checks the entered number
function checkGuess() {
let guess = parseInt(guessInput.value);
//validate the input
if(isNaN(guess) || guess < min || guess > max ) {
console.log('here')
/////// this below code setMessage is not executing when the condintions are true.. ////
setMessage(`Please enter a number between ${min} and ${max}` , 'red');
console.log('here again')
};
//check if won
if(guess === winningNum) {
// right case here
//dsiabe input
guessInput.disabled = true;
// change border color
guessInput.style.borderColor = 'green';
// set message
setMessage(`${winningNum} is correct.. you WON the game!!` , 'green');
} else {
// wrong case here
guessesLeft -= 1;
if(guessesLeft === 0) {
// game over - lost
// disable input
guessInput.disabled = true;
// change border color
guessInput.style.borderColor = 'red';
// set message
setMessage(`Game over..! The correct Number was ${winningNum}..` , 'red');
} else {
// game continues - answer wrong
// change border color
guessInput.style.borderColor = 'red';
// clear input
guessInput.value = '';
// tell user its the number
setMessage(`${guess} is not Correct,${guessesLeft} guesses left.` , 'orange')
};
}
};
// set message
function setMessage(msg , color) {
message.style.color = color;
message.textContent = msg;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css" />
<title>Number Guesser</title>
</head>
<body>
<div class="container">
<h1>Number Guesser</h1>
<div id="game">
<p>Guess a number beetween
<span class="min-num"></span>
and
<span class="max-num"></span>
</p>
<input type="number" name="" id="guess-input" placeholder="Enter Your Guess...">
<input type="submit" value="submit" id="guess-btn">
<p class="message"></p>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
when i click on the submit button without entering the values, the function in line 49 setMessage should execute, but its executing the code of 82nd line.., it should display the message (message placed in the argument) in 49th line code but its showing message from 82nd line.. please look at the issue..what else is wrong in the code???

Your problem is that you don't exit the checkGuess() function when it fails validation.
If you add a return; after the failed validation error is shown then it will solve your issue...
function checkGuess() {
let guess = parseInt(guessInput.value);
//validate the input
if(isNaN(guess) || guess < min || guess > max ) {
setMessage(`Please enter a number between ${min} and ${max}` , 'red');
return; // exit the function here, since we've failed validation
};

Related

Why isn't the input box outputting the correct response

When the user clicks the buttons I want it to output the correct response.If the user puts 0 in the input box and then clicks the button I want it to say this is zero.If it 1 and higher I want it to say it positive number.If it -1 and lower it should say this is negative number.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>numberCheck</title>
<style>
body{
text-align: center;
}
</style>
</head>
<body>
<h1>Number Check</h1>
<input type="number" id="num">
<button id="submit">Submit</button>
<div id="store"></div>
<script>
const num = document.getElementById('num');
const data = num.value
const btn = document.getElementById('submit');
const store = document.getElementById('store');
btn.addEventListener('click',()=>{
checker();
});
function checker(){
const ele = document.createElement('div');
if (data === 0){
ele.innerHTML =data+' this is a zero';
store.appendChild(ele);
}
if (data <0){
ele.innerHTML =data+' this is a negitive number';
store.appendChild(ele);
}
if (data >0){
ele.innerHTML =data+' this is a positive number';
store.appendChild(ele);
}
}
</script>
</body>
</html>
> const ele = document.createElement('div');
> if (num === 0){
> ele.innerHTML =num+' this is a zero';
> store.appendChild(ele);
> }
You try to refer to the HTML element and compare it to zero. It's not. What you have to do is to check if the value of the input matches to your condition.
if (num.value == 0)
By the way, don't use triple equals here. The input value is always a string, but you compare it against a number, so "===" will always return a false here. Either explicitly convert input's value to a type of number or use double equals.
So first do not repeat yourself, if you want to create a new div and append it i'll recommend u to do it once in your function.
const ele = document.createElement('div');
store.appendChild(ele);
and because you are using input type number u have to get the value as integrer with valueAsNumber.
Then you have to update the value, yes because the value change while u are loading the value but never updating it.
By the way for a changing value u can't use const but need to use a let or var.
btn.addEventListener('click', function() {
let val = num.valueAsNumber;
checker(val);
});
Here is a working version of your code : https://jsfiddle.net/4a17fsbn/
You write far too much code and your code is inefficient.
The main issue is, that the value of an input type="number"is not necessarily an integer. As soon as you write into the input with a keyboard then you get a string. To solve this you simply need to add a + before the string which converts it to an integer: +document.querySelector('#num').value.
As said above, your code is inefficient. One efficiency boost you can gain with textContent instead of using innerHTML which requires a re-parsing of the DOM. Then only write the actual necessary code and combine the eventListener with the function directly.
document.querySelector('#submit').addEventListener('click', function() {
let nr = +document.querySelector('#num').value,
el = document.querySelector('#store');
if (nr === 0) {
el.textContent = `${nr} this is a zero`;
}
if (nr < 0) {
el.textContent = `${nr} this is a negative number`;
}
if (nr > 0) {
el.textContent = `${nr} this is a positive number`;
}
})
<h1>Number Check</h1>
<input type="number" id="num">
<button id="submit">Submit</button>
<div id="store"></div>
you can use change event and get the value as per entered by the user
const inputField = document.getElementById("num");
let num = 0;
inputField.addEventListener("change", (e) => {
num = +e.target.value;
});
btn.addEventListener("click", () => {
checker(num);
});
function checker(num) {
const ele = document.createElement("div");
console.log(num);
if (num === 0) {
ele.innerHTML = num + " this is a zero";
store.appendChild(ele);
}
if (num < 0) {
ele.innerHTML = num + " this is a negitive number";
store.appendChild(ele);
}
if (num > 0) {
ele.innerHTML = num + " this is a positive number";
store.appendChild(ele);
}
}
or you can more simplify the code
btn.addEventListener("click", () => {
checker(+inputField.value);
});

Set a 10-second timer for each subject input

I've been making a typing game at school. The time setting does not work.
A time limit of 10 seconds is attached to each subject. When one subject is finished, the time will be reset to 10 seconds again.Please give me some advice.
1,The user sees the subject text, types the same value into the text box, and presses the OK button.
2,When the OK button is pressed, clear the text box and display the next subject.
3,Repeat steps 1 and 2 5 times.
4,When the ok button is pressed the 5th time, the total number of characters from the 1st to the 5th times, in which the subject and the value entered by the user are incorrect, is displayed on the screen.
⚠️If the OK button is not pressed within 10 seconds, it is an error for the number of characters in the subject.
I left some clarifications as code comments
const subject = document.getElementById("subject");
const timer = document.getElementById("timer");
const input = document.getElementById("text");
const questionList = [
{ text: "Hello", pronunciation: "Hello" },
{ text: "World", pronunciation: "World" },
{ text: "HTML", pronunciation: "HTML" },
{ text: "CSS", pronunciation: "CSS" },
{ text: "PHP", pronunciation: "PHP" },
];
var question =
questionList[Math.floor(Math.random() * questionList.length)];
subject.textContent = question["text"];
var TIME = 10;
var index = 0;
var CorrectCount = 0;
var missTypeCount = 0;
var state;
const countdown = setInterval(function () {
if (TIME > 0) {
timer.textContent = "Time limit:" + --TIME;
}
if (TIME === 0) {
finish();
}
}, 1000);
document.addEventListener("keypress", function(e) {
if (e.key === question["pronunciation"].charAt(index) ) {
index++;
if (index == question["pronunciation"].length ) {
// Here is where a full correct word was completely written.
// Normally here is where you want to increment CorrectCount++ and reset TIME = 10
// However this is redundant, because you are performing these actions on check()
// I would advice to either keep this conditional, or the check() function, not both
CorrectCount;
}
} else {
missTypeCount++;
e.preventDefault();
}
});
function check() {
if(input.value === subject.textContent ) {
CorrectCount++;
init();
}
if (CorrectCount >= 5 ) {
finish();
}
}
function init() {
question =
questionList[Math.floor(Math.random() * questionList.length)];
subject.textContent = question["text"];
index = 0;
input.value = '';
input.focus();
// You need to set/reset the time to 10 here
TIME = 10;
}
function finish() {
clearInterval(countdown);
if (missTypeCount >= 0 ){
subject.textContent="Perfect"
}
// these conditionals are not doing what you want them to do.
// I believe you mean missTypeCount >= 1 && missTypeCount <= 3
if (missTypeCount >= 1 || missTypeCount >= 3 ){
subject.textContent="Good"
}
if (missTypeCount >= 4 || missTypeCount >= 8 ){
subject.textContent="Almost"
}
if (missTypeCount >= 9 ){
subject.textContent="Bad"
}
}
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="../css/test.css">
</head>
<body>
<div>
<div class="subject"><h1 id="subject"></h1></div>
<form name="typing" onsubmit="return false;">
<div class="text">
<input id="text" type="text" autocomplete="off" >
</div>
<div class="btn">
<input type="submit" value="ok" onclick="check();" >
</div>
</form>
<div class="timer">
<p id="timer">Time limit :10</p>
</div>
</div>
<script type="text/javascript" src="../js/test.js"></script>
</body>
</html>
You need to reset the TIME in your init function:
function init() {
question =
questionList[Math.floor(Math.random() * questionList.length)];
subject.textContent = question["text"];
index = 0;
TIME = 10;
input.value = '';
input.focus();
}
Otherwise the time will just keep on running.
Here is a fiddle to try it out.
But you have several other issues: When you misspelled and try to correct yourself within the time, you can not do this. The input is blocked. And you should set the cursor inside of your input when you load the page, or only start the timer when somebody starts typing. otherwise it is really hard to do it in time.
Use the php function time() or try something like that
<script>
var myVar;
var timer = document.getElementById("userInput");
var countDownSeconds;
function startTime(){
myVar = setInterval(start, 1000);
document.getElementById("timerr").innerHTML = timer.value;
countDownSeconds = timer.value;
}
function start(){
countDownSeconds--;
document.getElementById("timerr").innerHTML = countDownSeconds;
if (countDownSeconds == -1){
stop();
document.getElementById("timerr").innerHTML = "0";
}
}
function stop(){
clearInterval(myVar);
}
</script>

How can I use JavaScript to grab a random div?

I'm using JavaScript to create a grid. What I'm trying to do is have a random box that is created change colors when I click on the "Play" button but I cannot seem to get it figured out.
I've tried using various amounts of Math.random(), this might be where my problem is.
const container = document.getElementById('container');
const gameButton = document.createElement('button');
// This is the button I'm trying to use for this.
gameButton.addEventListener('click', function (event) {
let getRandom = document.getElementsByTagName('div');
});
let userInput = prompt('Enter a number between 10-20: ');
if (isNaN(userInput)) {
alert('Numbers only.');
location.reload();
} else if (userInput < 10) {
alert('That\'s less than 10');
location.reload();
} else if (userInput > 20) {
alert('That\'s greater than 20');
location.reload();
} else {
gameButton.textContent = 'Play';
gameButton.style.height = '25px';
gameButton.style.width = '50px';
gameButton.style.borderRadius = '7px';
gameButton.style.marginBottom = '15px';
container.appendChild(gameButton);
}
for (let index = 1; index <= userInput; index++) {
let gameBoard = document.createElement('div');
gameBoard.setAttribute('class', 'game-board');
container.appendChild(gameBoard);
for (let j = 0; j < userInput; j++) {
const square = document.createElement('div');
square.setAttribute('class', 'square');
gameBoard.appendChild(square);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<div id="container">
</div>
<!---<script src="./app.js"></script>--->
</body>
</html>
Expected result is one of the 'divs' changes color when the button is clicked on.
Between your question and your code, it's a little confusing. But just going off what you said, here's a way to choose a random element from a list of elements, provided you give it a class name (feel free to tweak this):
// Function to get a random number, taking in min and max values.
const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)
// Function that takes in a class name to select all those elements
// on the page, and returns a random one from the list.
const getRandomElement = className => {
const elements = document.querySelectorAll(`.${className}`)
const num = randomNum(0, elements.length - 1)
return elements[num]
}
You could change the code in your event listener like this:
gameButton.addEventListener('click', function (event) {
let divs = document.getElementsByClassName('game-board');
let random_div = divs[Math.floor(Math.random()*divs.length)];
random_div.style.backgroundColor = 'red';
});
Or if you want only one square to change color, use document.getElementsByClassName('square') instead.
Relevante part o the code. You can make it better checking the elements, the styles, etc. But essentially it is:
gameButton.addEventListener('click', function (event) {
let getRandom = document.getElementsByTagName('div');
var a = Math.random()
let b = a.toString().substr(2, 1)
getRandom[b].style = 'background-color: ' + (parseInt(b) % 2 == 0 ? 'yellow' : 'red')
});
So you use Math.Random to get some random number after the dot(.) and use it to read some index from the collection you get for the getRandom.
Then you just set element style or whatever you want.
The fiddle: https://jsfiddle.net/cm5kyrdj/

how do I keep track of player's turn in game?

I have created a game that will display the winner with the highest score on the screen. There are two buttons for players one and two. Users will play game to a set score. For example, if the game is set to 5, the user will click both buttons until button one or button two reach the winning score of 5. The header may display "congratulations Player 1 win score of 5 to 4". Players should not be able to keep clicking one button to reach the winning score of 5. However, how do I keep track of player's turn in game? Below is the code:
score.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>score</title>
<link rel="stylesheet" href="score.css">
</head>
<body>
<h1> <span id="p1Display" > <span id="player1Win"></span> 0</span> to <span id="p2Display">0</span></h1>
<p>Play to: <span>5</span> </p>
<input type="number">
<button id="p1">Player one</button>
<button id="p2">Player two</button>
<button id="reset">Reset</button>
<script src="score.js"></script>
</body>
</html>
score.js file:
p1Button.addEventListener("click", function () {
if (!gameOver) {
if(turnTacker == 0) {
turnTacker = 1;
p1Score++;
}else {
turnTacker = 0;
p2Score++;
}
if (p1Score === winningscore) {
p1Display.classList.add("winner");
gameOver = true; //stop adding to score
}
p1Display.textContent = p1Score;
if (gameOver ) {
p1Display.textContent = `congratulations Player 1 win score of ${p1Score}`;
}
}
});
p2Button.addEventListener("click", function () {
if (!gameOver) {
if(turnTacker == 0) {
turnTacker = 1;
p2Score++;
}else {
turnTacker = 0;
p1Score++;
}
if (p2Score === winningscore) {
p2Display.classList.add("winner");
gameOver = true; //stop adding to score
}
p2Display.textContent = p2Score;
if (gameOver ) {
p2Display.textContent = `congratulations Player 2 win score of ${p2Score}`;
}
}
});
resetButton.addEventListener("click", function () {
reset(); //function to start over
p1Score = 0; //set player score back to 0
p2Score = 0;
//update score on html page to 0
p1Display.textContent = 0;
p2Display.textContent = 0;
//remove winner class from both p1 &p2
p1Display.classList.remove("winner");
p2Display.classList.remove("winner");
gameOver = false;
});
//start game over/reset to 0
function reset() {
p1Score = 0; //set player score back to 0
p2Score = 0;
//update score on html page to 0
p1Display.textContent = 0;
p2Display.textContent = 0;
//remove winner class from both p1 &p2
p1Display.classList.remove("winner");
p2Display.classList.remove("winner");
gameOver = false;
}
numInput.addEventListener("change", function () {
// winningscoreDisplay.textContent = numInput.value; //update winng score get value from text field
winningscoreDisplay.textContent = this.value; //update winng score get value from text field
winningscore = Number(this.value); //get and set value in textfield. Turn into number
//winningscore = Number(numInput.value); //get and set value in textfield. Turn into number
reset();//once input number run reset
});
For two players you will need a toggle. This can be a value from a hidden field in the page DOM, or just a JS variable as long as the page is not refreshed. Or to take it a step further you can keep track of turns on a server, yet this sounds too advanced for now.
A toggle can be based on an even/odd calculation, or just an if statement. something like:
if(turn==0){turn=1}else{turn=0}
the above line is like an on/off switch, is the turn off, player1 can play, and his/her action will turn it on. When the switch is on player2 can play and his/her action will turn it off again.
or if you have more than two players
turn++; // before turn increase by 1 each time
// do everything here for the current player
if(turn >= countPlayers()){turn=0} // reset to 0 after the last player
in this concept there is no value 0 as we start at 1 with the ++ before the first turn, then increase the turn each time a player did something until the total count of players have played and then reset back to 0.
The even/odd calculation is a simple alternative for a toggle if you have just two players. Since you are already keeping track of the total rounds played, there is no need for an extra variable.
function checkOdd(int){
return int % 2;
}
if(checkOdd(turnTacker)){
// player2 has to play
}else{
// player1 has to play
};
If turnTacker is 0 checkOdd is FALSE, if turnTacker is 1 checkOdd is TRUE, if turnTacker is 2 checkOdd is FALSE, and so on.
What you should do is add another variable which says whose turn it is.
For example:
var p1turn = true;
while (i < //a certain number of turns) {
if (p1turn) {
//something player 1 does
p1turn = false;
i++;
}
else {
//something player 2 does
p1turn = true;
i++;
}
}
Hope this helps!

javascript: Using functions and global variables in an anonymous function(addEventListener)

So i did a exercise on Udemy that requires me to create a score keeper application.
"Playing to : 5" indicates the winning score
The input field changes the winning score
The player 1 button increases the score on the left. When it reaches the winning score, the value changes to green and the game is over.
The player 2 button increases the score on the right. When it reaches the winning score, the value changes to green and the game is over.
Reset button resets the game and starts from 0 for both players.
If the winning scored is changed halfway during a game (i.e. the scores are not 0), the scores will be reset to 0 and the "playing to:" value will change according to what was typed in the input field.
THE PROBLEM: I created a function declaration (called incremenet() )that will be able to perform the similar task of increasing the scores of player 1 and player 2. It takes in 1 argument, which would be the score of the player (p1Score or p2Score).
I tried this function on player 1 but the score does not go past 1!
I suspect that this has something to do with the scopes or hoisting/execution stacks. Using console.log, p1Score never updates. It is always 0. Hence p1ScoreDisplay is always going to be 1
On top of that, i notice that an error will also occur when p1Score reaches the winning score. To make the score increase past 1, i just placed "p1Score++" before the increment() function call in the event listener. It will state "scoreToIncrement.classList" is undefined. This should add a class of ".winner" to the score. I believe this has something to do with scoping or hoisting as well.
My understanding is that since this increment function is nested within the event listener anonymous function, the increment function should still be able to call the global variable I have declared at the beginning and update them accordingly after the function is executed. But i guess my understanding is not 100% right here.
Hopefully someone can further explain the error and correct my understanding here. Thanks! Will try to continue troubleshooting and read up (not sure if closures have anything to do with it).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Score Keeper</title>
<style>
.winner {
color: green;
}
</style>
<body>
<h1><span id="h1p1Score">0</span> to <span id="h1p2Score">0</span></h1>
<p>Playing to: <span id="winningScore">5</span></p>
<input type="number" id="inputNum" placeholder="enter max playing number">
<button id="P1">Player One</button>
<button id="P2">Player Two</button>
<button id="Reset">Reset</button>
<script src="scoreKeeper.js"></script>
</body>
</html>
Below here is the javascript
var p1Button = document.querySelector("#P1");
var p2Button = document.querySelector("#P2");
var resetButton = document.querySelector("#Reset");
var p1ScoreDisplay = document.querySelector("#h1p1Score");
var p2ScoreDisplay = document.querySelector("#h1p2Score");
var inputValue = document.querySelector("#inputNum");
var p1Score = 0;
var p2Score = 0;
var gameOver = false;
var winningScore = 5;
var displayWinningScore = document.querySelector("#winningScore");
function increment(scoreToIncrement,scoreDisplay) {
if (!gameOver) {
scoreToIncrement++;
if (scoreToIncrement === winningScore) {
scoreToIncrement.classList.add("winner");
gameOver = true;
}
scoreDisplay.textContent = scoreToIncrement;
}
}
p1Button.addEventListener("click", function () {
increment(p1Score);
/* This is the original code i have commented out and replaced with the increment function above
if (!gameOver) {
p1Score++;
if (p1Score === winningScore) {
console.log("Game Over!");
p1ScoreDisplay.classList.add("winner");
gameOver = true;
}
p1ScoreDisplay.textContent = p1Score;
}
*/
});
p2Button.addEventListener("click", function () {
/*Same function as the one above but using variables related to player 2 instead*/
if (!gameOver) {
p2Score++;
if (p2Score === winningScore) {
console.log("Game Over!");
p2ScoreDisplay.classList.add("winner");
gameOver = true;
}
p2ScoreDisplay.textContent = p2Score;
}
});
function reset() {
p1Score = 0;
p1ScoreDisplay.textContent = p1Score;
p1ScoreDisplay.classList.remove("winner");
p2Score = 0;
p2ScoreDisplay.textContent = p2Score;
p2ScoreDisplay.classList.remove("winner");
gameOver = false;
inputValue.value = "";
}
resetButton.addEventListener("click", reset);
inputValue.addEventListener("change", function () {
winningScore = Number(this.value);
displayWinningScore.textContent = this.value;
reset();
});
Latest javascriptcode below that shows the answer to my problem. Instead of using variables, i used objects to allow them to be mutable(changed/altered).
The reason why i was not able to change the number variables initially is because of something known as "call by sharing". It involves passing numbers(primitive data type) by value and passing objects or arrays(non-primitive data types) by references. See link below for a good explanation. If not, you can always google search or wiki search "call by sharing javascript"
https://medium.com/#arunk.s/javascript-and-call-by-sharing-71b30e960fd4
I used many different variable names for the objects. Of course one can use just a single object to contain all the different parameters of the game. For example,
you can create the object like the one below here (which is not used in my rough solution).
var gameParameters = {
p1Score: 0,
p2Score: 0,
p1ScoreDisplay: document.querySelector("#h1p1Score"),
p2ScoreDisplay: document.querySelector("#h1p2Score")
.
.
.etc etc
}
Here is my dirty/rough solution
var p1Button = document.querySelector("#P1");
var p2Button = document.querySelector("#P2");
var resetButton = document.querySelector("#Reset");
/*
var p1ScoreDisplay = document.querySelector("#h1p1Score");
var p2ScoreDisplay = document.querySelector("#h1p2Score");
*/
var p1ScoreDisplay = {
scoreDisplay: document.querySelector("#h1p1Score")
};
var p2ScoreDisplay = {
scoreDisplay: document.querySelector("#h1p2Score")
};
var inputValue = document.querySelector("#inputNum");
/*
var p1Score = 0;
var p2Score = 0;
*/
var p1Score = {
score: 0
};
var p2Score = {
score: 0
};
/*
var gameOver = false;
*/
var isGameOver = {
gameOver: false
};
var winningScore = 5;
var displayWinningScore = document.querySelector("#winningScore");
/*function to increase the score of player 1 and player 2*/
function increment(scoreToIncrement,gameOverCheck,scoreToDisplay) {
if (!gameOverCheck.gameOver) {
scoreToIncrement.score++;
if (scoreToIncrement.score === winningScore) {
scoreToDisplay.scoreDisplay.classList.add("winner");
console.log("Game Over!");
gameOverCheck.gameOver = true;
}
scoreToDisplay.scoreDisplay.textContent = scoreToIncrement.score;
}
}
p1Button.addEventListener("click", function () {
increment(p1Score,isGameOver,p1ScoreDisplay);
/*original code to increase the score of player 1
if (!gameOver) {
p1Score++;
if (p1Score === winningScore) {
console.log("Game Over!");
p1ScoreDisplay.classList.add("winner");
gameOver = true;
}
p1ScoreDisplay.textContent = p1Score;
}
*/
});
p2Button.addEventListener("click", function () {
increment(p2Score,isGameOver,p2ScoreDisplay);
/*original code to increase the score of player 2
if (!isGameOver.gameOver) {
p2Score.score++;
if (p2Score.score === winningScore) {
console.log("Game Over!");
p2ScoreDisplay.scoreDisplay.classList.add("winner");
isGameOver.gameOver = true;
}
p2ScoreDisplay.scoreDisplay.textContent = p2Score.score;
}
*/
});
function reset() {
p1Score.score = 0;
p1ScoreDisplay.scoreDisplay.textContent = p1Score.score;
p1ScoreDisplay.scoreDisplay.classList.remove("winner");
p2Score.score = 0;
p2ScoreDisplay.scoreDisplay.textContent = p2Score.score;
p2ScoreDisplay.scoreDisplay.classList.remove("winner");
isGameOver.gameOver = false;
inputValue.value = "";
}
resetButton.addEventListener("click", reset);
inputValue.addEventListener("change", function () {
winningScore = Number(this.value);
displayWinningScore.textContent = this.value;
reset();
});

Categories