Create a Wordle Game in HTML,CSS, and JS

WHAT TO KNOW - Sep 8 - - Dev Community

<!DOCTYPE html>



Create Your Own Wordle Game with HTML, CSS, and JavaScript

<br> body {<br> font-family: sans-serif;<br> margin: 0;<br> padding: 20px;<br> }</p> <p>h1, h2, h3 {<br> text-align: center;<br> }</p> <p>.container {<br> display: flex;<br> flex-direction: column;<br> align-items: center;<br> justify-content: center;<br> height: 100vh;<br> }</p> <p>.wordle-board {<br> display: grid;<br> grid-template-columns: repeat(5, 50px);<br> grid-template-rows: repeat(6, 50px);<br> gap: 5px;<br> }</p> <p>.tile {<br> width: 50px;<br> height: 50px;<br> border: 2px solid #ccc;<br> border-radius: 5px;<br> display: flex;<br> justify-content: center;<br> align-items: center;<br> font-size: 24px;<br> cursor: pointer;<br> transition: background-color 0.2s;<br> }</p> <p>.tile.correct {<br> background-color: #6aaa64; /* Green */<br> }</p> <p>.tile.present {<br> background-color: #c9b458; /* Yellow */<br> }</p> <p>.tile.absent {<br> background-color: #787c7e; /* Dark Gray */<br> }</p> <h1> <a name="keyboard-" href="#keyboard-" class="anchor"> </a> keyboard { </h1> <p>display: flex;<br> flex-wrap: wrap;<br> justify-content: center;<br> margin-top: 20px;<br> }</p> <p>.keyboard-key {<br> width: 40px;<br> height: 40px;<br> border: 1px solid #ccc;<br> border-radius: 5px;<br> margin: 5px;<br> display: flex;<br> justify-content: center;<br> align-items: center;<br> font-size: 18px;<br> cursor: pointer;<br> transition: background-color 0.2s;<br> }</p> <p>.keyboard-key.correct {<br> background-color: #6aaa64; /* Green */<br> }</p> <p>.keyboard-key.present {<br> background-color: #c9b458; /* Yellow */<br> }</p> <p>.keyboard-key.absent {<br> background-color: #787c7e; /* Dark Gray */<br> }</p> <p>.message {<br> margin-top: 20px;<br> text-align: center;<br> }<br>



Building Your Own Wordle










<br> // 1. Setup:<br> const board = document.getElementById(&#39;wordle-board&#39;);<br> const keyboard = document.getElementById(&#39;keyboard&#39;);<br> const message = document.getElementById(&#39;message&#39;);<br> const wordLength = 5; // Wordle&#39;s standard word length<br> const maxGuesses = 6; // Wordle&#39;s standard number of guesses<br> let currentRow = 0;<br> let currentColumn = 0;<br> let wordToGuess = &#39;&#39;;<br> let guessedLetters = [];<br> let gameOver = false;</p> <p>// 2. Choose the Secret Word:<br> function chooseWord() {<br> const words = [<br> &#39;crane&#39;, &#39;apple&#39;, &#39;piano&#39;, &#39;house&#39;, &#39;water&#39;, &#39;beach&#39;, &#39;ocean&#39;, &#39;earth&#39;,<br> &#39;train&#39;, &#39;cloud&#39;, &#39;smile&#39;, &#39;music&#39;, &#39;light&#39;, &#39;bread&#39;, &#39;power&#39;, &#39;space&#39;,<br> // Add your own words here!<br> ];<br> const randomIndex = Math.floor(Math.random() * words.length);<br> wordToGuess = words[randomIndex].toUpperCase();<br> }</p> <p>// 3. Generate the Keyboard:<br> function createKeyboard() {<br> const alphabet = &#39;ABCDEFGHIJKLMNOPQRSTUVWXYZ&#39;;<br> const keys = alphabet.split(&#39;&#39;);<br> keys.push(&#39;ENTER&#39;);<br> keys.push(&#39;DELETE&#39;);</p> <p>keys.forEach(key =&gt; {<br> const keyElement = document.createElement(&#39;div&#39;);<br> keyElement.classList.add(&#39;keyboard-key&#39;);<br> keyElement.textContent = key;<br> keyElement.addEventListener(&#39;click&#39;, () =&gt; handleKeyboardInput(key));<br> keyboard.appendChild(keyElement);<br> });<br> }</p> <p>// 4. Generate the Board:<br> function createBoard() {<br> for (let i = 0; i &lt; maxGuesses; i++) {<br> for (let j = 0; j &lt; wordLength; j++) {<br> const tile = document.createElement(&#39;div&#39;);<br> tile.classList.add(&#39;tile&#39;);<br> tile.dataset.row = i;<br> tile.dataset.column = j;<br> tile.addEventListener(&#39;click&#39;, () =&gt; handleTileClick(tile));<br> board.appendChild(tile);<br> }<br> }<br> }</p> <p>// 5. Event Handlers:</p> <p>// Handle tile clicks (for keyboard-less interaction)<br> function handleTileClick(tile) {<br> if (gameOver || currentRow &gt;= maxGuesses || tile.textContent) return;<br> if (currentColumn &lt; wordLength) {<br> tile.textContent = guessedLetters[currentColumn] || &#39;&#39;;<br> currentColumn++;<br> }<br> }</p> <p>// Handle keyboard input<br> function handleKeyboardInput(key) {<br> if (gameOver) return;<br> if (key === &#39;ENTER&#39;) {<br> handleEnterPress();<br> } else if (key === &#39;DELETE&#39;) {<br> handleBackspacePress();<br> } else {<br> handleLetterPress(key);<br> }<br> }</p> <p>// Handle letter presses<br> function handleLetterPress(letter) {<br> if (currentColumn &lt; wordLength) {<br> guessedLetters[currentColumn] = letter;<br> updateBoard();<br> currentColumn++;<br> }<br> }</p> <p>// Handle backspace press<br> function handleBackspacePress() {<br> if (currentColumn &gt; 0) {<br> currentColumn--;<br> guessedLetters[currentColumn] = &#39;&#39;;<br> updateBoard();<br> }<br> }</p> <p>// Handle enter press<br> function handleEnterPress() {<br> if (currentColumn === wordLength) {<br> const guessedWord = guessedLetters.join(&#39;&#39;);<br> if (guessedWord.length === wordLength) {<br> const result = checkGuess(guessedWord);<br> updateBoard(result);<br> updateKeyboard(result);<br> guessedLetters = [];<br> currentColumn = 0;<br> currentRow++;<br> if (result.includes(&#39;correct&#39;) &amp;&amp; result.length === wordLength) {<br> gameOver = true;<br> message.textContent = &#39;You guessed it!&#39;;<br> } else if (currentRow &gt;= maxGuesses) {<br> gameOver = true;<br> message.textContent = <code>The word was ${wordToGuess}</code>;<br> }<br> } else {<br> message.textContent = &#39;Please enter a 5-letter word.&#39;;<br> }<br> }<br> }</p> <p>// 6. Update Board and Keyboard:</p> <p>// Update the visual representation of the board<br> function updateBoard(result = []) {<br> const tiles = board.querySelectorAll(&#39;.tile&#39;);<br> for (let i = 0; i &lt; wordLength; i++) {<br> const tile = tiles[currentRow * wordLength + i];<br> if (tile.textContent) {<br> if (result[i] === &#39;correct&#39;) {<br> tile.classList.add(&#39;correct&#39;);<br> } else if (result[i] === &#39;present&#39;) {<br> tile.classList.add(&#39;present&#39;);<br> } else if (result[i] === &#39;absent&#39;) {<br> tile.classList.add(&#39;absent&#39;);<br> }<br> }<br> }<br> }</p> <p>// Update the keyboard based on the guess result<br> function updateKeyboard(result = []) {<br> const keys = keyboard.querySelectorAll(&#39;.keyboard-key&#39;);<br> result.forEach((letter, index) =&gt; {<br> const key = keys[letter.charCodeAt(0) - 65]; // A = 65 in ASCII<br> if (key) {<br> if (letter === &#39;correct&#39;) {<br> key.classList.add(&#39;correct&#39;);<br> } else if (letter === &#39;present&#39;) {<br> key.classList.add(&#39;present&#39;);<br> } else if (letter === &#39;absent&#39; &amp;&amp; !key.classList.contains(&#39;present&#39;)) {<br> key.classList.add(&#39;absent&#39;);<br> }<br> }<br> });<br> }</p> <p>// 7. Check the Guess:</p> <p>// Compare the guessed word to the secret word and return the result<br> function checkGuess(guessedWord) {<br> let result = [];<br> const wordArray = wordToGuess.split(&#39;&#39;);</p> <p>// Check for exact matches (green)<br> for (let i = 0; i &lt; wordLength; i++) {<br> if (guessedWord[i] === wordArray[i]) {<br> result[i] = &#39;correct&#39;;<br> wordArray[i] = &#39;&#39;; // Mark the letter as used<br> }<br> }</p> <p>// Check for present letters (yellow)<br> for (let i = 0; i &lt; wordLength; i++) {<br> if (result[i] !== &#39;correct&#39; &amp;&amp; wordArray.includes(guessedWord[i])) {<br> result[i] = &#39;present&#39;;<br> wordArray[wordArray.indexOf(guessedWord[i])] = &#39;&#39;; // Mark the letter as used<br> } else if (result[i] === undefined) {<br> result[i] = &#39;absent&#39;;<br> }<br> }</p> <p>return result;<br> }</p> <p>// 8. Initialize the Game:</p> <p>chooseWord();<br> createBoard();<br> createKeyboard();<br>

Introduction

Welcome to the world of Wordle! This popular word game has captivated players with its simplicity and addictive nature. In this article, we'll delve into the process of creating your own Wordle game using HTML, CSS, and JavaScript.

Why build your own Wordle?

  • Customization: You can tailor the game to your preferences, choosing different word lists, difficulty levels, and game modes.
  • Learning: It's an excellent way to enhance your web development skills, specifically in HTML, CSS, and JavaScript, with a fun and engaging project.
  • Sharing: You can share your creation with friends and family, or even deploy it online for others to enjoy.

Building Your Wordle Game

We'll break down the development process into eight key steps:

1. Setup

  • HTML Structure:

    • Create a basic HTML file (index.html) with the following structure:
    <!DOCTYPE html>
    <html>
    <head>
    <title>
    Wordle Game
    </title>
    <link href="style.css" rel="stylesheet"/>
    </head>
    <body>
    <div class="container">
    <div class="wordle-board" id="wordle-board">
    </div>
    <div id="keyboard">
    </div>
    <div class="message" id="message">
    </div>
    </div>
    <script src="script.js">
    </script>
    </body>
    </html>
    
  • CSS Styling (style.css):

    • Style the game elements using CSS. The provided CSS code in the HTML above will give you a basic Wordle layout. You can customize colors, fonts, and spacing to your liking.
  • JavaScript Logic (script.js):

    • Create a JavaScript file (script.js) to handle the game logic, including:
    • Choosing a secret word
    • Generating the game board and keyboard
    • Handling user input (letter presses, enter, backspace)
    • Checking the guess and updating the board and keyboard
    • Determining game over conditions (correct guess or maximum guesses reached)

2. Choosing the Secret Word

  • Word List: Create an array of words to use in your game. You can use a pre-existing word list or create your own.
  • Random Selection: Use Math.random() to randomly select a word from the array.
const words = [
  'crane', 'apple', 'piano', 'house', 'water', 'beach', 'ocean', 'earth',
  'train', 'cloud', 'smile', 'music', 'light', 'bread', 'power', 'space'
];
const randomIndex = Math.floor(Math.random() * words.length);
const wordToGuess = words[randomIndex].toUpperCase();

3. Generating the Keyboard

  • Keyboard Layout: Create a container for the keyboard (in your HTML) and then dynamically create buttons for each letter, 'ENTER', and 'DELETE' using JavaScript.
  • Event Listeners: Attach click event listeners to each keyboard button to handle user input.
const keyboard = document.getElementById('keyboard');
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const keys = alphabet.split('');
keys.push('ENTER');
keys.push('DELETE');

keys.forEach(key =&gt; {
  const keyElement = document.createElement('div');
  keyElement.classList.add('keyboard-key');
  keyElement.textContent = key;
  keyElement.addEventListener('click', () =&gt; handleKeyboardInput(key));
  keyboard.appendChild(keyElement);
});

4. Generating the Board

  • Grid Structure: Use CSS grid layout to create a grid of tiles for the game board. Each tile will represent a letter in the word.
  • Dynamic Creation: Dynamically create the tiles using JavaScript, setting their row and column properties for later reference.
  • Event Listeners: Add click event listeners to each tile to allow users to interact with the board directly (optional, as you can also use the keyboard).
const board = document.getElementById('wordle-board');
const maxGuesses = 6; // Wordle's standard number of guesses
const wordLength = 5; // Wordle's standard word length

for (let i = 0; i &lt; maxGuesses; i++) {
  for (let j = 0; j &lt; wordLength; j++) {
    const tile = document.createElement('div');
    tile.classList.add('tile');
    tile.dataset.row = i;
    tile.dataset.column = j;
    tile.addEventListener('click', () =&gt; handleTileClick(tile)); // Optional
    board.appendChild(tile);
  }
}

5. Event Handlers

  • Key Press Handling (handleKeyboardInput):
    • This function will be called whenever a keyboard key is pressed.
    • Distinguish between letter keys, 'ENTER', and 'DELETE'.
    • For letter keys, store the letter in the guessedLetters array.
    • For 'ENTER', check if the word is complete and valid; if so, call checkGuess().
    • For 'DELETE', remove the last letter from the guessedLetters array.
  • Tile Click Handling (handleTileClick):
    • This function (optional) will be called when a tile on the board is clicked.
    • Allow the user to input a letter into the tile if the current row and column are valid.
let currentRow = 0;
let currentColumn = 0;
let guessedLetters = [];
let gameOver = false;

// Handle keyboard input
function handleKeyboardInput(key) {
  if (gameOver) return;
  if (key === 'ENTER') {
    handleEnterPress();
  } else if (key === 'DELETE') {
    handleBackspacePress();
  } else {
    handleLetterPress(key);
  }
}

// Handle letter presses
function handleLetterPress(letter) {
  if (currentColumn &lt; wordLength) {
    guessedLetters[currentColumn] = letter;
    updateBoard(); // Update the board to reflect the letter
    currentColumn++;
  }
}

// Handle backspace press
function handleBackspacePress() {
  if (currentColumn &gt; 0) {
    currentColumn--;
    guessedLetters[currentColumn] = ''; // Clear the letter at the current position
    updateBoard(); // Update the board to reflect the change
  }
}

// Handle enter press
function handleEnterPress() {
  if (currentColumn === wordLength) {
    const guessedWord = guessedLetters.join('');
    if (guessedWord.length === wordLength) {
      const result = checkGuess(guessedWord);
      updateBoard(result); // Update the board with the result of the guess
      updateKeyboard(result); // Update the keyboard with the result of the guess
      guessedLetters = [];
      currentColumn = 0;
      currentRow++;
      if (result.includes('correct') &amp;&amp; result.length === wordLength) {
        gameOver = true;
        message.textContent = 'You guessed it!';
      } else if (currentRow &gt;= maxGuesses) {
        gameOver = true;
        message.textContent = `The word was ${wordToGuess}`;
      }
    } else {
      message.textContent = 'Please enter a 5-letter word.';
    }
  }
}

// Handle tile clicks (for keyboard-less interaction)
function handleTileClick(tile) {
  if (gameOver || currentRow &gt;= maxGuesses || tile.textContent) return;
  if (currentColumn &lt; wordLength) {
    tile.textContent = guessedLetters[currentColumn] || '';
    currentColumn++;
  }
}

6. Update Board and Keyboard

  • Board Updates (updateBoard):
    • This function is called after each guess to visually update the board.
    • It will set the background color of each tile based on the result (correct, present, absent) returned by checkGuess().
  • Keyboard Updates (updateKeyboard):
    • This function is called to visually update the keyboard based on the guess result.
    • Highlight letter keys in green, yellow, or gray to indicate their status.
// Update the visual representation of the board
function updateBoard(result = []) {
  const tiles = board.querySelectorAll('.tile');
  for (let i = 0; i &lt; wordLength; i++) {
    const tile = tiles[currentRow * wordLength + i];
    if (tile.textContent) {
      if (result[i] === 'correct') {
        tile.classList.add('correct');
      } else if (result[i] === 'present') {
        tile.classList.add('present');
      } else if (result[i] === 'absent') {
        tile.classList.add('absent');
      }
    }
  }
}

// Update the keyboard based on the guess result
function updateKeyboard(result = []) {
  const keys = keyboard.querySelectorAll('.keyboard-key');
  result.forEach((letter, index) =&gt; {
    const key = keys[letter.charCodeAt(0) - 65]; // A = 65 in ASCII
    if (key) {
      if (letter === 'correct') {
        key.classList.add('correct');
      } else if (letter === 'present') {
        key.classList.add('present');
      } else if (letter === 'absent' &amp;&amp; !key.classList.contains('present')) {
        key.classList.add('absent');
      }
    }
  });
}

7. Check the Guess

  • checkGuess function: This function compares the guessed word to the secret word and returns an array indicating the status of each letter:
    • 'correct': The letter is in the correct position.
    • 'present': The letter is in the word but in the wrong position.
    • 'absent': The letter is not in the word.
  • Logic:
    1. Exact Matches (Green): Iterate through each letter in the guessed word and compare it to the corresponding letter in the secret word. If they match, mark the result as 'correct' and remove the letter from the secret word array to avoid duplicate yellow highlighting.
    2. Present Letters (Yellow): Iterate through each letter in the guessed word again. If the letter is not already marked as 'correct' and is present in the remaining secret word array, mark the result as 'present'. Remove the letter from the secret word array to prevent multiple yellow markings for the same letter.
    3. Absent Letters (Gray): For any letter in the guessed word that wasn't marked 'correct' or 'present', mark the result as 'absent'.
// Compare the guessed word to the secret word and return the result
function checkGuess(guessedWord) {
  let result = [];
  const wordArray = wordToGuess.split('');

  // Check for exact matches (green)
  for (let i = 0; i &lt; wordLength; i++) {
    if (guessedWord[i] === wordArray[i]) {
      result[i] = 'correct';
      wordArray[i] = ''; // Mark the letter as used
    }
  }

  // Check for present letters (yellow)
  for (let i = 0; i &lt; wordLength; i++) {
    if (result[i] !== 'correct' &amp;&amp; wordArray.includes(guessedWord[i])) {
      result[i] = 'present';
      wordArray[wordArray.indexOf(guessedWord[i])] = ''; // Mark the letter as used
    } else if (result[i] === undefined) {
      result[i] = 'absent';
    }
  }

  return result;
}

8. Initialize the Game

  • Run Game Logic: Call the necessary functions to set up the game:
    • chooseWord() to select the secret word.
    • createBoard() to generate the game board.
    • createKeyboard() to generate the keyboard.
// 8. Initialize the Game:

chooseWord();
createBoard();
createKeyboard();

Conclusion

Congratulations! You've successfully built your own Wordle game using HTML, CSS, and JavaScript. You've learned how to:

  • Create a game board and keyboard using HTML and CSS.
  • Handle user input using JavaScript event listeners.
  • Implement the core game logic, including choosing a secret word, checking guesses, and updating the game interface.

Best Practices:

  • Modular Code: Break your code into well-defined functions for improved readability and maintainability.
  • Error Handling: Add error handling to address invalid inputs or unexpected situations.
  • Accessibility: Ensure your game is accessible to all users by using appropriate ARIA attributes and semantic HTML.
  • Testing: Thoroughly test your game to catch any bugs or errors.

Now, you have the foundation to expand your Wordle game with exciting features:

  • Custom Difficulty: Implement different word lengths or allow players to choose from multiple word lists.
  • Game Modes: Add features like "hard mode" where correct letters must be used in subsequent guesses.
  • Themes: Change the game's appearance by adding themes with different color palettes.

Let your creativity flourish and build the ultimate Wordle experience!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player