Categories: Uncategorized

Colour Guessing Game (JS Mini Project) By Sanjana Gautam

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Color Guessing Game</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <h1>Color Guessing Game</h1>
  <div id="colorDisplay"></div>
  <div id="message"></div>
  <div id="container">
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
  </div>
  <script src="script.js"></script>
</body>
</html>

style.css

body {
    text-align: center;
    font-family: Arial, sans-serif;
  }
  
  h1 {
    color: steelblue;
  }
  
  #container {
    margin-top: 20px;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .square {
    width: 30%;
    padding-bottom: 30%;
    margin: 1.66%;
    float: left;
    border-radius: 6px;
    cursor: pointer;
  }
  
  #colorDisplay {
    margin-top: 20px;
    font-size: 2em;
  }
  
  #message {
    margin-top: 20px;
    font-size: 1.5em;
    color: green;
  }

script.js

slet colors = [];
let pickedColor;
const squares = document.querySelectorAll(".square");
const colorDisplay = document.getElementById("colorDisplay");
const message = document.getElementById("message");

function generateRandomColor() {
  const r = Math.floor(Math.random() * 256);
  const g = Math.floor(Math.random() * 256);
  const b = Math.floor(Math.random() * 256);
  return `rgb(${r}, ${g}, ${b})`;
}

function generateRandomColors(num) {
  const arr = [];
  for (let i = 0; i < num; i++) {
    arr.push(generateRandomColor());
  }
  return arr;
}

function pickColor() {
  const random = Math.floor(Math.random() * colors.length);
  return colors[random];
}

function changeColors(color) {
  squares.forEach(square => {
    square.style.backgroundColor = color;
  });
}

function reset() {
  colors = generateRandomColors(6);
  pickedColor = pickColor();
  colorDisplay.textContent = pickedColor;
  message.textContent = "";
  for (let i = 0; i < squares.length; i++) {
    if (colors[i]) {
      squares[i].style.display = "block";
      squares[i].style.backgroundColor = colors[i];
    } else {
      squares[i].style.display = "none";
    }
  }
}

squares.forEach((square, index) => {
  square.addEventListener("click", function() {
    const clickedColor = this.style.backgroundColor;
    if (clickedColor === pickedColor) {
      message.textContent = "Correct!";
      changeColors(clickedColor);
    } else {
      this.style.backgroundColor = "#232323";
      message.textContent = "Try Again";
    }
  });
});

reset();

 

jaminrai