DEV Community

Amro
Amro

Posted on

Building a Scrabble-like Word Puzzle Generator: From Concept to Code

Introduction

Word puzzle games like Scrabble challenge players to form valid words from a set of random letters. In this article, we'll break down how to build a Scrabble-like word puzzle generator in Python. We'll cover:

Game Mechanics (Tile Distribution, Word Validation, Scoring)

Algorithm Design (Generating Tiles, Finding Possible Words)

Pseudocode & Implementation

Enhancements & Variations
Enter fullscreen mode Exit fullscreen mode
  1. Game Mechanics 1.1 Tile Distribution (Letter Frequency & Points)

Scrabble uses a predefined distribution of letters based on their frequency in the English language. For example:

Common letters (E, A, I, O) appear more frequently.

Rare letters (Q, Z, X) have higher point values.
Enter fullscreen mode Exit fullscreen mode

Example Distribution (Simplified):
Letter Count Points
A 9 1
B 2 3
... ... ...
Z 1 10
1.2 Word Validation

Input: A set of letters (e.g., ['A', 'B', 'C', 'E']).

Output: All valid English words that can be formed (e.g., "CAB", "ACE").

Constraints:

    Words must exist in a dictionary.

    Letters can be used only once (unless duplicates exist).
Enter fullscreen mode Exit fullscreen mode

1.3 Scoring System

Each letter has a point value. The total score of a word is the sum of its letters' points.

  1. Algorithm Design 2.1 Generating Random Tiles

We need a function to randomly select tiles following Scrabble’s distribution rules.

Pseudocode:

FUNCTION generate_tiles(num_tiles):
    tile_bag = []
    FOR each letter in LETTER_DISTRIBUTION:
        ADD letter to tile_bag (repeated based on its count)
    SHUFFLE tile_bag
    RETURN first num_tiles letters
Enter fullscreen mode Exit fullscreen mode

2.2 Finding Valid Words

Given a set of letters, we check all possible combinations against a dictionary.

Pseudocode:

FUNCTION find_possible_words(letters, dictionary):
    possible_words = []
    FOR each word in dictionary:
        IF can_form_word(letters, word):
            ADD word to possible_words
    RETURN possible_words sorted by length & score
Enter fullscreen mode Exit fullscreen mode

Helper Function (can_form_word):

FUNCTION can_form_word(letters, word):
    letter_counts = COUNT each letter in letters
    FOR each letter in word:
        IF letter exists in letter_counts:
            REDUCE count by 1
        ELSE IF blank tile exists:
            USE blank tile
        ELSE:
            RETURN False
    RETURN True
Enter fullscreen mode Exit fullscreen mode

2.3 Calculating Word Scores

FUNCTION calculate_score(word):
    score = 0
    FOR each letter in word:
        score += LETTER_POINTS[letter]
    RETURN score
Enter fullscreen mode Exit fullscreen mode
  1. Python Implementation 3.1 Core Code Structure
import random
from collections import defaultdict

# Scrabble letter distribution & points
LETTER_DISTRIBUTION = {
    'A': {'count': 9, 'value': 1},
    'B': {'count': 2, 'value': 3},
    # ... (full distribution)
}

def generate_tiles(num_tiles=7):
    tile_bag = []
    for letter, data in LETTER_DISTRIBUTION.items():
        tile_bag.extend([letter] * data['count'])
    random.shuffle(tile_bag)
    return tile_bag[:num_tiles]

def can_form_word(letters, word):
    letter_counts = defaultdict(int)
    blank_count = letters.count(' ')  # Wildcards
    for letter in letters:
        if letter != ' ':
            letter_counts[letter] += 1
    for letter in word:
        if letter_counts[letter] > 0:
            letter_counts[letter] -= 1
        elif blank_count > 0:
            blank_count -= 1
        else:
            return False
    return True

def calculate_score(word):
    return sum(LETTER_DISTRIBUTION[letter]['value'] for letter in word)

def find_possible_words(letters, dictionary):
    return [word for word in dictionary if can_form_word(letters, word)]
Enter fullscreen mode Exit fullscreen mode

3.2 Example Usage

tiles = generate_tiles(7)  # Get 7 random tiles
dictionary = load_dictionary("words.txt")  # Load word list
possible_words = find_possible_words(tiles, dictionary)

print("Your letters:", " ".join(tiles))
print("Possible words:")
for word in sorted(possible_words, key=lambda x: (-len(x), calculate_score(x)):
    print(f"{word} ({len(word)} letters, {calculate_score(word)} points)")
Enter fullscreen mode Exit fullscreen mode
  1. Enhancements & Variations
    4.1 Additional Features

    Difficulty Levels (Adjust number of tiles)

    Time Challenge Mode (Solve within a time limit)

    Multiplayer Support (Turn-based gameplay)

4.2 Optimizations

Memoization (Cache previously checked words)

Trie Data Structure (For faster dictionary searches)
Enter fullscreen mode Exit fullscreen mode

4.3 Alternative Game Modes

Anagrams (Find all permutations of letters)

Crossword Helper (Find words matching a pattern, e.g., C?T → "CAT", "COT")
Enter fullscreen mode Exit fullscreen mode

Conclusion

We’ve built a Scrabble-like puzzle generator that:

Randomly selects tiles following Scrabble rules.

Finds valid words from a dictionary.

Calculates scores based on letter values.
Enter fullscreen mode Exit fullscreen mode

Next Steps:

Add a GUI (Tkinter, Pygame).

Integrate with a larger word database.

Implement multiplayer functionality.
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.