Home > database >  Can't assign a specific color to div even though I defined the color earlier
Can't assign a specific color to div even though I defined the color earlier

Time:11-12

I'm making a color guessing game in JS. You're given the RGB value of a color, and you're supposed to click one of the three divs with that specific color while the other two have a different color. I've managed to make these three divs have three different random colors; however, I can't figure out how to make one of them have the winning color.

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css">
    <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>Document</title>
</head>
<body>
    <h1 class="text-centered">Guess The Color!</h1>
    <h2 class="text-centered" id="colorguess"></h2>

    <div class="box-container">
        <div class="box">
        </div>
        <div class="box">
        </div>
        <div class="box">
        </div>
    </div>
</body>
<script src="script.js"></script>
</html>

*{
    box-sizing: border-box;
}
body{
    font-family: arial;
    background-color: #1c1874;
    color: rgb(105, 105, 139);
    color: #fff;
}
.text-centered{
 text-align: center;  
 text-shadow: 0px 2px 2px rgba(150, 150, 150, 1); 
}
.box-container{
    padding: 200px;
    align-self: center;
    display: flex;
    flex-direction: row;
    justify-content:space-evenly;
}
.box{
    width: 200px;
    height: 200px;
    border-radius: 20px;
    cursor: pointer;
}

function gamestart(){
    var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);
    var rgb = document.getElementById('colorguess');
    //here i defined the initial winning color
    rgbvaluetrue = "rgb(" r ", " g ", " b ")";
    rgb.innerHTML = rgbvaluetrue;
    var body = document.getElementsByTagName('body');
    var box = document.getElementsByClassName('box');
    for(var i=0;i<=box.length;i  ){
        var r,g,b = Math.floor(Math.random() * 256);
        rgbvalue = "rgb(" r ", " g ", " b ")";
        box[i].style.backgroundColor = rgbvalue;
    }

    //here I am trying to assign the initial rgb value to one of the divs randomly
    var rand = Math.floor(Math.random() * 3);
    
    //here I check if the div you clicked on is correct
    box[rand].style.backgroundColor = rgbvaluetrue;
    for(var i=0;i<=box.length;i  ){
        box[i].addEventListener("click", function(el) {
            if (el.style.backgroundColor == rgbvaluetrue){
                h1 = document.getElementsByTagName('h1');
                h1.innerHTML = "BRAVO";
            }
            else{
                gamestart();
            }
          })
    }
}
gamestart();

CodePudding user response:

The code for the game is there but there were three of mistakes in it.

I'll go through them one by one:

  1. The two for cycles are run 4 times instead of 3. The termination condition i<=box.length should be replaced by i<box.length.

  2. The addEventListener handler doesn't get the element as an input parameter but the event itself. You can then get the element with the target property like this: event.target.

  3. After this assignment h1 = document.getElementsByTagName('h1'); h1 contains an array with all the h1 elements so you can't assign use h1.innerHTML = "BRAVO"; to assign a content to it. I changed it to display the success text in the same h1 you are using to show the rgb value like this: h1 = document.getElementById('colorguess');

  4. Lastly, in your code the addEventListener is called every time the game is played. After the first victory you will have 2 listeners for every box making the game unplayable unless you refresh the entire page. To solve this I moved the listeners registration in a init function that you have to call only once at the start of the first game. (Another way was to remove and then readd the event listener every time)

Here is the complete js code. I didn't touch the html/css parts.

var rgbvaluetrue;

function initGame() {
  var box = document.getElementsByClassName('box');
  for(var i=0;i<box.length;i  ){
    box[i].addEventListener("click", checkWinner);
  }
}

function gamestart(){
    var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);
    var rgb = document.getElementById('colorguess');
    //here i defined the initial winning color
    rgbvaluetrue = "rgb(" r ", " g ", " b ")";
    rgb.innerHTML = rgbvaluetrue;
    var body = document.getElementsByTagName('body');
    var box = document.getElementsByClassName('box');
    for(var i=0;i<box.length;i  ){
        var r,g,b = Math.floor(Math.random() * 256);
        rgbvalue = "rgb(" r ", " g ", " b ")";
        box[i].style.backgroundColor = rgbvalue;
    }

    //here I am trying to assign the initial rgb value to one of the divs randomly
    var rand = Math.floor(Math.random() * 3);
    //here I check if the div you clicked on is correct
    box[rand].style.backgroundColor = rgbvaluetrue;
}

function checkWinner(event) {
    if (event.target.style.backgroundColor === rgbvaluetrue){
        h1 = document.getElementById('colorguess');
        h1.innerHTML = "BRAVO";
    }
    else{   
        gamestart();       
    }
  }

initGame();
gamestart();

CodePudding user response:

There is a small mistake in the loops: for(var i=0;i<=box.length;i ){ It goes 4 times, but you have 3 boxes change to for(var i=0;i<box.length;i ){

CodePudding user response:

There are multiple issues:

for loops are iterating more times than needed

var r, g, b = ... will only assign b. r and g will remain undefined

I refactored the JavaScript and fixed all issues, run the below snippet:

const getRandomColor = () => {
  return `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)})`;
}

let colorToGuess = '';
const resultContainer = document.querySelector('#result');
const colorToGuessContainer = document.querySelector('#color-to-guess');
const boxes = document.querySelectorAll('.box-container .box');

const startGame = () => {
  resultContainer.innerText = "Guess The Color!"
  colorToGuess = getRandomColor();
  colorToGuessContainer.innerHTML = colorToGuess;

  const randomBoxIndex = Math.floor(Math.random() * boxes.length);

  boxes.forEach((box, index) => {
    box.style.backgroundColor = index === randomBoxIndex ? colorToGuess : getRandomColor();
  })
}

boxes.forEach((box) => {
  box.addEventListener('click', ({
    target
  }) => {
    if (target.style.backgroundColor === colorToGuess) {
      resultContainer.innerText = "You guessed it, click me to play again."
    } else {
      startGame()
    }
  })
})

startGame();
resultContainer.addEventListener('click', startGame)
* {
  box-sizing: border-box;
}

body {
  font-family: arial;
  background-color: #1c1874;
  color: white;
}

.text-centered {
  text-align: center;
  text-shadow: 0px 2px 2px rgba(150, 150, 150, 1);
}

.box-container {
  padding: 2rem;
  display: flex;
  align-items: center;
  justify-content: center;
}

.box {
  width: 200px;
  height: 200px;
  border-radius: 20px;
  cursor: pointer;
}
<h1 class="text-centered" id="result"></h1>
<h2 class="text-centered" id="color-to-guess"></h2>

<div class="box-container">
  <div class="box">
  </div>
  <div class="box">
  </div>
  <div class="box">
  </div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related