DEV Community

XZM27
XZM27

Posted on

Wordle with python

Lets create the famous wordle game in python

  • How the game works:
    • learn by playing it yourself: wordle
  • Prerequisite:
    • classes and objects
    • pip install clrprint

Basic template
lets create the basic template for the game

import random
from clrprint import *


class Wordle:
    """main game class"""
    def __init__(self: object) -> None:
        """initialize attributes"""
        # word list and current word
        self.words = ["HELLO","WORLD","CRANE","BREAD",
                      "GIVER","GREAT","NEVER"]
        self.current_word = random.choice(self.words)

        self.current_row = 0

        self.letter_found = False

    def run_game(self: object) -> None:
        """main game runner class"""
        while self.current_row < 6 and not self.letter_found:
            pass       


if __name__ == "__main__":
    w_game = Wordle()
    w_game.run_game()
Enter fullscreen mode Exit fullscreen mode
  • __init__

    • Firstly we import random and clrprint. We will use clrprint to give colored outputs in our shell.
    • We define the main game class Wordle
    • We create a list of words self.words out of which one will be the current word self.current_word
    • More words can be added to self.words
    • We get the self.current_word using random.choice(self.words)
    • We initialize self.current_row. This will help us to keep track when the player has exhausted 6 tries.
    • We set self.letter_found = False so that when the letter is found we can stop the game
  • run_game

    • This contains the while loop for the game.
    • We run the while loop until the player has exhausted his tries or the player finds the word.
    • For the moment we run pass
  • starting the game

    • We create the objeect of Wordle as w_game under if __name__ == "__main__":
    • We call the run_game method using w_game.run_game()

Taking user input and incrementing self.current_row
Alright now we need to take the users input.

  • The user input must have a length of 5
  • It must be contained in "self.words"
  • If the input is valid then we increment self.current_row by 1 Lets create a method _check_row to accomplish this and we will call _check_row in the while loop.
--snip--
    def run_game(self: object) -> None:
        """main game runner class"""
        while self.current_row < 6 and not self.letter_found:
            self._check_row()

    def _check_row(self: object) -> None:
        """"handle the try count"""
        print(f"Number of tries: {self.current_row + 1}")
        user_word = input("enter word: ").upper()
        if len(user_word) == 5 and user_word in self.words:
            self.current_row += 1
            self.compare_word(user_word)
        else:
            print("input five letter word which is in word list")

    def compare_word(self: object, user_input: str) -> None:
        """compare user input to current word"""
        pass

--snip--
Enter fullscreen mode Exit fullscreen mode
  • run_game

    • We call the freshly baked _check_row in the while loop
  • _check_row

    • We print the current number of tries of the player
    • We take the users input user_word and use .upper() to covert the user input into uppercase
    • We check if the input is valid or not
    • For a valid input we increment self.current_row by 1
    • We need some logic to comapre the user input with our self.current_word. We create a new method for that called compare_wordand leave it with pass for the moment.
    • If the user input is invalid we do not incrememnt self.current_row and humbly ask the user to input a five letter word which is in self.words. We can run the game now. For valid inputs the tries will increment and when we reach 6 tries the game will stop. So far so good, but we still need to give the game its backbone logic.

Comparing the user input and urrent word and adding logic

  • Wordle logic:
    • If the letter is not in the actual word: grey
    • If the letter is in the actual word and in the correct position: green
    • If the letter is in the actual word and not in the correct position: yellow

We can implement this logic easily enumerate(). Also if the player finds the word we want to stop the game.

--snip--
    def compare_word(self: object, user_input: str) -> None:
        """compare user input to current word"""
        if user_input == self.current_word:
                clrprint("You found the letter", clr="red")
                self.letter_found = True

        else:
            for letter_index, letter in enumerate(user_input):
                if letter == self.current_word[letter_index]:
                    clrprint(f"{letter} is in the word and in correct position", clr="green")
                elif letter in self.current_word:
                    clrprint(f"{letter} is in the word but not in correct position", clr="yellow")
                else:
                    print(f"{letter} is not in the word")
--snip--
Enter fullscreen mode Exit fullscreen mode
  • compare_word(self: object, user_input: str) -> None

    • The compare_word method takes an argument user_input which is the user input.
    • Firstly we check if the user has found the word.
    • If the user finds the word we print a congatulations message and then set self.letter_found to True. This stops the while loop from running and ends the game.
    • clrprint allows us to give colored outputs in the shell.
    • If the word is not found we implement our logic part.
    • In the for loop we iterate through user_input
    • enumerate() adds a counter to the iterable and returns it.
    • We store two iterating variables- letter_index, letter
    • We then check if letter matches self.current_word[letter_index]. This compares the letter in both user input and current word at the same positions.
    • If the letter is not found in the same position we check if the letter is in the current word.
    • If none of the above holds truthy we output that the letter is not in the word.
    • We do this checking for every letter in the user input using the for loop.

SOURCE CODE

import random
from clrprint import *


class Wordle:
    """main game class"""
    def __init__(self: object) -> None:
        """initialize attributes"""
        # word lst and current word
        self.words = ["HELLO","WORLD","CRANE","BREAD","GIVER","GREAT","NEVER"]
        self.current_word = random.choice(self.words)

        self.current_row = 0

        self.letter_found = False

    def run_game(self: object) -> None:
        """main game runner class"""
        while self.current_row < 6 and not self.letter_found:
            self._check_row()

    def _check_row(self: object) -> None:
        """"handle the try count"""
        print(f"Number of tries: {self.current_row + 1}")
        user_word = input("enter word: ").upper()
        if len(user_word) == 5 and user_word in self.words:
            self.current_row += 1
            self.compare_word(user_word)
        else:
            print("input five letter word which is in word list")

    def compare_word(self: object, user_input: str) -> None:
        """compare user input to current word"""
        if user_input == self.current_word:
                clrprint("You found the letter", clr="red")
                self.letter_found = True

        else:
            for letter_index, letter in enumerate(user_input):
                if letter == self.current_word[letter_index]:
                    clrprint(f"{letter} is in the word and in correct position", clr="green")
                elif letter in self.current_word:
                    clrprint(f"{letter} is in the word but not in correct position", clr="yellow")
                else:
                    print(f"{letter} is not in the word")



if __name__ == "__main__":
    w_game = Wordle()
    w_game.run_game()

Enter fullscreen mode Exit fullscreen mode

The game is now ready to be played. Add more words to self.words to make the game more challenging.

From the author:
Please do comment any improvements/ bugs in the game. Thank you for reading and learning :)

Top comments (0)