Meu primeiro projeto em Python: um jogo da forca nerd em ASCII

Ilustração: um homem com uma cobra e um livro de Python diante de um laptop

🌐 Também em: English · Deutsch · Français · Español · Italiano · Nederlands · Polski

Pois é, faz alguns dias que ando brincando com Python — quase tudo teoria, revisando variáveis, loops, condicionais e os suspeitos de sempre. E como todo programador iniciante em sã consciência, decidi que meu primeiro projeto “de verdade” tinha que ser algo épico.

Naturalmente, isso significava… jogo da forca.

É o desafio perfeito para iniciantes:

  • Você pratica variáveis registrando as letras chutadas e as tentativas erradas.
  • Você usa loops para o fluxo do jogo.
  • Você espalha condicionais para decidir quem vive ou morre (bom, em ASCII).

Depois de algumas tentativas e erros (e uma boa dose de “Ah é, Python diferencia maiúsculas de minúsculas”), consegui fazer a minha versão funcionar. Admito que deixei o ChatGPT “turbinar” algumas partes — mas, ei, é assim que a gente aprende mais rápido, né?

O que ele faz

  • Escolhe uma palavra aleatória de uma lista predefinida
  • Mostra um boneco de palitinho em ASCII a cada chute errado
  • Deixa você chutar letras ou a palavra inteira
  • Lida com maiúsculas, minúsculas e chutes repetidos
  • Exibe meus superpoderes crescentes em Python

Por que eu adoro

Não é só um jogo — é uma pequena cápsula do tempo de onde estou agora na minha jornada de programação.

Daqui a alguns meses vou olhar para isso e pensar: “Uau… eu evoluí muito.”

Mas, por enquanto, é pura alegria ver meu terminal se encher de underscores, arte ASCII e mensagens de vitória (ou derrotas trágicas).

Considerações finais

Se você está começando com Python, faça um jogo da forca. Sério. É o playground perfeito para experimentar com loops, lógica e a magia do ASCII. E se você conseguir deixar o código limpo e rodando sem bugs, já ganhou.

library.py

words = ["Apfel", "Banane", "Mango", "Kirsche", "Pfirsich", "Linux", "Kernel", "Docker", "Ansible", "Python"]

logo = ['''
 _                                             
| |                                            
| |__   __ _ _ __   __ _ _ __ ___   __ _ _ __  
| '_ \ / _` | '_ \ / _` | '_ ` _ \ / _` | '_ \ 
| | | | (_| | | | | (_| | | | | | | (_| | | | |
|_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_|
                    __/ |                      
                   |___/''']

HANGMANPICS = ['''
  +---+
  |   |
      |
      |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
      |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
  |   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
=========''']

main.py

# =============================================================================
# Hangman Game
#
# File: main.py
# Author: Raphael Münch
# Email: you@example.com
# Website: https://www.apt-upgrade.me
#
# Created: 2025-08-15
# Last Updated: 2025-08-15
#
# Description:
#   A simple Hangman game played in the console.
#   Includes ASCII art, word guessing, and configurable max attempts.
#
# Copyright (c) 2025 Raphael Münch. All rights reserved.
#
# License:
#   This software is licensed under the MIT License.
#   You may use, copy, modify, merge, publish, distribute, sublicense,
#   and/or sell copies of the Software, provided the copyright notice
#   above appears in all copies.
#
# =============================================================================

import library
import os
import random

DEBUG = False

while True:
    # Clear the console (Windows = 'cls', others = 'clear')
    os.system('cls' if os.name == 'nt' else 'clear')
    print(library.logo[0])

    chosen_word = random.choice(library.words)
    word_lower = chosen_word.lower()

    # Create a mask: "_" for each letter in the word
    mask = ["_"] * len(chosen_word)

    guessed_letters = ""           # Letters guessed in the current round
    wrong_attempts = 0              # Count of wrong guesses
    max_attempts = len(library.HANGMANPICS) - 1  # e.g., 6 wrong guesses allowed
    found_letter = False

    while True:
        print(f"Your guesses: {guessed_letters}")
        print(f"Current word: {' '.join(mask)}")
        if DEBUG:
            print(f"Chosen word: {chosen_word}")
        print(f"Attempt: {wrong_attempts}/{max_attempts}")

        choice = input("Enter a letter or guess the word: ").strip()

        # Whole word guess
        if len(choice) > 1:
            if choice.lower() == word_lower:
                mask = list(chosen_word)  # Reveal the whole word
                print("You win!!!")
                break
            else:
                wrong_attempts += 1
                print(f"\n\n{library.HANGMANPICS[min(wrong_attempts, max_attempts)]}")
                if wrong_attempts >= max_attempts:
                    print("\n\aYou've lost!!!")
                    print(f"The word was: {chosen_word}")
                    break
                continue

        # Single letter guess
        if not choice:
            continue
        guess = choice.lower()

        # Skip if letter already guessed
        if guess in guessed_letters:
            print("Already guessed. Try another letter.")
            continue

        guessed_letters += guess

        # Check if guess matches any letter in the word
        found_letter = False
        for i, ch in enumerate(word_lower):
            if guess == ch:
                mask[i] = chosen_word[i]   # Preserve original case
                found_letter = True

        if not found_letter:
            wrong_attempts += 1

        print(f"\n\n{library.HANGMANPICS[min(wrong_attempts, max_attempts)]}")

        if wrong_attempts >= max_attempts:
            print("\n\aYou've lost!!!")
            print(f"The word was: {chosen_word}")
            break

        if "".join(mask).lower() == word_lower:
            print("You win!!!")
            break

    answer = input("Do you want to play again (y/n)? ").strip().lower()
    if answer != "y":
        break

Captura de tela do terminal com o jogo da forca em ASCII feito em Python

Alguns textos e imagens deste site foram criados com a ajuda de IA ou gerados por IA. Detalhes