Certainly! I'll help you modify your Wordle clone to enhance the delete functionality. Specifically, when you delete a letter in a tile that contains a letter, it will remove that letter and move the cursor appropriately within the current row. This ensures a more intuitive user experience when correcting mistakes.
Updated Code with Enhanced Delete Functionality
Below is the complete HTML, CSS, and JavaScript code with the necessary modifications to achieve the desired delete behavior. I've added comments to highlight the changes made to the deleteLetter function and related parts.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Advanced Wordle Clone</title>
<style>
/* Reset and Base Styles */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
:root {
--bg-color: #121213;
--text-color: #FFFFFF;
--tile-border: #3a3a3c;
--tile-bg: #121213;
--tile-correct: #538D4E;
--tile-present: #B59F3B;
--tile-absent: #3A3A3C;
--key-bg: #818384;
--key-correct: #538D4E;
--key-present: #B59F3B;
--key-absent: #3A3A3C;
--modal-bg: #1E1E1E;
--button-bg: #818384;
--button-hover: #6c6d70;
--menu-bg: #1E1E1E;
--active-border: #FFEB3B;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
min-height: 100vh;
padding: 20px;
position: relative;
overflow: hidden;
}
h1 {
margin: 20px 0;
font-size: 2.5em;
letter-spacing: 2px;
}
/* Coin Display */
.coins {
position: absolute;
top: 20px;
right: 20px;
background-color: var(--button-bg);
padding: 10px 15px;
border-radius: 6px;
display: flex;
align-items: center;
gap: 5px;
font-size: 1em;
color: var(--text-color);
}
.coins img {
width: 24px;
height: 24px;
}
/* Grid Styles */
.grid {
display: grid;
grid-template-rows: repeat(6, 1fr);
grid-gap: 8px;
margin-bottom: 30px;
}
.row {
display: grid;
grid-template-columns: repeat(5, 1fr);
grid-gap: 8px;
}
.tile {
width: 70px;
height: 70px;
border: 3px solid var(--tile-border);
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
font-size: 2em;
text-transform: uppercase;
font-weight: bold;
background-color: var(--tile-bg);
transition: background-color 0.3s, border-color 0.3s, transform 0.2s;
position: relative;
cursor: pointer;
outline: none;
}
.tile.correct {
background-color: var(--tile-correct);
border-color: var(--tile-correct);
color: white;
}
.tile.present {
background-color: var(--tile-present);
border-color: var(--tile-present);
color: white;
}
.tile.absent {
background-color: var(--tile-absent);
border-color: var(--tile-absent);
color: white;
}
.tile.active {
border-color: var(--active-border);
animation: pulse 1s infinite;
}
@keyframes pulse {
0% { border-color: var(--active-border); }
50% { border-color: #FFD700; }
100% { border-color: var(--active-border); }
}
/* Keyboard Styles */
.keyboard {
display: flex;
flex-direction: column;
align-items: center;
max-width: 700px;
width: 100%;
}
.keyboard-row {
display: flex;
margin-bottom: 8px;
}
.key {
margin: 0 6px;
padding: 12px 15px;
min-width: 45px;
height: 58px;
background-color: var(--key-bg);
color: white;
border: none;
border-radius: 6px;
cursor: pointer;
text-transform: uppercase;
font-size: 1em;
font-weight: 600;
transition: background-color 0.3s, transform 0.1s;
user-select: none;
}
.key.correct {
background-color: var(--key-correct);
}
.key.present {
background-color: var(--key-present);
}
.key.absent {
background-color: var(--key-absent);
}
.key:active {
transform: scale(0.95);
}
/* Modal Styles */
.modal {
position: fixed;
top: 0;
left: 0;
width:100%;
height:100%;
background: rgba(0,0,0,0.85);
display: flex;
align-items: center;
justify-content: center;
visibility: hidden;
opacity: 0;
transition: visibility 0s, opacity 0.3s;
z-index: 1000;
}
.modal.show {
visibility: visible;
opacity: 1;
}
.modal-content {
background: var(--modal-bg);
padding: 40px;
border-radius: 12px;
text-align: center;
max-width: 90%;
width: 400px;
animation: fadeIn 0.5s;
color: var(--text-color);
}
@keyframes fadeIn {
from { transform: scale(0.8); opacity: 0; }
to { transform: scale(1); opacity: 1; }
}
.modal-content h2 {
margin-bottom: 20px;
font-size: 2em;
}
.modal-content p {
margin-bottom: 30px;
font-size: 1.2em;
color: #CCCCCC;
}
.close-btn {
padding: 12px 25px;
background: var(--button-bg);
border: none;
border-radius: 6px;
color: white;
cursor: pointer;
font-size: 1em;
transition: background-color 0.3s, transform 0.1s;
user-select: none;
}
.close-btn:hover {
background: var(--button-hover);
}
.close-btn:active {
transform: scale(0.95);
}
/* Shop Modal Styles */
.shop-modal {
position: fixed;
top: 0;
left: 0;
width:100%;
height:100%;
background: rgba(0,0,0,0.85);
display: flex;
align-items: center;
justify-content: center;
visibility: hidden;
opacity: 0;
transition: visibility 0s, opacity 0.3s;
z-index: 1001; /* Above the message modal */
}
.shop-modal.show {
visibility: visible;
opacity: 1;
}
.shop-content {
background: var(--modal-bg);
padding: 40px;
border-radius: 12px;
text-align: center;
max-width: 90%;
width: 800px;
animation: fadeIn 0.5s;
color: var(--text-color);
max-height: 90vh;
overflow-y: auto;
}
.shop-content h2 {
margin-bottom: 20px;
font-size: 2em;
}
.shop-items {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 15px;
margin-bottom: 30px;
}
.shop-item {
background-color: var(--tile-border);
padding: 15px;
border-radius: 8px;
cursor: pointer;
transition: background-color 0.3s, transform 0.1s;
display: flex;
align-items: center;
justify-content: space-between;
font-size: 1.1em;
color: var(--text-color);
width: 220px;
}
.shop-item:hover {
background-color: var(--key-bg);
}
.shop-item:active {
transform: scale(0.98);
}
.shop-item.disabled {
background-color: #555;
cursor: not-allowed;
opacity: 0.6;
}
/* Main Menu Styles */
.menu-btn {
position: absolute;
top: 20px;
left: 20px;
background: var(--button-bg);
border: none;
border-radius: 6px;
color: white;
padding: 10px 15px;
cursor: pointer;
font-size: 1em;
transition: background-color 0.3s, transform 0.1s;
z-index: 1002;
}
.menu-btn:hover {
background: var(--button-hover);
}
.menu-btn:active {
transform: scale(0.95);
}
/* Side Menu Styles */
.side-menu {
position: fixed;
top: 0;
left: -300px;
width: 300px;
height: 100%;
background-color: var(--menu-bg);
box-shadow: 2px 0 5px rgba(0,0,0,0.5);
transition: left 0.3s;
z-index: 1001;
display: flex;
flex-direction: column;
padding: 20px;
}
.side-menu.open {
left: 0;
}
.side-menu h2 {
margin-bottom: 20px;
font-size: 1.8em;
color: var(--text-color);
text-align: center;
}
.side-menu .section {
margin-bottom: 30px;
}
.side-menu .section h3 {
margin-bottom: 10px;
font-size: 1.4em;
color: #CCCCCC;
}
.side-menu .button {
background-color: var(--button-bg);
padding: 10px 15px;
border: none;
border-radius: 6px;
cursor: pointer;
transition: background-color 0.3s, transform 0.1s;
font-size: 1em;
color: white;
margin-bottom: 10px;
}
.side-menu .button:hover {
background-color: var(--button-hover);
}
.side-menu .button:active {
transform: scale(0.98);
}
.close-menu-btn {
padding: 10px 15px;
background: var(--button-bg);
border: none;
border-radius: 6px;
color: white;
cursor: pointer;
font-size: 1em;
transition: background-color 0.3s, transform 0.1s;
user-select: none;
}
.close-menu-btn:hover {
background: var(--button-hover);
}
.close-menu-btn:active {
transform: scale(0.95);
}
/* Typing Animation */
.tile.typing {
animation: typing 0.3s forwards;
}
@keyframes typing {
from { opacity: 0; transform: scale(0.8); }
to { opacity: 1; transform: scale(1); }
}
/* Flip Animation */
@keyframes flip {
0% { transform: rotateX(0); }
50% { transform: rotateX(90deg); }
100% { transform: rotateX(0); }
}
/* Responsive Styles */
@media (max-width: 600px) {
.tile {
width: 50px;
height: 50px;
font-size: 1.5em;
}
.key {
padding: 8px 10px;
min-width: 35px;
height: 45px;
font-size: 0.9em;
}
.modal-content, .shop-content {
padding: 20px;
}
.modal-content h2, .shop-content h2 {
font-size: 1.5em;
}
.modal-content p {
font-size: 1em;
}
.close-btn, .shop-item {
font-size: 0.9em;
}
.menu-btn {
padding: 8px 12px;
font-size: 0.9em;
}
.side-menu {
width: 80%;
}
.coins {
padding: 8px 12px;
font-size: 0.9em;
}
.coins img {
width: 20px;
height: 20px;
}
}
</style>
</head>
<body>
<!-- Coin Display -->
<div class="coins">
<img src="https://img.icons8.com/emoji/48/000000/money-bag-emoji.png" alt="Coins">
<span id="coin-count">0</span>
</div>
<!-- Menu Button -->
<button class="menu-btn" id="menu-btn">☰ Menu</button>
<!-- Side Menu -->
<div class="side-menu" id="side-menu">
<h2>Main Menu</h2>
<div class="section" id="shop-section">
<h3>Shop</h3>
<button class="button" id="open-shop">🛒 Open Shop</button>
</div>
<div class="section" id="settings-section">
<h3>Settings</h3>
<button class="button" id="toggle-theme">🌓 Toggle Dark/Light Mode</button>
</div>
<button class="close-menu-btn" id="close-menu-btn">Close Menu</button>
</div>
<!-- Shop Modal -->
<div class="shop-modal" id="shop-modal">
<div class="shop-content" id="shop-content">
<h2>Shop</h2>
<div class="shop-items">
<!-- Theme Categories -->
<div class="shop-category">
<h3>🎨 Themes</h3>
<div class="shop-item" data-item="color1" data-price="5">
💠 Color Theme 1 - 5 Coins
</div>
<div class="shop-item" data-item="color2" data-price="10">
🔵 Color Theme 2 - 10 Coins
</div>
<div class="shop-item" data-item="color3" data-price="15">
🟣 Color Theme 3 - 15 Coins
</div>
<div class="shop-item" data-item="color4" data-price="20">
🟢 Color Theme 4 - 20 Coins
</div>
<div class="shop-item" data-item="color5" data-price="25">
🔴 Color Theme 5 - 25 Coins
</div>
<!-- Add more themes as needed -->
</div>
<!-- Cosmetic Enhancements -->
<div class="shop-category">
<h3>✨ Cosmetics</h3>
<div class="shop-item" data-item="sparkles" data-price="10">
✨ Sparkle Effect - 10 Coins
</div>
<div class="shop-item" data-item="glow" data-price="15">
🌟 Glow Animation - 15 Coins
</div>
<div class="shop-item" data-item="gradient" data-price="20">
🎨 Gradient Background - 20 Coins
</div>
<div class="shop-item" data-item="neon" data-price="25">
🟡 Neon Lights - 25 Coins
</div>
<!-- Add more cosmetics as needed -->
</div>
<!-- Utility Items -->
<div class="shop-category">
<h3>🔧 Utilities</h3>
<div class="shop-item" data-item="auto-fill" data-price="30">
📝 Auto-Fill - 30 Coins
</div>
<div class="shop-item" data-item="extended-lives" data-price="40">
♾️ Extended Lives - 40 Coins
</div>
<div class="shop-item" data-item="hint" data-price="35">
💡 Hint System - 35 Coins
</div>
<div class="shop-item" data-item="theme-lock" data-price="50">
🔒 Theme Lock - 50 Coins
</div>
<!-- Add more utilities as needed -->
</div>
<!-- Exclusive Items -->
<div class="shop-category">
<h3>🌟 Exclusive</h3>
<div class="shop-item" data-item="diamond-theme" data-price="60">
💎 Diamond Theme - 60 Coins
</div>
<div class="shop-item" data-item="gold-theme" data-price="70">
🥇 Gold Theme - 70 Coins
</div>
<div class="shop-item" data-item="platinum-theme" data-price="80">
💍 Platinum Theme - 80 Coins
</div>
<div class="shop-item" data-item="royal-theme" data-price="90">
👑 Royal Theme - 90 Coins
</div>
<div class="shop-item" data-item="legendary-theme" data-price="100">
🏆 Legendary Theme - 100 Coins
</div>
<!-- Add more exclusive items as needed -->
</div>
<!-- Additional Themes to reach 25 items -->
<div class="shop-category">
<h3>🎨 Additional Themes</h3>
<div class="shop-item" data-item="color6" data-price="30">
🎨 Color Theme 6 - 30 Coins
</div>
<div class="shop-item" data-item="color7" data-price="35">
🎨 Color Theme 7 - 35 Coins
</div>
<div class="shop-item" data-item="color8" data-price="40">
🎨 Color Theme 8 - 40 Coins
</div>
<div class="shop-item" data-item="color9" data-price="45">
🎨 Color Theme 9 - 45 Coins
</div>
<div class="shop-item" data-item="color10" data-price="50">
🎨 Color Theme 10 - 50 Coins
</div>
</div>
</div>
<button class="close-btn" id="close-shop-btn">Close Shop</button>
</div>
</div>
<!-- Main Title -->
<h1>Wordle Clone</h1>
<!-- Game Grid -->
<div class="grid" id="grid">
<!-- 6 Rows of 5 Tiles will be generated by JavaScript -->
</div>
<!-- On-Screen Keyboard -->
<div class="keyboard" id="keyboard">
<!-- Keyboard Rows -->
<div class="keyboard-row">
<button class="key">Q</button>
<button class="key">W</button>
<button class="key">E</button>
<button class="key">R</button>
<button class="key">T</button>
<button class="key">Y</button>
<button class="key">U</button>
<button class="key">I</button>
<button class="key">O</button>
<button class="key">P</button>
</div>
<div class="keyboard-row">
<button class="key">A</button>
<button class="key">S</button>
<button class="key">D</button>
<button class="key">F</button>
<button class="key">G</button>
<button class="key">H</button>
<button class="key">J</button>
<button class="key">K</button>
<button class="key">L</button>
</div>
<div class="keyboard-row">
<button class="key">Enter</button>
<button class="key">Z</button>
<button class="key">X</button>
<button class="key">C</button>
<button class="key">V</button>
<button class="key">B</button>
<button class="key">N</button>
<button class="key">M</button>
<button class="key">←</button>
</div>
</div>
<!-- Message Modal -->
<div class="modal" id="message-modal">
<div class="modal-content" id="message-modal-content">
<h2 id="modal-title">Congratulations!</h2>
<p id="modal-text">You guessed the word correctly.</p>
<button class="close-btn" id="close-message-btn">Close</button>
</div>
</div>
<script>
// DOM Elements
const grid = document.getElementById('grid');
const keyboard = document.getElementById('keyboard');
const messageModal = document.getElementById('message-modal');
const modalTitle = document.getElementById('modal-title');
const modalText = document.getElementById('modal-text');
const closeMessageBtn = document.getElementById('close-message-btn');
const menuBtn = document.getElementById('menu-btn');
const sideMenu = document.getElementById('side-menu');
const closeMenuBtn = document.getElementById('close-menu-btn');
const openShopBtn = document.getElementById('open-shop');
const shopModal = document.getElementById('shop-modal');
const shopContent = document.getElementById('shop-content');
const closeShopBtn = document.getElementById('close-shop-btn');
const shopItems = document.querySelectorAll('.shop-item');
const toggleThemeBtn = document.getElementById('toggle-theme');
const coinCount = document.getElementById('coin-count');
// Game State Variables
let currentRow = 0;
let currentTile = 0;
let isGameOver = false;
let solution = '';
let activeTile = null;
let isMenuOpen = false;
let isShopOpen = false;
// Coin System
let coins = 0;
// Theme Management
let currentTheme = 'default';
const themes = {
default: {
'--bg-color': '#121213',
'--text-color': '#FFFFFF',
'--tile-border': '#3a3a3c',
'--tile-bg': '#121213',
'--tile-correct': '#538D4E',
'--tile-present': '#B59F3B',
'--tile-absent': '#3A3A3C',
'--key-bg': '#818384',
'--key-correct': '#538D4E',
'--key-present': '#B59F3B',
'--key-absent': '#3A3A3C',
'--modal-bg': '#1E1E1E',
'--button-bg': '#818384',
'--button-hover': '#6c6d70',
'--menu-bg': '#1E1E1E'
},
// ... [All theme definitions up to color25 and light] ...
// Ensure all themes (color1 to color25) are defined here as per previous code
// For brevity, only a few are shown. Ensure completeness in your implementation.
// Example:
color1: {
'--bg-color': '#f0f8ff',
'--text-color': '#333333',
'--tile-border': '#b0c4de',
'--tile-bg': '#f0f8ff',
'--tile-correct': '#4682B4',
'--tile-present': '#87CEFA',
'--tile-absent': '#778899',
'--key-bg': '#b0c4de',
'--key-correct': '#4682B4',
'--key-present': '#87CEFA',
'--key-absent': '#778899',
'--modal-bg': '#e6f2ff',
'--button-bg': '#b0c4de',
'--button-hover': '#87CEFA',
'--menu-bg': '#e6f2ff'
},
// ... Add color2 to color25 and light mode similarly
};
// Apply Theme
function applyTheme(theme) {
const root = document.documentElement;
const selectedTheme = themes[theme];
for (let varName in selectedTheme) {
root.style.setProperty(varName, selectedTheme[varName]);
}
currentTheme = theme;
}
// Initialize with default theme
applyTheme('default');
// Initialize Grid
function initGrid() {
for (let i = 0; i < 6; i++) {
const row = document.createElement('div');
row.classList.add('row');
row.dataset.row = i;
for (let j = 0; j < 5; j++) {
const tile = document.createElement('div');
tile.classList.add('tile');
tile.dataset.row = i;
tile.dataset.col = j;
tile.tabIndex = 0; // Make tile focusable
tile.addEventListener('click', () => {
// Allow clicking only on tiles in the current row and not game over/menu/shop
if (i === currentRow && !isGameOver && !isMenuOpen && !isShopOpen) {
setActiveTile(i, j);
}
});
row.appendChild(tile);
}
grid.appendChild(row);
}
setActiveTile(0, 0);
}
// Fetch a random five-letter word from API
async function fetchRandomWord() {
try {
const response = await fetch('https://random-word-api.herokuapp.com/word?number=1&length=5');
const data = await response.json();
const word = data[0].toUpperCase();
console.log("Solution:", word); // For debugging
solution = word;
} catch (error) {
console.error("Error fetching random word:", error);
// Fallback word if API fails
const fallbackWords = ["APPLE", "BRAVE", "CRANE", "DREAM", "EVOKE"];
solution = fallbackWords[Math.floor(Math.random() * fallbackWords.length)];
console.log("Using fallback word:", solution);
}
}
// Validate word via Dictionary API
async function validateWord(word) {
try {
const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word.toLowerCase()}`);
if (response.ok) {
const data = await response.json();
return data && Array.isArray(data) && data.length > 0;
} else {
return false;
}
} catch (error) {
console.error("Error validating word:", error);
return false;
}
}
// Initialize Coins
function initializeCoins() {
const storedCoins = localStorage.getItem('coins');
if (storedCoins !== null) {
coins = parseInt(storedCoins);
} else {
coins = 10; // Starting coins
localStorage.setItem('coins', coins);
}
updateCoinDisplay();
}
// Update Coin Display
function updateCoinDisplay() {
coinCount.textContent = coins;
}
// Handle Keyboard Clicks
keyboard.addEventListener('click', (e) => {
if (isGameOver || isMenuOpen || isShopOpen) return;
if (e.target.classList.contains('key')) {
const key = e.target.textContent;
handleKey(key);
}
});
// Handle Physical Keyboard
document.addEventListener('keydown', (e) => {
if (isGameOver || isMenuOpen || isShopOpen) return;
const key = e.key.toUpperCase();
if (key === 'ENTER') {
handleKey('Enter');
} else if (key === 'BACKSPACE' || e.key === 'DELETE') {
handleKey('←');
} else if (/^[A-Z]$/.test(key)) {
handleKey(key);
} else if (['ARROWUP', 'ARROWDOWN', 'ARROWLEFT', 'ARROWRIGHT'].includes(e.key.toUpperCase())) {
navigateGrid(e.key.toUpperCase());
}
});
// Handle Key Input
function handleKey(key) {
if (key === 'Enter') {
submitWord();
return;
}
if (key === '←') {
deleteLetter();
return;
}
if (currentTile < 5 && currentRow < 6) {
const tile = getTile(currentRow, currentTile);
if (tile.textContent === '') {
tile.textContent = key;
tile.classList.add('typing');
setTimeout(() => {
tile.classList.remove('typing');
}, 300);
} else {
tile.textContent = key; // Replace existing letter
}
tile.classList.remove('absent', 'present', 'correct');
moveToNextTile();
}
}
// Enhanced Delete Letter Function
function deleteLetter() {
if (currentTile === 0 && currentRow === 0) {
// At the very first tile, nothing to delete
return;
}
// Determine the tile to delete: currentTile - 1
let tileToDelete = getTile(currentRow, currentTile - 1);
if (currentTile === 0 && currentRow > 0) {
// If at the start of a row and not the first row, move to the previous row
currentRow--;
currentTile = 5;
tileToDelete = getTile(currentRow, currentTile - 1);
}
if (tileToDelete.textContent !== '') {
// Delete the letter
tileToDelete.textContent = '';
tileToDelete.classList.remove('absent', 'present', 'correct');
currentTile--;
setActiveTile(currentRow, currentTile);
} else if (currentTile > 0) {
// If the current tile is empty, look for the previous filled tile
for (let i = currentTile - 2; i >= 0; i--) {
tileToDelete = getTile(currentRow, i);
if (tileToDelete.textContent !== '') {
tileToDelete.textContent = '';
tileToDelete.classList.remove('absent', 'present', 'correct');
currentTile = i;
setActiveTile(currentRow, currentTile);
break;
}
}
}
}
// Submit Word
async function submitWord() {
const row = grid.children[currentRow];
let word = '';
for (let i = 0; i < 5; i++) {
const tile = row.children[i];
word += tile.textContent;
}
if (word.length !== 5) {
showMessage("Not enough letters");
return;
}
const isValid = await validateWord(word);
if (!isValid) {
showMessage("Word not found");
return;
}
// Check letters
const solutionArr = solution.split('');
const guessArr = word.split('');
const letterStatus = Array(5).fill('absent');
// First pass for correct letters
for (let i = 0; i < 5; i++) {
if (guessArr[i] === solutionArr[i]) {
letterStatus[i] = 'correct';
solutionArr[i] = null;
}
}
// Second pass for present letters
for (let i = 0; i < 5; i++) {
if (letterStatus[i] === 'correct') continue;
const index = solutionArr.indexOf(guessArr[i]);
if (index !== -1) {
letterStatus[i] = 'present';
solutionArr[index] = null;
}
}
// Update tiles and keyboard
let correctLetters = 0;
for (let i = 0; i < 5; i++) {
const tile = row.children[i];
tile.classList.add(letterStatus[i]);
flipTile(tile, letterStatus[i]);
updateKeyboard(guessArr[i], letterStatus[i]);
if (letterStatus[i] === 'correct') {
correctLetters++;
}
}
// Reward coins for correct letters
coins += correctLetters;
localStorage.setItem('coins', coins);
updateCoinDisplay();
if (word === solution) {
isGameOver = true;
showModal("🎉 Congratulations!", `You guessed the word correctly and earned ${correctLetters} coins!`);
return;
}
currentRow++;
currentTile = 0;
if (currentRow === 6) {
isGameOver = true;
showModal("😞 Game Over", `The word was "${solution}".`);
} else {
setActiveTile(currentRow, currentTile);
}
}
// Flip Tile Animation
function flipTile(tile, status) {
tile.style.animation = "flip 0.6s forwards";
// Remove animation class after animation completes
tile.addEventListener('animationend', () => {
tile.style.animation = '';
}, { once: true });
}
// Update Keyboard Keys
function updateKeyboard(letter, status) {
const keys = Array.from(document.querySelectorAll('.key'));
for (let key of keys) {
if (key.textContent === letter) {
if (status === 'correct') {
key.classList.remove('present', 'absent');
key.classList.add('correct');
} else if (status === 'present') {
if (!key.classList.contains('correct')) {
key.classList.remove('absent');
key.classList.add('present');
}
} else {
if (!key.classList.contains('correct') && !key.classList.contains('present')) {
key.classList.add('absent');
}
}
break;
}
}
}
// Show Message Modal
function showMessage(message) {
modalTitle.textContent = "";
modalText.textContent = message;
messageModal.classList.add('show');
}
// Show End Game Modal
function showModal(title, text) {
modalTitle.textContent = title;
modalText.textContent = text;
messageModal.classList.add('show');
}
// Close Modal
function closeModal() {
messageModal.classList.remove('show');
if (isGameOver) {
resetGame();
}
}
// Get Tile by Row and Column
function getTile(row, col) {
return grid.children[row].children[col];
}
// Move to Next Tile
function moveToNextTile() {
if (currentTile < 4) {
currentTile++;
setActiveTile(currentRow, currentTile);
}
}
// Navigate Grid with Arrow Keys
function navigateGrid(direction) {
// Only allow left and right navigation within the current row
let newRow = currentRow;
let newCol = currentTile;
switch(direction) {
case 'ARROWLEFT':
newCol = currentTile > 0 ? currentTile - 1 : currentTile;
break;
case 'ARROWRIGHT':
newCol = currentTile < 4 ? currentTile + 1 : currentTile;
break;
default:
// Ignore ARROWUP and ARROWDOWN
return;
}
setActiveTile(newRow, newCol);
}
// Set Active Tile
function setActiveTile(row, col) {
if (activeTile) {
activeTile.classList.remove('active');
}
activeTile = getTile(row, col);
activeTile.classList.add('active');
activeTile.focus();
currentRow = row;
currentTile = col;
}
// Initialize Main Menu
menuBtn.addEventListener('click', () => {
sideMenu.classList.add('open');
menuBtn.style.display = 'none';
isMenuOpen = true;
});
closeMenuBtn.addEventListener('click', () => {
sideMenu.classList.remove('open');
menuBtn.style.display = 'block';
isMenuOpen = false;
setActiveTile(currentRow, currentTile); // Return focus to active tile
});
// Open Shop
openShopBtn.addEventListener('click', () => {
shopModal.classList.add('show');
isShopOpen = true;
});
// Close Shop
closeShopBtn.addEventListener('click', () => {
shopModal.classList.remove('show');
isShopOpen = false;
});
// Handle Shop Purchases
shopItems.forEach(item => {
item.addEventListener('click', () => {
// Prevent clicking on disabled items
if (item.classList.contains('disabled')) return;
const selectedItem = item.dataset.item;
const price = parseInt(item.dataset.price);
const theme = selectedItem;
if (coins >= price) {
coins -= price;
localStorage.setItem('coins', coins);
updateCoinDisplay();
applyTheme(theme);
showModal("✔️ Purchase Successful!", `You have purchased ${item.textContent}.`);
// Optionally disable the item after purchase if it's a one-time purchase
// item.classList.add('disabled');
} else {
showMessage("💰 Not enough coins");
}
});
});
// Handle Theme Toggle in Settings
toggleThemeBtn.addEventListener('click', () => {
if (currentTheme !== 'light') {
applyTheme('light');
showModal("☀️ Light Mode Enabled", "You have switched to Light Mode.");
} else {
applyTheme('default');
showModal("🌙 Dark Mode Enabled", "You have switched to Dark Mode.");
}
});
// Reset the game for a new round
async function resetGame() {
currentRow = 0;
currentTile = 0;
isGameOver = false;
// Clear all tiles
const rows = grid.children;
for (let row of rows) {
for (let tile of row.children) {
tile.textContent = '';
tile.classList.remove('absent', 'present', 'correct', 'typing', 'active');
}
}
// Reset keyboard
const keys = Array.from(document.querySelectorAll('.key'));
for (let key of keys) {
key.classList.remove('absent', 'present', 'correct');
}
// Fetch a new word
await fetchRandomWord();
setActiveTile(currentRow, currentTile);
}
// Initialize the game on page load
window.onload = async () => {
initGrid();
initializeCoins();
await fetchRandomWord();
};
// Close Modals when Close Buttons are Clicked
closeMessageBtn.addEventListener('click', closeModal);
// Prevent "Enter" key from submitting forms or other unintended behaviors
window.addEventListener('keydown', function(e) {
if (e.key === 'Enter' && (isMenuOpen || isShopOpen)) {
e.preventDefault();
}
});
</script>
</body>
</html>
Key Modifications Explained
-
Enhanced deleteLetter Function:
The primary change is in the deleteLetter function to ensure that when the user deletes a letter, it correctly removes the most recently entered letter and moves the cursor appropriately within the current row. Here's how it's achieved:
// Enhanced Delete Letter Function
function deleteLetter() {
if (currentTile === 0 && currentRow === 0) {
// At the very first tile, nothing to delete
return;
}
// Determine the tile to delete: currentTile - 1
let tileToDelete = getTile(currentRow, currentTile - 1);
if (currentTile === 0 && currentRow > 0) {
// If at the start of a row and not the first row, move to the previous row
currentRow--;
currentTile = 5;
tileToDelete = getTile(currentRow, currentTile - 1);
}
if (tileToDelete.textContent !== '') {
// Delete the letter
tileToDelete.textContent = '';
tileToDelete.classList.remove('absent', 'present', 'correct');
currentTile--;
setActiveTile(currentRow, currentTile);
} else if (currentTile > 0) {
// If the current tile is empty, look for the previous filled tile
for (let i = currentTile - 2; i >= 0; i--) {
tileToDelete = getTile(currentRow, i);
if (tileToDelete.textContent !== '') {
tileToDelete.textContent = '';
tileToDelete.classList.remove('absent', 'present', 'correct');
currentTile = i;
setActiveTile(currentRow, currentTile);
break;
}
}
}
}
What This Does:
-
Boundary Check: Ensures that deletion doesn't occur beyond the first tile of the first row.
-
Row Navigation: If the user is at the start of a row (but not the first row), pressing delete moves the cursor to the last tile of the previous row.
-
Deleting Letters:
- Deletes the letter in the current tile (if any) and moves the cursor back by one.
- If the current tile is already empty, it searches backward in the current row to find the last filled tile, deletes it, and updates the cursor position accordingly.
-
Cursor Management:
The setActiveTile function is used to visually indicate the active tile and set the focus appropriately. This ensures that after deletion, the cursor moves to the correct position for the next input.
// Set Active Tile
function setActiveTile(row, col) {
if (activeTile) {
activeTile.classList.remove('active');
}
activeTile = getTile(row, col);
activeTile.classList.add('active');
activeTile.focus();
currentRow = row;
currentTile = col;
}
Testing the Enhanced Delete Functionality
After implementing the above changes, it's essential to test the delete functionality thoroughly to ensure it behaves as expected:
-
Delete Within the Current Row:
- Enter letters in the first row.
- Press the delete (
←) key (either on the on-screen keyboard or your physical keyboard).
- The most recently entered letter should be removed, and the cursor should move back to that tile.
-
Crossing Row Boundaries:
- Complete the first row and move to the second row.
- Press the delete key at the start of the second row.
- The cursor should move back to the last tile of the first row, allowing you to delete a letter from there.
-
Edge Cases:
- Attempt to delete when at the very first tile of the first row to ensure no errors occur.
- Try deleting multiple letters in succession to verify consistent behavior.
Final Notes
-
Theme Definitions: Ensure that all themes (color1 to color25 and light mode) are appropriately defined in the themes object. For brevity, only default and color1 are shown here, but you'll need to add the rest based on your design requirements.
-
Persisting Purchases: If you want to disable items after purchase or persist user purchases, consider adding logic to handle purchased items, possibly storing them in localStorage and updating the UI accordingly.
-
Accessibility: Ensure that all interactive elements are accessible via keyboard navigation and screen readers for an inclusive user experience.
With these modifications, your Wordle clone should have a more intuitive and responsive delete functionality, enhancing the overall gameplay experience. If you encounter any issues or have further customizations in mind, feel free to ask!