I am building a 2 Player shooter game. Each player has a health of 100. Players can shoot at each other with a random power (0-5) which will reduce the opponent’s health.
I am trying to reduce the currentScore by random health as given below. But its showing the TypeError.
textContent is showing null value. What should I do solve this error?
"use strict";
const player1El = document.querySelector(".player-1");
const player2El = document.querySelector(".player-2");
const score1El = document.querySelector("#score--1");
const score2El = document.querySelector("#score--2");
const current1El = document.querySelector("#current--1");
const current2El = document.querySelector("#current--2");
const healthEl = document.querySelector(".health");
const btnNew = document.querySelector(".btn--new");
const btnShoot = document.querySelector(".btn--shoot");
let wins, currentScore, activePlayer, playing;
// Initializing
const init = function () {
wins = [0, 0];
currentScore = 100;
activePlayer = 0;
playing = true;
score1El.textContent = 0;
score2El.textContent = 0;
current1El.textContent = 100;
current2El.textContent = 100;
healthEl.classList.add("hidden");
player1El.classList.remove("player--winner");
player2El.classList.remove("player--winner");
player1El.classList.add("active");
player2El.classList.remove("active");
};
init();
// console.log(currentScore);
// Switching Players
const switchPlayer = function () {
document.getElementById(`current--${activePlayer}`).textContent = 0;
currentScore = 100;
activePlayer = activePlayer === 1 ? 2 : 1;
player1El.classList.toggle("player--active");
player2El.classList.toggle("player--active");
};
// Shooting Functionality
btnShoot.addEventListener("click", function () {
// 1. Generating random number
const health = Math.trunc(Math.random() * 6);
// 2. Display health
healthEl.classList.remove("hidden");
healthEl.src = `imgs/Num-${health}.png`;
// 3. Decrease health
currentScore -= health;
console.log(currentScore);
document.querySelector(`current--${activePlayer}`).textContent = currentScore;
});