personagem = pygame.Rect(100, 100, TAMANHO_JOGADOR, TAMANHO_JOGADOR)
Criar os inimigos
inimigos = [pygame.Rect(random.randint(0, TAMANHO_PAINEL - TAMANHO_INIMIGO), random.randint(0, TAMANHO_PAINEL - TAMANHO_INIMIGO), TAMANHO_INIMIGO, TAMANHO_INIMIGO) for _ in range(10)]
Criar a arma
arma = pygame.Rect(300, 300, TAMANHO_ARMA, TAMANHO_ARMA)
Definir o pontuador
pontuador = 0
Definir a vida
vida = TAMANHO_VIDA
Função para atualizar a tela
def atualizar_tela():
tela.fill(BRANCO)
pygame.draw.rect(tela, PRETO, personagem)
for inimigo in inimigos:
pygame.draw.rect(tela, (255, 0, 0), inimigo)
pygame.draw.rect(tela, VERDE, arma)
Função para gerenciar o evento
def gerenciar_evento(event):
global vida
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and vida > 0:
# Firing a arma
disparar_arma()
elif event.key == pygame.K_r:
# Reiniciar o jogo
personagem.x = 100
personagem.y = 100
inimigos = [pygame.Rect(random.randint(0, TAMANHO_PAINEL - TAMANHO_INIMIGO), random.randint(0, TAMANHO_PAINEL - TAMANHO_INIMIGO), TAMANHO_INIMIGO, TAMANHO_INIMIGO) for _ in range(10)]
vida = TAMANHO_VIDA
pontuador = 0
Função para disparar a arma
def disparar_arma():
global vida
# Cria um projétil
projétil = pygame.Rect(personagem.x + personagem.width / 2, personagem.y + personagem.height / 2, TAMANHO_ARMA, TAMANHO_ARMA)
# Muda a direção do projétil
dx = random.choice([-1, 1])
dy = -30
# Adiciona o projétil à lista de projéteis
projéteis.append(projétil)
Função para atualizar os projéteis
def atualizar_projéteis():
global vida
for i, projétil in enumerate(projéteis):
# Desenha o projétil
pygame.draw.rect(tela, (0, 0, 255), projétil)
# Atualiza a posição do projétil
projétil.y += dy
# Verifica se o projétil colidiu com um inimigo ou não
for j, inimigo in enumerate(inimigos):
if projétil.colliderect(inimigo):
# Inimigo morto
inimigos.pop(j)
vida += 1
pontuador += 10
# Remove o projétil da lista
projéteis.pop(i)
Função para atualizar a vida
def atualizar_vida():
global vida
if vida <= 0:
# Jogo terminado
tela.fill(BRANCO)
font = pygame.font.Font(None, 36)
texto = font.render("Jogador morto! Pressione R para reiniciar.", True, PRETO)
tela.blit(texto, (TAMANHO_PAINEL / 2 - 150, TAMANHO_PAINEL / 2))
Assistant
Função para atualizar o pontuador
def atualizar_pontuador():
global pontuador
font = pygame.font.Font(None, 36)
texto = font.render(f"Pontuador: {pontuador}", True, PRETO)
tela.blit(texto, (10, 10))
Listas de projéteis e inimigos
projéteis = []
inimigos_projeteis = []
Loop principal do jogo
while vida > 0:
# Processa os eventos
gerenciar_evento(pygame.event.get())
# Atualiza a tela
atualizar_tela()
# Atualiza os projéteis e inimigos
for i, projétil in enumerate(projéteis):
atualizar_projéteis()
if projétil.y < 0:
projéteis.pop(i)
for j, inimigo in enumerate(inimigos):
# Atualiza a posição do inimigo
inimigo.x += random.choice([-1, 1])
inimigos_projeteis.append((inimigo, projéteis))
if inimigo.y < 0 or inimigo.y > TAMANHO_PAINEL - TAMANHO_INIMIGO:
inimigos.pop(j)
# Atualiza a vida
atualizar_vida()
# Atualiza o pontuador
atualizar_pontuador()
# Limpa a tela
pygame.display.update()
Loop principal do jogo
while vida > 0:
# Processa os eventos
gerenciar_evento(pygame.event.get())
# Atualiza a tela
atualizar_tela()
# Atualiza os projéteis e inimigos
for i, projétil in enumerate(projéteis):
atualizar_projéteis()
if projétil.y < 0:
projéteis.pop(i)
for j, inimigo in enumerate(inimigos):
# Atualiza a posição do inimigo
inimigo.x += random.choice([-1, 1])
inimigos_projeteis.append((inimigo, projéteis))
if inimigo.y < 0 or inimigo.y > TAMANHO_PAINEL - TAMANHO_INIMIGO:
inimigos.pop(j)
# Atualiza a vida
atualizar_vida()
# Atualiza o pontuador
atualizar_pontuador()
# Verifica se o jogador morreu ou conquistou o objetivo
if vida <= 0:
break
elif len(inimigos) == 0 and pontuador >= 500:
vida += 10
inimigos = [pygame.Rect(random.randint(0, TAMANHO_PAINEL - TAMANHO_INIMIGO), random.randint(0, TAMANHO_PAINEL - TAMANHO_INIMIGO), TAMANHO_INIMIGO, TAMANHO_INIMIGO) for _ in range(10)]
pontuador = 0
Tela de vitória ou derrota
tela.fill(BRANCO)
font = pygame.font.Font(None, 36)
texto = font.render("Você ganhou!", True, PRETO) if vida > 0 else font.render("Jogador morto! Pressione R para reiniciar.", True, PRETO)
tela.blit(texto, (TAMANHO_PAINEL / 2 - 100, TAMANHO_PAINEL / 2))
pygame.display.update()
Loop principal do jogo novamente
while True:
gerenciar_evento(pygame.event.get())
atualizar_tela()
# Atualiza os projéteis e inimigos
for i, projétil in enumerate(projéteis):
atualizar_projéteis()
if projétil.y < 0:
projéteis.pop(i)
for j, (inimigo, _) in enumerate(inimigos_projeteis):
# Atualiza a posição do inimigo
inimigo.x += random.choice([-1, 1])
if inimigo.y > TAMANHO_PAINEL - TAMANHO_INIMIGO:
inimigos.pop(j)
del inimigos_projeteis[j]
# Atualiza a vida
atualizar_vida()
# Verifica se o jogador morreu ou conquistou o objetivo
if vida <= 0 or len(inimigos) == 0 and pontuador >= 500:
break
# Limita a velocidade do jogo
pygame.time.Clock().tick(60)
Função para atualizar os inimigos e verificar colisões
def atualizar_inimigos():
global vida
global inimigos
for i, inimigo in enumerate(inimigos):
inimigo.x += random.choice([-1, 1])
if inimigo.x < 0 or inimigo.x > TAMANHO_PAINEL - TAMANHO_INIMIGO:
inimigos.pop(i)
vida -= 10
for projéteil in projéteis:
if projéteil.colliderect(inimigo):
inimigos.pop(i)
projéteis.remove(projéteil)
vida += 20
Função para atualizar os projéteis e verificar colisões
def atualizar_projeteis():
global projéteis
for i, projéteil in enumerate(projéteis):
projéteil.y -= 5
if projéteil.y < 0:
projéteis.pop(i)
for inimigo in inimigos:
if projéteil.colliderect(inimigo):
inimigos.pop(inimigos.index(inimigo))
projéteis.pop(projéteis.index(projéteil))
vida += 10
Função para atualizar o jogo
def atualizar_jogo():
global vida
global pontuador
screen.fill(BRANCO)
# Desenha o painel de controle
pygame.draw.rect(screen, PRETO, (100, 500, 200, 50), 1)
texto = font.render("Reiniciar", True, PRETO)
screen.blit(texto, (110, 510))
pygame.draw.rect(screen, PRETO, (300, 500, 100, 50), 1)
texto = font.render("Desafio difícil", True, PRETO)
screen.blit(texto, (310, 510))
# Desenha o painel de vida
pygame.draw.rect(screen, VERMELHO, (10, 10, 200, 30))
texto = font.render("Vida: " + str(vida), True, PRETO)
screen.blit(texto, (20, 25))
# Desenha os inimigos
atualizar_inimigos()
for i, inimigo in enumerate(inimigos):
pygame.draw.rect(screen, VERMELHO, inimigo)
# Desenha os projéteis
atualizar_projeteis()
for i, projéteil in enumerate(projéteis):
pygame.draw.rect(screen, AZUL, projéteil)
# Desenha o pontuador
atualizar_pontuador()
# Verifica se o jogador morreu ou conquistou o objetivo
if vida <= 0 or len(inimigos) == 0 and pontuador > 0:
print("Parabéns, você ganhou!")
pygame.quit()
quit()
# Atualiza a tela
pygame.display.update()
Função para inicializar o jogo
def iniciar_jogo():
global vida
global pontuador
global inimigos
global projéteis
vida = 100
pontuador = 0
inimigos = [pygame.Rect(random.randint(0, TAMANHO_PAINEL - TAMANHO_INIMIGO), random.randint(0, TAMANHO_PAINEL - TAMANHO_INIMIGO), TAMANHO_INIMIGO, TAMANHO_INIMIGO) for _ in range(5)]
projéteis = []
clock = pygame.time.Clock()
running = True
while running:
# Eventos
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and projéteis == []:
projéteis.append(pygame.Rect(inimigos[0].x + TAMANHO_INIMIGO // 2, inimigos[0].y + TAMANHO_INIMAGO // 2, 10, 10))
# Atualização
atualizar_jogo()
clock.tick(60)
pygame.quit()
Inicializa o jogo
iniciar_jogo()
Função para gerenciar a velocidade dos inimigos
def aumentar_velocidade_inimigos():
global velocidade_inimigos
if velocidade_inimigos < 2:
velocidade_inimigos += 0.1
Função para reduzir a vida do jogador
def reduzir_vida_jogador():
global vida
vida -= 10
Função para aumentar a pontuação do jogador
def aumentar_pontuacao():
global pontuador
pontuador += 1
vida = 100
pontuador = 0
inimigos = [pygame.Rect(random.randint(0, TAMANHO_PAINEL - TAMANHO_INIMIGO), random.randint(0, TAMANHO_PAINEL - TAMANHO_INIMAGO), TAMANHO_INIMIGO, TAMANHO_INIMAGO) for _ in range(5)]
projéteis = []
velocidade_inimigos = 1
while True:
# Eventos
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# Aumentar velocidade dos inimigos
aumentar_velocidade_inimigos()
# Reduzir vida do jogador
reduzir_vida_jogador()
# Aumentar pontuação do jogador
if len(inimigos) == 0:
aumentar_pontuacao()
inimigos = [pygame.Rect(random.randint(0, TAMANHO_PAINEL - TAMANHO_INIMIGO), random.randint(0, TAMANHO_PAINEL - TAMANHO_INIMAGO), TAMANHO_INIMIGO, TAMANHO_INIMOGO) for _ in range(5)]
# Desenhar tudo
screen.fill((0, 0, 0))
desenhar_painel_controle()
desenhar_painel_vida()
desenhar_inimigos()
desenhar_projeteis()
desenhar_pontuacao()
pygame.display.update()
# Limitar FPS
clock.tick(60)
Função para verificar colisão entre o jogador e um inimigo
def verificar_colisao_jogador_inimigo():
global vida
for i, inimigo in enumerate(inimigos):
if inimigo.colliderect(jogador):
reduzir_vida_jogador()
inimigos.pop(i)
break
Função para verificar colisão entre o jogador e um projétil
def verificar_colisao_jogador_projeteis():
global pontuador
for i, projéteil in enumerate(projéteis):
if projéteil.colliderect(jogador):
projetéis.pop(i)
break
Função para verificar colisão entre um projétil e um inimigo
def verificar_colisao_projeteis_inimigos():
global pontuador
for i, projéteil in enumerate(projéteis):
for j, inimigo in enumerate(inimigos):
if projéteil.colliderect(inimigo):
projetéis.pop(i)
inimigos.pop(j)
break
Função para atualizar a situação do jogo
def atualizar_situação_jogo():
global vida
global pontuador
global inimigos
global projéteis
verificar_colisao_jogador_inimigo()
verificar_colisao_jogador_projeteis()
verificar_colisao_projeteis_inimigos()
vida = 100
pontuador = 0
inimigos = [pygame.Rect(random.randint(0, 700), random.randint(0, 500), 50, 50) for _ in range(5)]
projéteis = []
velocidade_inimigos = 1
Definir a posição do jogador
jogador = pygame.Rect(350, 550, 50, 50)
while True:
# Eventos
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# Aumentar velocidade dos inimigos
aumentar_velocidade_inimigos()
# Reduzir vida do jogador
reduzir_vida_jogador()
# Aumentar pontuação do jogador
if len(inimigos) == 0:
pontuador += 1
print("Pontuação:", pontuador)
# Obter as teclas pressionadas
teclas = pygame.key.get_pressed()
# Movimentar o jogador
if teclas[pygame.K_UP]:
jogador.y -= 5
if teclas[pygame.K_DOWN]:
jogador.y += 5
if teclas[pygame.K_LEFT]:
jogador.x -= 5
if teclas[pygame.K_RIGHT]:
jogador.x += 5
# Limitar a posição do jogador
jogador.x = max(0, min(jogador.x, 700))
jogador.y = max(0, min(jogador.y, 500))
# Atualizar a situação do jogo
atualizar_situação_jogo()
# Desenhar tudo
screen.fill((0, 0, 0))
pygame.draw.rect(screen, (255, 0, 0), jogador)
desenhar_painel_controle()
desenhar_painel_vida()
for inimigo in inimigos:
pygame.draw.rect(screen, (0, 255, 0), inimigo)
for projéteil in projetéis:
pygame.draw.rect(screen, (0, 0, 255), projéteil)
# Verificar se há projetis
if teclas[pygame.K_SPACE] and projetéis == []:
projetéis.append(pygame.Rect(jogador.centerx, jogador.top, 10, 20))
# Movimentar os inimigos
for i, inimigo in enumerate(inimigos):
inimigo.x += velocidade_inimigos
if inimigo.x > 700:
inimigos.pop(i)
pontuador -= 1
print("Pontuação:", pontuador)
pygame.display.update()
# Limitar FPS
clock.tick(60)
It looks like you're developing a game using Pygame, but you're encountering some issues with your code. Let's analyze your code, identify the problems, and provide solutions to help you get your game running smoothly.
Understanding the Issues:
Repeated and Redundant Code:
You have multiple main loops and functions redefined multiple times. This can cause confusion and unforeseen bugs.
Functions like gerenciar_evento, atualizar_tela, atualizar_inimigos, and others are defined more than once.
Variable Scope Issues:
Variables like inimigos, vida, pontuador, and projéteis are modified inside functions without declaring them as global, so changes inside the functions don't affect the global variables.
For example, in gerenciar_evento, you modify vida without declaring it as global.
Undefined Variables and Attributes:
Some variables like TAMANHO_PROJÉTIL are used but not defined.
Using evento.pos for a KEYDOWN event, but KEYDOWN events don't have a pos attribute.
The variables dx and dy are not correctly scoped.
Logic Errors and Incorrect Function Usage:
The way you're handling events and updating the game state has logical flaws.
Populating and iterating over a list while modifying it can lead to unexpected behavior.
Collisions and game over conditions are not consistently checked.
Lack of Structure:
The code lacks organization, making it difficult to follow or debug.
There's no clear separation of concerns or use of classes to manage game objects.
Solutions and Recommendations:
Let's address these issues step by step.
1. Clean Up and Organize Your Code
Remove Duplicated Code:
Go through your code and remove any duplicated functions and loops.
Ensure that each function is defined only once.
Organize Your Code Structure:
Use functions and possibly classes to encapsulate different aspects of your game (e.g., player, enemies, projectiles).
Keep your main game loop clean and focused on calling these functions.
2. Fix Variable Scope Issues
Declare Global Variables When Modifying Them Inside Functions:
When a function needs to modify a global variable, you must declare it as global inside the function.
def gerenciar_evento(event):
global vida, inimigos, pontuador, projéteis
# Rest of your code
Example for disparar_arma:
def disparar_arma():
global projéteis
# Rest of your code
3. Define All Necessary Variables
Ensure All Variables Are Defined Before Use:
Define TAMANHO_PROJÉTIL if you plan to use it.
Initialize variables like dx and dy within the appropriate scope.
Correct Usage of Event Attributes:
For KEYDOWN events, do not use evento.pos. Position attributes are only available for mouse events like MOUSEBUTTONDOWN.
Fixing the Event Handling:
def gerenciar_evento(eventos):
global vida, inimigos, pontuador, projéteis
for evento in eventos:
if evento.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif evento.type == pygame.KEYDOWN:
if evento.key == pygame.K_r:
# Reset the game
vida = 100
pontuador = 0
projéteis.clear()
inimigos = [pygame.Rect(random.randint(0, TAMANHO_PAINEL - TAMANHO_INIMIGO),
random.randint(0, TAMANHO_PAINEL - TAMANHO_INIMIGO),
TAMANHO_INIMIGO, TAMANHO_INIMIGO) for _ in range(10)]
elif evento.key == pygame.K_SPACE:
disparar_arma()
4. Correct Function Logic and Object Movement
Handle dx and dy Correctly:
In disparar_arma(), you set dx and dy, but they are not used correctly in atualizar_projéteis().
You need to associate movement velocities with each projectile.
Modify Projectile Handling:
Implement a projectile class or modify your projectiles to include movement:
class Projetil:
def __init__(self, x, y, dx, dy):
self.rect = pygame.Rect(x, y, TAMANHO_ARMA, TAMANHO_ARMA)
self.dx = dx
self.dy = dy
Update your disparar_arma and atualizar_projéteis functions accordingly.
5. Simplify and Standardize Your Main Game Loop
Single Main Loop:
Ensure you have only one main game loop that:
Handles events.
Updates game state.
Renders graphics.
Maintains consistent game timing using pygame.time.Clock.
6. Use Object-Oriented Programming (Optional but Recommended)
Implementing classes for your game objects makes your code cleaner and easier to manage.
Example:
class Player:
def __init__(self):
self.rect = pygame.Rect(100, 100, TAMANHO_JOGADOR, TAMANHO_JOGADOR)
self.lives = 3
self.score = 0
def move(self, dx, dy):
self.rect.x += dx
self.rect.y += dy
class Enemy:
# Define enemy attributes and methods
class Projectile:
# Define projectile attributes and methods
7. Sample Simplified Code
Here's a simplified version of your game with corrections applied.
import pygame
import sys
import random
pygame.init()
# Constants
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
PLAYER_SIZE = 50
ENEMY_SIZE = 30
PROJECTILE_SIZE = 10
FPS = 60
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
# Screen setup
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()
# Player
player = pygame.Rect(SCREEN_WIDTH // 2, SCREEN_HEIGHT - PLAYER_SIZE - 10, PLAYER_SIZE, PLAYER_SIZE)
# Enemy list
enemies = [pygame.Rect(random.randint(0, SCREEN_WIDTH - ENEMY_SIZE),
random.randint(-1500, -ENEMY_SIZE),
ENEMY_SIZE, ENEMY_SIZE) for _ in range(10)]
# Projectile list
projectiles = []
# Game variables
score = 0
lives = 3
font = pygame.font.Font(None, 36)
running = True
while running:
clock.tick(FPS)
# -- Event Handling --
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# -- Controls --
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player.left > 0:
player.x -= 5
if keys[pygame.K_RIGHT] and player.right < SCREEN_WIDTH:
player.x += 5
if keys[pygame.K_SPACE]:
# Add a projectile
projectile = pygame.Rect(player.centerx - PROJECTILE_SIZE // 2, player.top - PROJECTILE_SIZE, PROJECTILE_SIZE, PROJECTILE_SIZE)
projectiles.append(projectile)
# -- Game Logic --
# Move projectiles
for projectile in projectiles[:]:
projectile.y -= 10
if projectile.bottom < 0:
projectiles.remove(projectile)
# Move enemies
for enemy in enemies[:]:
enemy.y += 3
if enemy.top > SCREEN_HEIGHT:
enemies.remove(enemy)
lives -= 1
if lives <= 0:
running = False
# Check collisions
for enemy in enemies[:]:
if player.colliderect(enemy):
enemies.remove(enemy)
lives -= 1
if lives <= 0:
running = False
for projectile in projectiles[:]:
if enemy.colliderect(projectile):
enemies.remove(enemy)
projectiles.remove(projectile)
score += 10
break # Avoid modifying list while iterating
# -- Drawing --
screen.fill(WHITE)
pygame.draw.rect(screen, BLACK, player)
for enemy in enemies:
pygame.draw.rect(screen, RED, enemy)
for projectile in projectiles:
pygame.draw.rect(screen, BLUE, projectile)
# Draw the score and lives
score_text = font.render(f"Score: {score}", True, BLACK)
lives_text = font.render(f"Lives: {lives}", True, BLACK)
screen.blit(score_text, (10, 10))
screen.blit(lives_text, (10, 50))
# Update the display
pygame.display.flip()
# -- Game Over Screen --
screen.fill(WHITE)
game_over_text = font.render("Game Over", True, BLACK)
final_score_text = font.render(f"Final Score: {score}", True, BLACK)
screen.blit(game_over_text, (SCREEN_WIDTH // 2 - game_over_text.get_width() // 2,
SCREEN_HEIGHT // 2 - game_over_text.get_height()))
screen.blit(final_score_text, (SCREEN_WIDTH // 2 - final_score_text.get_width() // 2,
SCREEN_HEIGHT // 2))
pygame.display.flip()
pygame.time.wait(3000)
pygame.quit()
sys.exit()
8. Test Incrementally
Start with a basic version and add features one at a time.
Test each new feature thoroughly before moving on.
9. Additional Tips
Avoid Modifying Lists While Iterating Over Them:
When removing items from a list you're iterating over, iterate over a copy using list[:] or iterate in reverse.
Use Pygame Sprites:
Pygame's Sprite class can help you manage game objects more efficiently.
Optimize Performance:
Limit the number of projectiles and enemies to maintain performance.
Use sound effects and images to enhance the game experience.
By addressing these issues and following the recommendations, you should be able to get your game up and running. Remember to keep your code clean and well-organized, and don't hesitate to seek further help if you encounter specific problems.