Skip to content

Conversation

@R4f43lVB
Copy link
Owner

@R4f43lVB R4f43lVB commented Mar 12, 2025

Coesão:

Inicialmente havia apenas um loop que era responsável por reagir a todas as teclas apertadas no menu (Fechar o jogo, mudar a dificuldade, etc) Foi criada uma nova função que reage à seleção de dificuldade.

Abstração:

De forma similar, antes as teclas apertadas durante o jogo eram gerenciadas por um grande loop dentro do arquivo do jogo, então foi gerada uma nova função para lidar com os comandos de movimento do jogador

Summary by Sourcery

Refactors the game logic to improve code organization and readability. It introduces new functions to handle difficulty selection and player movement commands, which were previously managed within a single loop.

Enhancements:

  • Improves code structure by extracting difficulty selection logic into a dedicated function.
  • Improves code structure by extracting player movement logic into a dedicated function.

@sourcery-ai
Copy link

sourcery-ai bot commented Mar 12, 2025

Reviewer's Guide by Sourcery

This pull request refactors the game's code to improve its structure and readability. It introduces new functions to handle specific tasks, such as difficulty selection and event handling. This makes the code more modular and easier to maintain.

Sequence diagram for difficulty selection

sequenceDiagram
    participant User
    participant titulo.py

    User->>titulo.py: Selects difficulty (1, 2, 3, or 9)
    activate titulo.py
    titulo.py->>titulo.py: usa_teclas(event)
    activate titulo.py
    titulo.py->>titulo.py: seleciona_dificuldade(event.key)
    activate titulo.py
    titulo.py-->>titulo.py: Returns fps (10, 15, 30, or 70)
    deactivate titulo.py
    titulo.py-->>User: Returns fps
    deactivate titulo.py
Loading

File-Level Changes

Change Details Files
The difficulty selection logic was extracted into a new function.
  • Created a seleciona_dificuldade function to handle difficulty selection based on key presses.
  • The main loop in titulo.py now calls seleciona_dificuldade to set the game's FPS.
titulo.py
The event handling logic in the title screen was extracted into a new function.
  • Created a usa_teclas function to handle keyboard events and quit events.
  • The main loop in titulo.py now calls usa_teclas to handle events.
titulo.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @R4f43lVB - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider extracting the game logic into a separate class to further improve abstraction.
Here's what I looked at during the review
  • 🟡 General issues: 8 issues found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 2 issues found
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

pygame.display.set_caption('Jogo da cobrinha')
fps = 15

assets = baixar_assets()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (performance): Duplicate asset loading detected.

The function baixar_assets() is called twice consecutively without a change in state between the calls. It would be more efficient to load the assets only once, unless there is a specific reason for refreshing them.

Suggested implementation:

pygame.display.set_caption('Jogo da cobrinha')
fps = 15
assets = baixar_assets()
# Sons e Musica do jogo
pygame.mixer.music.load('assets/musica_jogo6.mp3')

# Configurações das paredes (o player morre quando encosta nas paredes)
while True:
    # janela=pygame.display.set_mode((janela_comp,janela_alt))

Make sure that there is no other call to baixar_assets() inside the loop or elsewhere causing duplicate asset loading.

Comment on lines +36 to +42
for event in pygame.event.get():
if usa_teclas(event) is not None:
if usa_teclas(event) == False:
tela = False
else:
fps = usa_teclas(event)
print(fps)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (performance): Avoid redundant calls to usa_teclas(event).

usa_teclas(event) is being called multiple times in the same event loop block, which may lead to inconsistent state or unnecessary repeated operations. Consider storing its result in a variable and using that instead.

Suggested change
for event in pygame.event.get():
if usa_teclas(event) is not None:
if usa_teclas(event) == False:
tela = False
else:
fps = usa_teclas(event)
print(fps)
for event in pygame.event.get():
result = usa_teclas(event)
if result is not None:
if result is False:
tela = False
else:
fps = result
print(fps)

Como rodar o jogo:
Para rodar o jogo basta abrir o repositório e no arquivo Jogo rodar o programa.
Quando o jogo abrir aparecerá uma tela com o titulo e opções de dificuldade correspodendo:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (typo): Typo: 'correspodendo' should be 'correspondendo'.

Suggested change
Quando o jogo abrir aparecerá uma tela com o titulo e opções de dificuldade correspodendo:
Quando o jogo abrir aparecerá uma tela com o titulo e opções de dificuldade correspondendo:

3-Difícil 30 FPS (velocidade e dificuldade elevadas)
9-Ipossível 70 FPS (Velocidade e dificuldade extremas, não é para amadores)
Para seslcionar a dificuldade basta precinar a tecla correspondete caso não seja selecionada o jogo rodará na dificuldade média
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (typo): Typo: 'seslcionar' should be 'selecionar'.

Para seslcionar a dificuldade basta precinar a tecla correspondete caso não seja selecionada o jogo rodará na dificuldade média
Após selecionar a dificuldade basta prssionar a tela ENTER
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (typo): Typo: 'prssionar' should be 'pressionar'.

Suggested change
Após selecionar a dificuldade basta prssionar a tela ENTER
Após selecionar a dificuldade basta pressionar a tela ENTER

Como rodar o jogo:
Para rodar o jogo basta abrir o repositório e no arquivo Jogo rodar o programa.
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Clarify what "arquivo Jogo" refers to.

It's unclear what the user should be looking for. Is it a Python file with a specific name? Providing more context would be helpful.

Suggested change
Para rodar o jogo basta abrir o repositório e no arquivo Jogo rodar o programa.
-Para rodar o jogo, basta abrir o repositório e executar o arquivo "jogo.py". Se o jogo for um script Python, você pode iniciá-lo com o comando:
python jogo.py

# janela=pygame.display.set_mode((janela_comp,janela_alt))
pygame.display.set_caption('Jogo da cobrinha')
fps = 15

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): Consider extracting repeated initialization sequences into helper functions to reduce duplication and improve code clarity, such as asset loading and fruit position generation, and then calling these functions in the appropriate places to avoid re-initialization within loops, which simplifies the code and makes it easier to maintain and understand without altering the game's functionality..

The code currently re-initializes the same state (e.g. re-fetching assets and re-setting the fruit position/spawn) multiple times. To reduce duplication and improve clarity without changing functionality, consider extracting these repeated sequences into helper functions. For example:

def init_assets():
    return baixar_assets()

def get_new_fruit():
    return [random.randrange(1, (janela_comp // 10)) * 10,
            random.randrange(1, (janela_alt // 10)) * 10]

# Initial setup
pygame.display.set_caption('Jogo da cobrinha')
fps = 15
assets = init_assets()
fruta_pos = get_new_fruit()
fruta_spawn = True

Then remove the second occurrences of these initializations in the inner loop. This consolidates state setup and reduces clutter.

if evento == pygame.K_1:
return 10
elif evento == pygame.K_2:
return 15
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): Consider calling usa_teclas(event) once and storing the result in a variable to avoid redundant processing and simplify control flow within the event loop in the titulo function, as it is currently being called three times for each event, which is inefficient and makes the code harder to read..

You’re calling usa_teclas(event) three times. This redundant processing can be streamlined by calling it once per event. For example, instead of:

for event in pygame.event.get():
    if usa_teclas(event) is not None:
        if usa_teclas(event) == False:
            tela = False
        else:
            fps = usa_teclas(event)
            print(fps)

you could store the result in a variable:

for event in pygame.event.get():
    resultado = usa_teclas(event)
    if resultado is not None:
        if resultado is False:
            tela = False
        else:
            fps = resultado
            print(fps)

This change maintains all functionality while reducing redundant calls and simplifying the control flow.

# Configurações da janela do jogo

# Configurações das paredes (o player morre quando encosta nas paredes)
while True:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (code-quality): Hoist statements out of for/while loops (hoist-statement-from-loop)

Comment on lines +28 to +29
fps = seleciona_dificuldade(evento.key)
return fps
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code-quality): Inline variable that is immediately returned (inline-immediately-returned-variable)

Suggested change
fps = seleciona_dificuldade(evento.key)
return fps
return seleciona_dificuldade(evento.key)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants