Simon Game using HTML CSS & JavaScript – Live Demonstration with Full Code

Creating a Simon Game with HTML, CSS, and JavaScript

In this article, we will explore how to create a Simon Game using HTML, CSS, and JavaScript. In the Simon game, the player must repeat a sequence of colors. If the player succeeds, the sequence becomes progressively longer and more complex. The game ends when the player fails to repeat the sequence correctly.

Prerequisites

  • HTML
  • CSS
  • JavaScript

Approach

  1. HTML Structure:
    • Create the base structure of the game using <div> elements.
    • Use a <button> element to start the game.
    • Include an <input> element for toggling strict mode, where a single mistake requires the player to restart from the beginning.
  2. Styling with CSS:
    • Add styling properties to define the layout and appearance of the game.
    • Apply padding, margin, font sizes, alignments, and colors to the various elements.
  3. JavaScript Functionality:
    • Attach onclick events to each light button, referring to a handleClick() function.
    • Each light button will have a data-color attribute to identify it (e.g., data-color="1" for the first color, data-color="2" for the second, etc.).
    • The start button will initialize the game and reset everything to default if a previous game was played.
    • Implement a nextRound() function to proceed to the next round, incrementing the level counter.
    • Implement a checkSequence() function to verify if the player has correctly repeated the sequence.
    • Include helper functions to enable or disable strict mode and the light buttons.
  4. Game Logic:
    • Use two arrays: sequence and userSequence.
    • The sequence array stores the order of colors generated by the computer.
    • The userSequence array stores the order of colors input by the player.
    • Compare these arrays to determine if the player follows the sequence correctly.
    • Continue the game until the player makes a mistake.

Example Implementation

Here is a basic implementation of the Simon Game using HTML, CSS, and JavaScript:

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport"
		content="width=device-width, initial-scale=1.0">
	<link rel="preconnect" href=
"https://fonts.googleapis.com">
	<link rel="preconnect" href=
"https://fonts.gstatic.com" crossorigin>
	<link href=
"https://fonts.googleapis.com/css2?family=Balsamiq+Sans&display=swap"
		rel="stylesheet">
	<title>Simon Game</title>
	<!-- CSS -->
	<style>
		body {
			display: flex;
			flex-direction: column;
			align-items: center;
			height: 100vh;
			margin: 0;
			background-color: rgb(206, 201, 201);
			font-family: 'Balsamiq Sans', sans-serif;
		}

		#controls {
			margin: 20px 0 20px 0;
		}

		#strict-mode {
			margin-right: 20px;
		}

		#simon-board {
			display: grid;
			grid-template-columns: repeat(2, 1fr);
			gap: 20px;
			max-width: 300px;
			text-align: center;
			margin-bottom: 1rem;
		}

		.simon-btn {
			width: 100px;
			height: 100px;
			border: none;
			outline: none;
			cursor: pointer;
			font-size: 18px;
			font-weight: bold;
			background-color: #3498db;
			color: #fff;
			transition: background-color 0.3s;
		}

		.top-left {
			background-color: darkgreen;
		}

		.top-right {
			background-color: darkred;
		}

		.bottom-left {
			background-color: goldenrod;
		}

		.bottom-right {
			background-color: darkblue;
		}

		.level-count {
			color: red;
			background-color: rgb(81, 0, 0);
			padding: 0.25rem 1rem;
		}

		#start-btn,
		#power-btn {
			font-family: 'Balsamiq Sans', sans-serif;
			margin-top: 30px;
			padding: 10px;
			font-size: 16px;
			cursor: pointer;
			background-color: #2ecc71;
			color: #fff;
			border: none;
			outline: none;
			border-radius: 5px;
			transition: background-color 0.3s;
		}

		#start-btn:hover,
		#power-btn:hover {
			background-color: #27ae60;
		}

		#start-btn:disabled,
		#power-btn:disabled {
			background-color: #484a4b;
			cursor: not-allowed;
		}
	</style>
</head>

<body>
	<h1>Simon Game</h1>
	<div id="controls">
		<label for="strict-mode">Strict Mode</label>
		<input type="checkbox" id="strict-mode"
			onchange="toggleStrictMode()">
	</div>

	<div id="simon-board">
		<button class="simon-btn top-left"
				onclick="handleClick(this)"
		data-color="1" disabled></button>
		<button class="simon-btn top-right"
				onclick="handleClick(this)"
		data-color="2" disabled></button>
		<button class="simon-btn bottom-left"
				onclick="handleClick(this)"
		data-color="3" disabled></button>
		<button class="simon-btn bottom-right"
				onclick="handleClick(this)"
		data-color="4" disabled></button>
	</div>

	<div id="level">
		<span>Level: 
			<span class="level-count">-</span>
		</span>
	</div>
	<button id="power-btn"
			onclick="togglePower()">Start</button>
	<!-- JavaScript -->
	<script>
		let strictMode = false;
		let powerOn = false;
		const sequence = [];
		let userSequence = [];
		let level = 1;

		const levelCount = document.querySelector('.level-count');

		function startGame() {
			sequence.length = 0;
			userSequence.length = 0;
			level = 1;
			levelCount.textContent = level;
			nextRound();
			document.getElementById("start-btn").disabled = true;
			document.getElementById("power-btn").disabled = false;
		}

		function nextRound() {
			addToSequence();
			playSequence();
		}

		function addToSequence() {
			const randomColor = Math.floor(Math.random() * 4) + 1;
			sequence.push(randomColor);
		}

		function playSequence() {
			let i = 0;
			const intervalId = setInterval(() => {
				highlightButton(sequence[i]);
				i++;
				if (i >= sequence.length) {
					clearInterval(intervalId);
					enableButtons();
				}
			}, 1000);
		}

		function handleClick(button) {
			if (powerOn) {
				const userColor = button.getAttribute("data-color");
				userSequence.push(Number(userColor));
				highlightButton(userColor);
				if (!checkSequence()) {
					if (strictMode) {
						alert(`Game over! Press Start to retry 
						from level 1.\nFINAL SCORE: ${level}`);
						togglePower();
						startGame();
					} else {
						alert(`Wrong sequence! Press Start to try again
						from current level.\nFINAL SCORE: ${level}`);
						userSequence = [];
						document.getElementById('power-btn')
						.addEventListener('click', () => {
							playSequence();
						})
					}
				} else if (userSequence.length === sequence.length) {
					userSequence = [];
					level++;
					levelCount.textContent = level;
					/*Can change level as per convenience or if we want the game to 
					continue indefinitely, can omit if-else condition */
					if (level <= 20) {
						setTimeout(() => nextRound(), 1000);
					} else {
						alert("Congratulations! You won!");
						startGame();
					}
				}
			}
		}

		function checkSequence() {
			for (let i = 0; i < userSequence.length; i++) {
				if (userSequence[i] !== sequence[i]) {
					return false;
				}
			}
			return true;
		}

		function highlightButton(color) {
			const button = document
			.querySelector(`[data-color="${color}"]`);
			if (Number(color) == 1) {
				button.style.backgroundColor = 'lightgreen'
			}
			else if (Number(color) == 2) {
				button.style.backgroundColor = 'tomato'
			}
			else if (Number(color) == 3) {
				button.style.backgroundColor = 'yellow'
			}
			else if (Number(color) == 4) {
				button.style.backgroundColor = 'lightskyblue'
			}
			setTimeout(() => {
				button.attributes.removeNamedItem('style');
			}, 300);
		}

		function enableButtons() {
			const buttons = document
			.querySelectorAll('.simon-btn');
			buttons.forEach(button => 
			button.removeAttribute('disabled'));
		}

		function disableButtons() {
			const buttons = document
			.querySelectorAll('.simon-btn');
			buttons.forEach(button => 
			button.setAttribute('disabled', 'true'));
		}

		function toggleStrictMode() {
			strictMode = !strictMode;
		}

		function togglePower() {
			powerOn = !powerOn;
			if (powerOn) {
				startGame();
				enableButtons();
				document.getElementById("start-btn")
				.disabled = false;
			} else {
				userSequence = [];
				disableButtons();
				document.getElementById("start-btn")
				.disabled = true;
			}
		}
	</script>
</body>

</html>

Output:

In this detailed guide, we have walked through the process of creating a Simon Game using HTML, CSS, and JavaScript. By following the approach outlined above, you can build a fully functional Simon Game that challenges players to repeat progressively longer and more complex sequences of colors.

Conclusion

In this comprehensive guide, we delved into the creation of a Simon Game using HTML, CSS, and JavaScript. This project serves as an excellent example of how to combine these three core web technologies to build an interactive and engaging game. Here’s a detailed summary of what we covered:

Understanding the Simon Game

We began by understanding the basic mechanics of the Simon Game. The game challenges players to remember and repeat a sequence of colors that progressively become longer and more complex. A mistake at any point ends the game, especially in strict mode where the player must start over from the beginning if an error is made.

Setting Up the Prerequisites

We listed the essential prerequisites for this project:

  • HTML: For creating the structure and elements of the game.
  • CSS: For styling the game and making it visually appealing.
  • JavaScript: For adding interactivity and game logic.

Step-by-Step Implementation

  1. HTML Structure:
    • We created the basic layout of the game using <div> elements to represent the color buttons, a <button> element to start the game, and an <input> element for enabling strict mode.
  2. CSS Styling:
    • We applied styles to arrange the game grid, set the colors for the buttons, and styled the start button and strict mode checkbox. This ensured a clean and responsive design.
  3. JavaScript Functionality:
    • Event Handling: We added event listeners to the start button and color buttons. The handleClick function was used to manage user inputs.
    • Game Logic: We implemented functions such as startGame, nextRound, playSequence, lightUp, and checkSequence. These functions controlled the flow of the game, generated random sequences, validated user inputs, and handled the game’s progression.
    • Strict Mode: We included a strict mode toggle that resets the game upon an incorrect input, adding an extra level of challenge for the player.

Live Demonstration and Full Code

The guide provided a live demonstration of the game, showcasing its functionality and interactivity. We included the full code for HTML, CSS, and JavaScript, allowing readers to follow along and implement the game themselves. By running the provided code, readers could experience the game firsthand and see how each part of the code contributes to the final product.

Key Learnings

Through this project, readers learned how to:

  • Structure an interactive web application using HTML.
  • Apply CSS to create a visually appealing and responsive design.
  • Use JavaScript to add complex interactivity and control game logic.
  • Combine HTML, CSS, and JavaScript to build a complete, functioning game.

Final Thoughts

Building a Simon Game using HTML, CSS, and JavaScript is not only a fun project but also an educational one. It helps reinforce foundational web development skills and demonstrates how these technologies can be used together to create dynamic, interactive applications. Whether you are a beginner looking to practice your skills or an experienced developer seeking a fun project, the Simon Game offers valuable insights and a rewarding experience.

By following this guide, you now have the knowledge and tools to create your own Simon Game, customize it further, and even expand upon it with additional features. Happy coding!

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>