Skip to content

Commit

Permalink
refactored, redesigned, theme introduced, #KAYAPALAT
Browse files Browse the repository at this point in the history
  • Loading branch information
aakashdinkarh committed Oct 12, 2024
1 parent 70f96d0 commit 227ddec
Show file tree
Hide file tree
Showing 3 changed files with 351 additions and 109 deletions.
45 changes: 37 additions & 8 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,47 @@
<meta name="twitter:image" content="https://aakashdinkarh.github.io/static_assets/images/portfolio/original-images/meta-og-image.jpeg" />

<title>Memory Game - Aakash Dinkar</title>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<link rel="stylesheet" href="./style.css" />
<script>
const localStorageKey = '--saved--isDarkThemeEnabled';
function saveIsDarkThemeEnabledToLocalStorage(isDarkThemeEnabled) {
localStorage.setItem(localStorageKey, JSON.stringify(isDarkThemeEnabled));
}
function getIsDarkThemeEnabledFromLocalStorage() {
let isDarkThemeEnabled = true;
try {
const storedKeyResult = localStorage.getItem(localStorageKey);
isDarkThemeEnabled =
storedKeyResult != null ? JSON.parse(storedKeyResult) : true;
} catch {
isDarkThemeEnabled = true;
}
return isDarkThemeEnabled;
saveIsDarkThemeEnabledToLocalStorage(isDarkThemeEnabled);
}
</script>
</head>
<body>
<script>
document.body.classList.add(getIsDarkThemeEnabledFromLocalStorage() ? 'dark-theme' : 'light-theme');
</script>
<div class="container">
<h1>Memory Game</h1>
<button class="success" onclick="start()">Start Game</button>
<br><br>
<div id="score"></div>

<div id="boardgame"></div>
<button id="restart-btn">Restart Game</button>
<!-- theme slider *** START *** -->
<div class="theme-slider-container">
<label class="theme-slider">
<input type="checkbox" checked />
<div class="round slider"></div>
</label>
</div>
<!-- theme slider *** END *** -->
<br>
<br>
<p id="moves">Moves: 0</p>
<div id="gameBoard"></div>
<p id="gameWonMsg"></p>
</div>

<script src="./script.js"></script>
</body>
</html>
212 changes: 140 additions & 72 deletions script.js
Original file line number Diff line number Diff line change
@@ -1,72 +1,140 @@
const images = ['panda.jpg', 'cat.jpg', 'panda.jpg', 'cat.jpg', 'mickey.jpg', 'mickey.jpg'];

function start() {
let moves = 0;
var points = document.createElement('p')
points.setAttribute('id', 'points');
points.innerHTML = 'points';
document.getElementById("score").append(points)

let imagesCopy = [];
for(let i = 0; i < images.length; i++) {
imagesCopy.push(images[i]);
}
var row = document.createElement('div')
var n = images.length;
for(let i = 1; i <=n; i++){
var div = document.createElement('div');
div.setAttribute('class', 'imageDiv')

let randomImg = imagesCopy.splice(Math.floor(Math.random() * imagesCopy.length), 1);
console.log(randomImg)

var img = document.createElement('img')
img.setAttribute('src', randomImg)
img.setAttribute('class', 'hide')

div.appendChild(img)
row.appendChild(div)

if( i%3 == 0) {
document.getElementById('boardgame').appendChild(row);
row = document.createElement('div');
}

div.addEventListener('click', function(event) {
moves++;
document.getElementById('points').innerHTML = moves;


var curr = event.currentTarget.children
var currImg = curr[0];

var currShowing = document.getElementsByClassName('show')

let flag = 0;
if(currShowing.length >= 1) {
for(let j = 0; j < currShowing.length; j++) {
if(currShowing[j].src != currImg.src)
currShowing[j].classList.remove('show')
else {
currShowing[j].classList.add('match')
currImg.classList.add('match')
flag = 1;
}
}
}
if(flag == 0) {
currImg.classList.add('show');
}

if( document.getElementsByClassName('match').length == n ) {
let button = document.createElement('button')
button.setAttribute('class', 'warning')

let node = document.createTextNode("You've won!! Moves = "+moves)
button.appendChild(node);

document.getElementById('score').appendChild(button)
}
});
}
}
(function () {
const images = ['panda.jpg', 'cat.jpg', 'panda.jpg', 'cat.jpg', 'mickey.jpg', 'mickey.jpg'];
const imagesPerRow = 3;

let winMessageShown = false;
const __moves__ = document.getElementById('moves');
const __restartBtn__ = document.getElementById('restart-btn');
const __gameBoard__ = document.getElementById('gameBoard');
const __gameWonMsg__ = document.getElementById('gameWonMsg');
const __toggleSwitch__ = document.querySelector('.theme-slider input[type="checkbox"]');
const __slider__ = document.querySelector('.theme-slider .slider');
const __getMatchElements__ = () => document.getElementsByClassName('match');
const __getAllImageDiv__ = () => document.querySelectorAll('.imageDiv');
const __getShowingElements__ = () => document.getElementsByClassName('show');

function restartGame() {
__gameBoard__.innerHTML = '';
__gameWonMsg__.innerText = '';
winMessageShown = false;

startGame();
}

function startGame() {
let moves = 0;
renderMoves(moves);

const shuffledImages = shuffleImages(images);
generateBoard(shuffledImages);

function updateScore() {
moves++;
renderMoves(moves);
}

__getAllImageDiv__().forEach((div) => {
div.addEventListener('click', function (event) {
handleCardClick(event, moves, updateScore);
});
});
}

function renderMoves(moves = 0) {
__moves__.innerText = `Moves: ${moves}`;
}

function shuffleImages(imagesArray) {
let copy = [...imagesArray];
let shuffled = [];
while (copy.length) {
let randomIndex = Math.floor(Math.random() * copy.length);
shuffled.push(copy.splice(randomIndex, 1)[0]);
}
return shuffled;
}

function generateBoard(images) {
const fragment = document.createDocumentFragment();
let row = document.createElement('div');

images.forEach((image, index) => {
const div = document.createElement('div');
div.setAttribute('class', 'imageDiv');

const img = document.createElement('img');
img.setAttribute('src', image);
img.setAttribute('class', 'hide');

div.appendChild(img);
row.appendChild(div);

if ((index + 1) % imagesPerRow === 0) {
fragment.appendChild(row);
row = document.createElement('div');
}
});

__gameBoard__.replaceChildren(fragment);
}

function handleCardClick(event, moves, updateScore) {
if (winMessageShown) return;

updateScore();
const clickedImage = event.currentTarget.children[0];
const showingImages = __getShowingElements__();

let matchFound = false;

if (showingImages.length >= 1) {
[...showingImages].forEach((showingImage) => {
if (showingImage.src !== clickedImage.src) {
showingImage.classList.remove('show');
} else {
showingImage.classList.add('match');
clickedImage.classList.add('match');
matchFound = true;
}
});
}

if (!matchFound) {
clickedImage.classList.add('show');
}

if (__getMatchElements__().length === images.length) {
displayWinMessage(moves);
}
}

function displayWinMessage(moves) {
winMessageShown = true;
__gameWonMsg__.innerText = `You've won!! Moves = ${moves}`;
}

document.addEventListener('DOMContentLoaded', () => {
document.body.style.cssText = `transition: background-color 0.3s, color 0.3s;`;
startGame();
__restartBtn__.onclick = restartGame;

/* theme slider logic --- START --- */
__toggleSwitch__.onchange = toggleTheme;
__toggleSwitch__.checked = document.body.className === 'dark-theme';
setTimeout(() => {
__slider__.classList.add('slider-transition-class');
}, 0);
/* theme slider logic --- END --- */

function toggleTheme(e) {
const isDarkThemeEnabled = e.target.checked;

if (isDarkThemeEnabled) {
document.body.className = 'dark-theme';
} else {
document.body.className = 'light-theme';
}
saveIsDarkThemeEnabledToLocalStorage(isDarkThemeEnabled);
};
});
})();
Loading

0 comments on commit 227ddec

Please sign in to comment.