Koodi struktureerimine

Mõned inimesed arvavad, et kui kood töötab, siis see on hea kood ja rohkem sellest oodata ei tohi. Tõenäoliselt need inimesed ei saa kunagi headeks progejateks. Kuna programmeerimine nõuab tihti rühmatööd, peab kood olema ka lisaks autorile ka teistele arusaadav. Isegi projekti üksi arendades võib olla kogu protsess drastiliselt raskendatud, kui sa ei jälgi koodi modulaarsuse ja struktureerituse reegleid.

Koodi modulaarsus tähendab seda, et kogu kood jaotatakse väikesteks iseseivateks osadeks, näiteks funktsioonideks, klassideks ja mooduliteks. Kui kood koosneb iseseisvatest plokkidest, siis seda on lihtne muuta, lisades uut funktsionaalsust või muutes juba olemasolevat. Samuti on sellest koodist lihtsam aru saada.

Proovime teha näiteks lihtsa hangman-i. Kasutaja valib keerukuse ja üritab ennustada sõna, mis on valitud juhuslikult ette antud nimekirjast.

Halb näide antud programmist:

import random as r

words_hard = [
    "table", "star", "root", "flat", "turtle", "fish", "goat", "rocket",
    "dragon", "power", "source", "program", "wheel", "candle", "dog", "cat", "branch"
]

words_easy = [
    "dragonborn", "monosaccharide", "disposable", "environment",
    "implementation", "disorientation", "carbohydrate", "disrespectful", "dominant"
]

difficulty = input("Please select difficulty('h' for 'hard' and 'e' for 'easy'): ")

if difficulty == 'h':
    words = words_hard
elif difficulty == 'e':
    words = words_easy
else:
    raise ValueError("Not allowed input")

word = r.choice(words)
guesses = len(word)
guess_word = ["*"] * len(word)

while True:
    print(f"\nGuesses left: {guesses}")
    print(f"The word is: {''.join(guess_word)}")

    char = input("Please enter single character: ")
    if char in word:
        for i in range(len(word)):
            guess_word[i] = char if word[i] == char else guess_word[i]
    else:
        print(f"The character {char} is not in the word!")
        guesses -= 1

    if "".join(guess_word) == word:
        print("\nYou won!")
        print(f"The word is: {word}")
        break

    if guesses == 0:
        print("\nYou lost!")
        print(f"The word was {word}")
        break

Hea näide antud programmist:

import random as r


def select_difficulty(words_hard, words_easy) -> list:

    difficulty = input("Please select difficulty ('h' for 'hard' and 'e' for 'easy'): ")

    if difficulty == 'h':
        words = words_hard
    elif difficulty == 'e':
        words = words_easy
    else:
        raise ValueError("Not allowed input")

    return words


def update_word(word, guess_word, char):

    for i in range(len(word)):
        if word[i] == char:
            guess_word[i] = char


def track_game_state(word, guess_word, guesses) -> bool:

    if "".join(guess_word) == word:
        print("\nYou won!")
        print(f"The word is: '{word}'")
        return True

    if guesses == 0:
        print("\nYou lost!")
        print(f"The word was '{word}'")
        return True

    return False


def game(words_hard: list, words_easy: list):

    words = select_difficulty(words_hard, words_easy)

    word = r.choice(words)
    guesses = len(word)
    guess_word = ["*"] * len(word)

    finished = False

    while not finished:
        print(f"\nGuesses left: {guesses}")
        print(f"The word is: {''.join(guess_word)}")

        char = input("Please enter single character: ")

        if char not in word:
            print(f"The character '{char}' is not in the word!")
            guesses -= 1
        else:
            update_word(word, guess_word, char)

        finished = track_game_state(word, guess_word, guesses)


def main():

    hard = [
        "table", "star", "root", "flat", "turtle", "fish", "goat", "rocket",
        "dragon", "power", "source", "program", "wheel", "candle", "dog", "cat", "branch"
    ]

    easy = [
        "dragonborn", "monosaccharide", "disposable", "environment",
        "implementation", "disorientation", "carbohydrate", "disrespectful", "dominant"
    ]

    game(words_hard=hard, words_easy=easy)


if __name__ == '__main__':
    main()