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

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!

Related

How do you wait for a button to get pressed a certain amount of times before running another function?

I am trying to build a gambling simulator that lets you gamble with fake money to see if you'd win more often times than not. The game I am sort of trying to replicate is Mines from Roobet. In my game, there are 9 squares laid out in a grid like format. One of the squares is the bomb square, which means if you click it, you lose. The player does not know which square is the bomb square though. You have to click 4 squares, and if all of the ones you have clicked are non-bomb squares, then you win $50. If you click the bomb square, then you lose $50.
What I have been trying to figure out for like a week now is how do you make the game wait until either 4 non-bomb squares have been clicked, or 1 bomb square to have been clicked in order to do certain functions(subtract 50 from gambling amount, restart the game). I have tried while loops, but that crashes the browser. I have also tried if-else statements, but the code doesn't wait until either 4 non-bomb squares or 1 bomb square has been clicked. It just checks it instantly. So it results in it not working right. I also have tried for the function to call itself, and then check for either case, but it just results in an error saying "Maximum call stack size exceeded."
function bombClicked () {
for (let i = 0; i < array.length; i++) { //each square is put into an array named array
array[i].addEventListener("click", () => {
if (array[i].value == "bomb") {
array[i].style.background = "red";
redCounter++;
didLose = true
}
else{
array[i].style.background = "green";
greenCounter++;
didLose = false;
}
})
}
if (greenCounter >= 4 || redCounter >= 1) {
if (didLose == true) {
gamblingAmount.value = parseInt(gamblingAmount.value) - 50;
}
else {
gamblingAmount.value = parseInt(gamblingAmount.value) + 50;
}
reset();
}
}
What a fun little exercise! Here's my quick and dirty jquery solution.
const NO_OF_TRIES_ALLOWED = 4;
const SCORE_WON_LOST = 50;
var score = 0;
var tries = 0;
var bombId;
function restart() {
tries = 0;
$("button").removeClass("ok");
$("button").removeClass("bang");
bombId = Math.floor( Math.random() * 9);
$("#bombLabel").text(bombId);
}
function win() {
window.alert('you win!');
score += SCORE_WON_LOST;
$("#scoreLabel").text(score);
restart();
}
function lose(){
window.alert('you lose!');
score -= SCORE_WON_LOST;
$("#scoreLabel").text(score);
restart();
}
$(document).on("click", "button", function() {
if( !$(this).is(".bang") && !$(this).is(".ok") ) {
let buttonId = $(this).data("id");
if(buttonId === bombId) {
$(this).addClass('bang');
setTimeout(lose, 100); // bit of a delay before the alert
}
else {
$(this).addClass('ok');
tries++;
if(tries === NO_OF_TRIES_ALLOWED) {
setTimeout(win, 100); // bit of a delay before the alert
}
}
}
});
restart();
button{
width: 50px;
height: 50px;
padding: 0;
}
.ok{
background-color: green;
}
.bang{
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-id="0"></button>
<button data-id="1"></button>
<button data-id="2"></button><br>
<button data-id="3"></button>
<button data-id="4"></button>
<button data-id="5"></button><br>
<button data-id="6"></button>
<button data-id="7"></button>
<button data-id="8"></button><br>
Score: <span id="scoreLabel"></span>
It looks like you need some sort of state. I don't know what the rest of your code looks like, but maybe creating a helper to keep track of your counts might help:
class Counter {
constructor() {
this.count = 0;
}
inc() {
this.count ++;
}
getCount() {
return this.count
}
}
const counter = new Counter();
counter.inc();
counter.inc();
counter.inc();
counter.getCount(); // 3
Javascript should keep this in memory for you. I might have to see the rest of your code to understand how exactly to fix the issue, but maybe this will put you on the right track!

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>

minor problem with control structure not executing code the way I want it to

Making a game us JS which selects a winner based on who gets to a certain number the first. however when I implement an if statement it breaks my game as this IF statement is to merely stop the game as soon as a winner has been selected.
when I remove the if statement the code works and selects a winner however, you can still keep clicking on the dice roll button and this is not what I want to happen here. Thank you in advance!
var scores, roundScore, currentPlayer, playTime;
game();
document.querySelector(".btn-roll").addEventListener("click", function() {
if (playTime) {
// 1. random number generator
var dice = Math.floor(Math.random() * 6) + 1;
console.log(dice);
// 2. display the result
var diceDom = document.querySelector(".dice");
diceDom.style.display = "block";
diceDom.src = "/images/dice-" + dice + ".png";
// 3. update the round score if the rolled number was not a 1
if (dice !== 1) {
// i. add score
roundScore += dice;
document.querySelector(
"#current-" + currentPlayer
).textContent = roundScore;
} else {
// ii. next player
nextPlayer();
}
}
});
document.querySelector(".btn-hold").addEventListener("click", function() {
if (playTime) {
// 4. add current players score to global score
scores[currentPlayer] += roundScore;
// i. update UI
document.querySelector("#score-" + currentPlayer).textContent =
scores[currentPlayer];
// ii. check who one the game
if (scores[currentPlayer] >= 10) {
document.querySelector("#name-" + currentPlayer).textContent =
"You are the winner!";
document.querySelector(".dice").style.display = "none";
document
.querySelector(".player-" + currentPlayer + "-panel")
.classList.add("winner");
document
.querySelector(".player-" + currentPlayer + "-panel")
.classList.remove(".active");
playTime = false;
} else {
// iii. next player
nextPlayer();
}
}
});
function nextPlayer() {
currentPlayer === 0 ? (currentPlayer = 1) : (currentPlayer = 0);
roundScore = 0;
//iii. reset scores to 0
document.getElementById("current-0").textContent = "0";
document.getElementById("current-1").textContent = "0";
//iiii. toggle active class for selected player
document.querySelector(".player-0-panel").classList.toggle("active");
document.querySelector(".player-1-panel").classList.toggle("active");
//iiiii. remove dice image when new player is appointed
document.querySelector(".dice").style.display = "none";
}
document.querySelector(".btn-new").addEventListener("click", game);
function game() {
scores = [0, 0];
currentPlayer = 0;
roundScore = 0;
// hide dice on intital page load
document.querySelector(".dice").style.display = "none";
// reset scores to 0
document.getElementById("score-0").textContent = "0";
document.getElementById("score-1").textContent = "0";
document.getElementById("current-0").textContent = "0";
document.getElementById("current-1").textContent = "0";
document.getElementById("name-0").textContent = "Player 1";
document.getElementById("name-1").textContent = "Player 2";
// reset colour of player panels
document.querySelector(".player-0-panel").classList.remove("winner");
document.querySelector(".player-1-panel").classList.remove("winner");
document.querySelector(".player-0-panel").classList.remove("active");
document.querySelector(".player-1-panel").classList.remove("active");
// re adding the active class
document.querySelector(".player-1-panel").classList.add("active");
}
I am expecting the If statement (playTime) which is located just under the queryselector '.btn-roll' to stop the game as soon as the winner is announced. but instead it is just not allowing this part of the code to run

executing the wrong function in if statement

/*
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
};

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