#Blog

How to Structure Code: Wordle Game Example

One common challenge for new coders is learning how to properly structure their code. Most often, beginners would add all their code in a single file or function. This practice leads to unstable code and making any update on the existing code very difficult.

In this post, let’s learn how to properly structure your code by designing a simple version of the popular Wordle game. If you’ve never played Wordle, check it out here.

Wordle Game Image

Understand the Requirements and User Flow

Before writing any code, consider both the user flow and data flow. This will help you understand how to structure the code efficiently.

Here’s a rough outline of the game’s functionality:

  1. The game engine chooses the word for the day
  2. The user enters their input
  3. The game engine returns the score for the input word
  4. Continue this loop for 6 times or until the user guesses the word correctly
  5. Save user results

How to Modularize the Code?

We can create the following files or services based on the game flow we have decided:

  1. GameEngine
  2. UserInput
  3. GameResult

Let’s add the following functions to our services:

GameEngine

  • getTodaysWord() - The words can be stored in a database, a CSV file, or as simple as in-memory.
  • getScore(todaysWord, userInput) - Returns the score for the user input word.

UserInput

  • readInput()
  • validateInput(userInput) - Add validations like ensuring the input word is five characters and a valid dictionary word.

GameResult

  • saveUserScore(score) - If the user is logged in, save the result in a database; otherwise, save it in browser cache.

This is a good starting point to make your code modular. We can see that there is no overlap between any of the functions. If we modify the code in any of the above functions, it won’t impact the others. For example, if I modify the saveUserScore function to save in a different database, it wouldn’t require re-testing any of the other functions.

More posts

Blog|Youtube|Careers|Contact Us
Have Feedback or want to contribute? Email: hello[@]100DaysOfCode.io
100DaysOfCode@2024