Skip to content

Commit cd70adb

Browse files
Merge pull request #26 from SuryaKarmakar/IBM-JavaScript-Essentials
Ibm java script essentials
2 parents fedcc6e + 25d3e9a commit cd70adb

File tree

5 files changed

+233
-0
lines changed

5 files changed

+233
-0
lines changed

Courses/IBM-JavaScript-Essentials/02-Control-Flow-And-Conditional-Statements/ control_flow.html renamed to Courses/IBM-JavaScript-Essentials/02-Control-Flow-And-Conditional-Statements/control_flow.html

File renamed without changes.
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Develop Colorful Memory Match Game Using JavaScript DOM:
2+
3+
## What you will learn:
4+
5+
You will learn the fundamentals of building a memory matching game using HTML and JavaScript. You will understand how to dynamically generate game elements, such as cards with various colors, handle click events to reveal and match colors, implement a basic scoring system that increments upon successful matches, create a timer mechanism to limit game time and initiate game restart functionalities. Through this lab, you will grasp key concepts of DOM manipulation, event handling, array manipulation (shuffling), and basic game logic, offering practical insight into creating interactive web-based games.
6+
7+
## Learning objectives:
8+
9+
1. DOM manipulation: Understand and implement dynamic HTML element creation and modification using JavaScript to generate a playable memory matching game grid.
10+
11+
2. Event handling: Learn to manage and respond to user interactions by handling click events on game cards, revealing colors, and implementing logic for matching pairs.
12+
13+
3. Game logic implementation: Develop fundamental game logic by incorporating mechanisms to match pairs of colors, track scores, reset the game, and manage game time through a simple timer.
14+
15+
4. Fundamentals of web game development: Gain insights into core concepts essential for creating interactive web-based games, including array manipulation for shuffling elements, styling elements with CSS, and integrating JavaScript functionalities for game interactivity and dynamics.
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
2+
body {
3+
padding: 0;
4+
margin: 0;
5+
background-color: #3498db;
6+
box-sizing: border-box;
7+
8+
}
9+
10+
.container {
11+
font-family: Arial, sans-serif;
12+
background-color: #3498db;
13+
display: flex;
14+
justify-content: center;
15+
align-items: center;
16+
height: 100vh;
17+
}
18+
19+
.startMain {
20+
margin-left: 20px;
21+
display: flex;
22+
align-items: center;
23+
flex-direction: column;
24+
}
25+
26+
h1 {
27+
color: #fff;
28+
text-align: center;
29+
}
30+
31+
#game-container {
32+
display: grid;
33+
grid-template-columns: repeat(4, 100px);
34+
grid-gap: 10px;
35+
background-color: #fff;
36+
padding: 10px;
37+
border-radius: 10px;
38+
}
39+
40+
.card {
41+
width: 100px;
42+
height: 100px;
43+
background-color: #ddd;
44+
display: flex;
45+
justify-content: center;
46+
align-items: center;
47+
font-size: 20px;
48+
cursor: pointer;
49+
transition: background-color 0.3s;
50+
border-radius: 5px;
51+
}
52+
53+
.matched {
54+
background-color: #4CAF50;
55+
color: #fff;
56+
}
57+
58+
#score {
59+
text-align: center;
60+
font-size: 24px;
61+
color: #fff;
62+
}
63+
64+
#timer {
65+
text-align: center;
66+
font-size: 24px;
67+
color: #fff;
68+
}
69+
70+
#startbtn{
71+
padding: 10px 20px;
72+
background-color: white;
73+
color: #3498db;
74+
border: none;
75+
font-weight: 900;
76+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<title>Colorful Memory Match Game</title>
5+
<link rel="stylesheet" href="./colorfulGame.css" />
6+
</head>
7+
8+
<body>
9+
<h1>Colorful Memory Match Game</h1>
10+
<div class="container">
11+
<div id="game-container">
12+
<!-- Cards will be generated dynamically using JavaScript -->
13+
</div>
14+
<div class="startMain">
15+
<p id="score">Score: 0</p>
16+
<p id="timer">Time Left: 30</p>
17+
<button id="startbtn">Start/Restart</button>
18+
</div>
19+
</div>
20+
<script src="./colorful_memory_game.js"></script>
21+
</body>
22+
</html>
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
// colors array: This array holds distinct color values in strings, representing the colors for the cards in the memory match game. These colors create pairs for the game.
2+
3+
// cards array: Initialized by shuffling and attaching the 'colors' array, this 'cards' array holds the color values for the cards in the game. The shuffle function employs the Fisher-Yates algorithm to randomize the order of the colors and then duplicates these colors to create pairs, forming the set of cards for gameplay.
4+
5+
// selectedCards: This variable acts as a temporary storage for the currently selected cards during the game. When a player clicks on a card, it gets added to this array to enable match comparisons.
6+
7+
// score: This variable tracks the player's score throughout the game. The score gets incremented whenever the player matches a pair of cards successfully. It's updated and displayed to reflect the player's progress and performance.
8+
9+
// timeLeft: It represents the time remaining for the player to complete the game. Initially set to a specific duration, it counts down as the game progresses. When it reaches zero, the game ends.
10+
11+
// gameInterval: This variable manages the game timer. It's utilized to control the countdown mechanism for the game's duration. The interval continuously decrements the 'timeLeft' variable, updating the displayed time and triggering the game's end when the time expires.
12+
const colors = [
13+
"red",
14+
"blue",
15+
"green",
16+
"purple",
17+
"orange",
18+
"pink",
19+
"red",
20+
"blue",
21+
"green",
22+
"purple",
23+
"orange",
24+
"pink",
25+
];
26+
let cards = shuffle(colors.concat(colors));
27+
let selectedCards = [];
28+
let score = 0;
29+
let timeLeft = 30;
30+
let gameInterval;
31+
32+
const startbtn = document.getElementById("startbtn");
33+
const gameContainer = document.getElementById("game-container");
34+
const scoreElement = document.getElementById("score");
35+
const timerElement = document.getElementById("timer");
36+
37+
// Create the generateCards() function responsible for dynamically creating the card elements within the game container based on the 'cards' array that holds color values for the cards. This function creates the card elements dynamically within the game-container div. Include given code in javaScript file after previous code.
38+
function generateCards() {
39+
// It utilizes a 'for…of' loop to iterate over each element (color) in the 'cards' array. For each color in the 'cards' array:
40+
for (const color of cards) {
41+
const card = document.createElement("div");
42+
card.classList.add("card");
43+
card.dataset.color = color;
44+
card.textContent = "?";
45+
gameContainer.appendChild(card);
46+
}
47+
}
48+
49+
// The shuffle() Function is responsible for shuffling the elements of an array in random order. It uses the Fisher-Yates shuffle algorithm, a common method for randomizing the order of elements in an array. Include given code after generateCards() function.
50+
function shuffle(array) {
51+
// Shuffling process using loop through the array: The function starts by initiating a 'for' loop that iterates backward through the array starting from the last index (let i = array.length - 1; i > 0; i–).
52+
for (let i = array.length - 1; i > 0; i--) {
53+
// Within each iteration, it generates a random index 'j'
54+
const j = Math.floor(Math.random() * (i + 1));
55+
56+
// Swapping elements: It then swaps the elements at the 'i' and 'j' indices using array destructuring assignment: [array[i], array[j]] = [array[j], array[i]]. This line efficiently swaps the values at positions 'i' and 'j' without requiring a temporary variable.
57+
[array[i], array[j]] = [array[j], array[i]];
58+
}
59+
return array;
60+
}
61+
62+
// The handleCardClick(event) function manages the logic when a user clicks the card in the memory match game. Include given code after shuffle() function. Let's break down each step within this function:
63+
function handleCardClick(event) {
64+
const card = event.target;
65+
if (!card.classList.contains("card") || card.classList.contains("matched")) {
66+
return;
67+
}
68+
card.textContent = card.dataset.color;
69+
card.style.backgroundColor = card.dataset.color;
70+
selectedCards.push(card);
71+
if (selectedCards.length === 2) {
72+
setTimeout(checkMatch, 500);
73+
}
74+
}
75+
76+
function checkMatch() {
77+
const [card1, card2] = selectedCards;
78+
if (card1.dataset.color === card2.dataset.color) {
79+
card1.classList.add("matched");
80+
card2.classList.add("matched");
81+
score += 2;
82+
scoreElement.textContent = `Score: ${score}`;
83+
} else {
84+
card1.textContent = "?";
85+
card2.textContent = "?";
86+
card1.style.backgroundColor = "#ddd";
87+
card2.style.backgroundColor = "#ddd";
88+
}
89+
selectedCards = [];
90+
}
91+
92+
function startGame() {
93+
let timeLeft = 30;
94+
startbtn.disabled = true;
95+
score = 0; // Reset score to zero
96+
scoreElement.textContent = `Score: ${score}`;
97+
startGameTimer(timeLeft);
98+
cards = shuffle(colors.concat(colors));
99+
selectedCards = [];
100+
gameContainer.innerHTML = "";
101+
generateCards();
102+
gameContainer.addEventListener("click", handleCardClick);
103+
}
104+
105+
function startGameTimer(timeLeft) {
106+
timerElement.textContent = `Time Left: ${timeLeft}`;
107+
gameInterval = setInterval(() => {
108+
timeLeft--;
109+
timerElement.textContent = `Time Left: ${timeLeft}`;
110+
111+
if (timeLeft === 0) {
112+
clearInterval(gameInterval);
113+
let timeLeft = 30;
114+
alert("Game Over!");
115+
startbtn.disabled = false;
116+
}
117+
}, 1000);
118+
}
119+
120+
startbtn.addEventListener("click", startGame);

0 commit comments

Comments
 (0)