Pagina 1 di 2

Creare giochi in Python con PyGame

Inviato: 13/04/2025, 12:51
da FrancyDotNet
:games_alien1: Mini guida: Iniziare a creare giochi con Python e Pygame :joystick:

Hai sempre sognato di creare un videogioco tutto tuo? Con Python e la libreria Pygame è possibile realizzare giochi (sia in 2D che in 3D) in modo semplice e divertente! In questa guida ti spiego passo passo come iniziare.

Python è uno dei linguaggi più facili da imparare, con una sintassi leggibile e diretta. È perfetto per chi è alle prime armi e vuole iniziare subito a scrivere codice funzionante.

Pygame è una libreria open source scritta in Python pensata apposta per chi vuole creare videogiochi in modo semplice e divertente. Ti permette di gestire tutto quello che serve in un gioco: creare una finestra grafica, disegnare forme o immagini sullo schermo, leggere i comandi da tastiera o mouse, riprodurre musica ed effetti sonori, e tanto altro ancora. È consigliata perché è leggera, ben documentata, e perfetta per imparare i concetti fondamentali della programmazione di giochi.

Ecco un esempio di base che crea una finestra di gioco:

Codice: Seleziona tutto

import pygame
import sys

# Inizializza Pygame
pygame.init()

# Imposta dimensioni della finestra
larghezza, altezza = 800, 600
schermo = pygame.display.set_mode((larghezza, altezza))
pygame.display.set_caption("Il mio primo gioco con Pygame")

# Colori RGB
bianco = (255, 255, 255)

# Ciclo principale del gioco
while True:
    for evento in pygame.event.get():
        if evento.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    schermo.fill(bianco)  # Colore di sfondo
    pygame.display.flip()  # Aggiorna lo schermo

Ma come funziona un gioco in Pygame? Riassumendo brevemente un gioco è composto da questi elementi principali:
  • Inizializzazione: imposta Pygame e la finestra
  • Loop del gioco: continua a girare finché il giocatore non esce
  • Gestione eventi: tasti, mouse, uscita, ecc.
  • Logica di gioco: spostamenti, punteggio, collisioni…
  • Disegno a schermo: sfondo, oggetti, testo, ecc.
  • Aggiornamento: rinfresca lo schermo ogni frame

Re: Creare giochi in Python con PyGame - Tris (Tic Tac Toe)

Inviato: 13/04/2025, 13:15
da FrancyDotNet
Tris (Tic Tac Toe)

Codice: Seleziona tutto

import pygame
import sys

# Inizializza Pygame
pygame.init()

# Dimensioni della finestra
LARGHEZZA = 300
ALTEZZA = 340
DIM_CELLA = 100

# Colori
COLORE_SFONDO = pygame.Color('lightyellow')
COLORE_LINEE = pygame.Color('firebrick')
COLORE_TESTO = pygame.Color('darkblue')
COLORE_VITTORIA = pygame.Color('gold')

# Schermo e font
finestra = pygame.display.set_mode((LARGHEZZA, ALTEZZA))
pygame.display.set_caption("Tris con X e O")
font_simboli = pygame.font.SysFont("Arial", 60)
font_punteggio = pygame.font.SysFont("Arial", 24)

# Griglia e stato del gioco
griglia = [[0 for _ in range(3)] for _ in range(3)]
giocatore = 1  # 1 = X, 2 = O
fine_partita = False
punteggi = {1: 0, 2: 0}

# Funzione per disegnare le linee della griglia
def disegna_griglia():
    for i in range(1, 3):
        pygame.draw.line(finestra, COLORE_LINEE, (0, i * DIM_CELLA + 40), (LARGHEZZA, i * DIM_CELLA + 40), 4)
        pygame.draw.line(finestra, COLORE_LINEE, (i * DIM_CELLA, 40), (i * DIM_CELLA, ALTEZZA), 4)

# Funzione per disegnare X e O
def disegna_simboli():
    for r in range(3):
        for c in range(3):
            if griglia[r][c] != 0:
                simbolo = "X" if griglia[r][c] == 1 else "O"
                testo = font_simboli.render(simbolo, True, COLORE_TESTO)
                x = c * DIM_CELLA + (DIM_CELLA - testo.get_width()) // 2
                y = r * DIM_CELLA + 40 + (DIM_CELLA - testo.get_height()) // 2
                finestra.blit(testo, (x, y))

# Mostra punteggi in alto
def mostra_punteggio():
    # Cancella la parte alta (dove c'è il punteggio)
    pygame.draw.rect(finestra, COLORE_SFONDO, (0, 0, LARGHEZZA, 40))

    # Scrive il punteggio
    testo1 = font_punteggio.render(f"G1: {punteggi[1]}", True, COLORE_TESTO)
    testo2 = font_punteggio.render(f"G2: {punteggi[2]}", True, COLORE_TESTO)
    finestra.blit(testo1, (10, 10))
    finestra.blit(testo2, (LARGHEZZA - testo2.get_width() - 10, 10))

    # Linea divisoria sotto il punteggio
    pygame.draw.line(finestra, COLORE_LINEE, (0, 40), (LARGHEZZA, 40), 2)


# Verifica se un giocatore ha fatto tris
def controlla_tris(gioc):
    for i in range(3):
        # Righe
        if griglia[i][0] == griglia[i][1] == griglia[i][2] == gioc:
            disegna_linea(i, 0, i, 2)
            punteggi[gioc] += 1
            return True
        # Colonne
        if griglia[0][i] == griglia[1][i] == griglia[2][i] == gioc:
            disegna_linea(0, i, 2, i)
            punteggi[gioc] += 1
            return True
    # Diagonale principale
    if griglia[0][0] == griglia[1][1] == griglia[2][2] == gioc:
        disegna_linea(0, 0, 2, 2)
        punteggi[gioc] += 1
        return True
    # Diagonale secondaria
    if griglia[0][2] == griglia[1][1] == griglia[2][0] == gioc:
        disegna_linea(0, 2, 2, 0)
        punteggi[gioc] += 1
        return True
    return False

# Verifica se la griglia è piena (pareggio)
def griglia_piena():
    return all(griglia[r][c] != 0 for r in range(3) for c in range(3))

# Linea rossa in caso di vittoria
def disegna_linea(r1, c1, r2, c2):
    x1 = c1 * DIM_CELLA + DIM_CELLA // 2
    y1 = r1 * DIM_CELLA + DIM_CELLA // 2 + 40
    x2 = c2 * DIM_CELLA + DIM_CELLA // 2
    y2 = r2 * DIM_CELLA + DIM_CELLA // 2 + 40
    pygame.draw.line(finestra, COLORE_VITTORIA, (x1, y1), (x2, y2), 4)

# Ricomincia una nuova partita
def ricomincia():
    global griglia, giocatore, fine_partita
    griglia = [[0 for _ in range(3)] for _ in range(3)]
    giocatore = 1
    fine_partita = False
    finestra.fill(COLORE_SFONDO)
    disegna_griglia()
    mostra_punteggio()

# Avvio iniziale
finestra.fill(COLORE_SFONDO)
disegna_griglia()
mostra_punteggio()

# Ciclo principale
while True:
    for evento in pygame.event.get():
        if evento.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        if evento.type == pygame.MOUSEBUTTONDOWN and not fine_partita:
            mouse_x, mouse_y = evento.pos
            if mouse_y > 40:
                r = (mouse_y - 40) // DIM_CELLA
                c = mouse_x // DIM_CELLA
                if griglia[r][c] == 0:
                    griglia[r][c] = giocatore
                    if controlla_tris(giocatore):
                        fine_partita = True
                        mostra_punteggio()
                    elif griglia_piena():
                        fine_partita = True
                        mostra_punteggio()
                    giocatore = 2 if giocatore == 1 else 1
                    disegna_simboli()

        if evento.type == pygame.KEYDOWN:
            if evento.key == pygame.K_r or evento.key == pygame.K_SPACE:
                ricomincia()
            if evento.key == pygame.K_q or evento.key == pygame.K_ESCAPE:
                pygame.quit()
                sys.exit()

    pygame.display.update()

Re: Creare giochi in Python con PyGame - Carta-Sasso-Forbice

Inviato: 13/04/2025, 20:27
da FrancyDotNet
Carta-Forbice-Sasso

Codice: Seleziona tutto

import pygame
import random
import sys

# Inizializza Pygame
pygame.init()
LARGHEZZA, ALTEZZA = 600, 400
schermo = pygame.display.set_mode((LARGHEZZA, ALTEZZA))
pygame.display.set_caption("Carta Forbice Sasso")

FONT = pygame.font.SysFont(None, 40)
BIANCO = (255, 255, 255)
NERO = (0, 0, 0)
GRIGIO = (200, 200, 200)
ROSSO = (255, 0, 0)
VERDE = (0, 200, 0)

SCELTE = ['Carta', 'Forbice', 'Sasso']

# Disegna un pulsante
def disegna_pulsante(testo, x, y):
    rett = pygame.Rect(x, y, 160, 60)
    pygame.draw.rect(schermo, GRIGIO, rett)
    testo_surf = FONT.render(testo, True, NERO)
    testo_rect = testo_surf.get_rect(center=rett.center)
    schermo.blit(testo_surf, testo_rect)
    return rett

# Determina il vincitore
def determina_risultato(giocatore, computer):
    if giocatore == computer:
        return "Pareggio!"
    elif (giocatore == "Carta" and computer == "Sasso") or \
         (giocatore == "Sasso" and computer == "Forbice") or \
         (giocatore == "Forbice" and computer == "Carta"):
        return "Hai vinto!"
    else:
        return "Hai perso!"

risultato = ""
scelta_giocatore = ""
scelta_computer = random.choice(SCELTE)

running = True
while running:
    schermo.fill(BIANCO)
    titolo = FONT.render("Scegli:", True, NERO)
    schermo.blit(titolo, (LARGHEZZA // 2 - titolo.get_width() // 2, 30))

    pulsanti = {
        'Carta': disegna_pulsante("Carta", 70, 100),
        'Forbice': disegna_pulsante("Forbice", 220, 100),
        'Sasso': disegna_pulsante("Sasso", 370, 100)
    }

    if risultato:
        messaggio = FONT.render(f"{risultato}", True, VERDE if "vinto" in risultato else ROSSO)
        schermo.blit(messaggio, (LARGHEZZA // 2 - messaggio.get_width() // 2, 200))
        scelte = FONT.render(f"Tu: {scelta_giocatore} | PC: {scelta_computer}", True, NERO)
        schermo.blit(scelte, (LARGHEZZA // 2 - scelte.get_width() // 2, 250))

    for evento in pygame.event.get():
        if evento.type == pygame.QUIT:
            running = False

        elif evento.type == pygame.MOUSEBUTTONDOWN and not risultato:
            pos = evento.pos
            for scelta, rett in pulsanti.items():
                if rett.collidepoint(pos):
                    scelta_giocatore = scelta
                    risultato = determina_risultato(scelta_giocatore, scelta_computer)
                    pygame.time.set_timer(pygame.USEREVENT, 2000)

        elif evento.type == pygame.USEREVENT:
            scelta_computer = random.choice(SCELTE)
            risultato = ""
            scelta_giocatore = ""
            pygame.time.set_timer(pygame.USEREVENT, 0)

    pygame.display.flip()

pygame.quit()
sys.exit()

Re: Creare giochi in Python con PyGame - Memory

Inviato: 13/04/2025, 20:48
da FrancyDotNet
Memory

Codice: Seleziona tutto

import pygame
import random
import time

# Inizializza Pygame
pygame.init()

# Costanti
LARGHEZZA = 600
ALTEZZA = 600
RIGHE = 4
COLONNE = 4
TILE_SIZE = LARGHEZZA // COLONNE
FONT = pygame.font.SysFont(None, 60)
FPS = 30

# Colori
BIANCO = (255, 255, 255)
NERO = (0, 0, 0)
GRIGIO = (200, 200, 200)
VERDE = (100, 255, 100)
ROSSO = (255, 100, 100)

# Crea la finestra
finestra = pygame.display.set_mode((LARGHEZZA, ALTEZZA))
pygame.display.set_caption("Memory")

# Funzione per creare la griglia con coppie di numeri
def crea_griglia():
    numeri = list(range(1, (RIGHE * COLONNE // 2) + 1)) * 2
    random.shuffle(numeri)
    griglia = []
    for r in range(RIGHE):
        riga = []
        for c in range(COLONNE):
            riga.append(numeri.pop())
        griglia.append(riga)
    return griglia

# Disegna i riquadri
def disegna_griglia(scoperte):
    for r in range(RIGHE):
        for c in range(COLONNE):
            x = c * TILE_SIZE
            y = r * TILE_SIZE
            if scoperte[r][c]:
                pygame.draw.rect(finestra, VERDE, (x, y, TILE_SIZE, TILE_SIZE))
                testo = FONT.render(str(griglia[r][c]), True, NERO)
                finestra.blit(testo, (x + TILE_SIZE//3, y + TILE_SIZE//4))
            else:
                pygame.draw.rect(finestra, GRIGIO, (x, y, TILE_SIZE, TILE_SIZE))
            pygame.draw.rect(finestra, NERO, (x, y, TILE_SIZE, TILE_SIZE), 2)

# Mostra schermata di fine gioco
def mostra_game_over():
    finestra.fill(BIANCO)
    testo1 = FONT.render("Hai vinto!", True, ROSSO)
    testo2 = FONT.render("Premi Q per uscire", True, NERO)
    testo3 = FONT.render("o", True, NERO)
    testo4 = FONT.render("R per ricominciare", True, NERO)
    finestra.blit(testo1, (LARGHEZZA//3, ALTEZZA//4))
    finestra.blit(testo2, (LARGHEZZA//5, ALTEZZA//2))
    finestra.blit(testo3, (LARGHEZZA//2, ALTEZZA//2 + 40))
    finestra.blit(testo4, (LARGHEZZA//5, ALTEZZA//2 + 80))
    pygame.display.update()

# Funzione principale del gioco
def gioca():
    global griglia
    griglia = crea_griglia()
    scoperte = [[False]*COLONNE for _ in range(RIGHE)]
    selezioni = []
    clock = pygame.time.Clock()
    vinto = False
    in_gioco = True

    while in_gioco:
        for evento in pygame.event.get():
            if evento.type == pygame.QUIT:
                return False
            if evento.type == pygame.MOUSEBUTTONDOWN and not vinto:
                x, y = pygame.mouse.get_pos()
                c = x // TILE_SIZE
                r = y // TILE_SIZE
                if not scoperte[r][c] and len(selezioni) < 2:
                    scoperte[r][c] = True
                    selezioni.append((r, c))

        if len(selezioni) == 2:
            r1, c1 = selezioni[0]
            r2, c2 = selezioni[1]
            if griglia[r1][c1] != griglia[r2][c2]:
                pygame.display.update()
                pygame.time.delay(1000)
                scoperte[r1][c1] = False
                scoperte[r2][c2] = False
            selezioni = []

        finestra.fill(BIANCO)
        disegna_griglia(scoperte)
        pygame.display.update()
        clock.tick(FPS)

        # Controllo vittoria
        if all(all(riga) for riga in scoperte):
            vinto = True
            mostra_game_over()

        # Schermata finale: attende R o Q
        while vinto:
            for evento in pygame.event.get():
                if evento.type == pygame.QUIT:
                    return False
                if evento.type == pygame.KEYDOWN:
                    if evento.key == pygame.K_q:
                        return False
                    if evento.key == pygame.K_r:
                        return True

# Loop principale
giocando = True
while giocando:
    giocando = gioca()

pygame.quit()

Re: Creare giochi in Python con PyGame - Pong

Inviato: 13/04/2025, 20:48
da FrancyDotNet
:ballbounces: Pong

Codice scritto in modo semplice e struttura lineare adatta a chi studia o vuole partire con pygame

:arrow: 1. Gameplay e meccaniche
  • Gioco Pong a 2 giocatori
  • Controlli:
    • Giocatore sinistra: W (su), S (giù)
    • Giocatore destra: frecce su e giù
  • La palla rimbalza su:
    • Pareti superiore/inferiore
    • Racchette
  • Quando esce dallo schermo:
  • Viene riposizionata al centro
  • Il punteggio viene aggiornato
:arrow: 2. Struttura logica
  • Tutto il gioco è scritto in un singolo file
  • Ciclo principale ben definito con:
    • Gestione eventi
    • Input da tastiera
    • Movimento e collisioni
    • Disegno grafico
  • Non c’è separazione in funzioni per input/logica/disegno (ma per la semplicità va bene così)
:arrow: 3. Grafica e aspetto
  • Risoluzione: 800 × 500 (16:10)
  • Colori: NERO per lo sfondo, BIANCO per palla, racchette e punteggio
  • Tutto il disegno avviene su un unico surface (finestra)
  • Font chiaro e leggibile (Arial)

Codice: Seleziona tutto

import pygame
import sys

# Inizia Pygame
pygame.init()

# Dimensioni della finestra (16:10)
LARGHEZZA = 800
ALTEZZA = 500

# Colori
NERO = (0, 0, 0)
BIANCO = (255, 255, 255)

# Crea la finestra di gioco
finestra = pygame.display.set_mode((LARGHEZZA, ALTEZZA))
pygame.display.set_caption("Classic Pong")

# Imposta il tempo (fotogrammi al secondo)
clock = pygame.time.Clock()
FPS = 60

# Font per il punteggio
font = pygame.font.SysFont("Arial", 40)

# Racchette
larghezza_racchetta = 10
altezza_racchetta = 100
velocita_racchetta = 6

giocatore_sinistra = pygame.Rect(20, ALTEZZA//2 - altezza_racchetta//2, larghezza_racchetta, altezza_racchetta)
giocatore_destra  = pygame.Rect(LARGHEZZA - 30, ALTEZZA//2 - altezza_racchetta//2, larghezza_racchetta, altezza_racchetta)

# Palla
dimensione_palla = 8
palla = pygame.Rect(LARGHEZZA//2 - dimensione_palla//2, ALTEZZA//2 - dimensione_palla//2, dimensione_palla*2, dimensione_palla*2)
velocita_palla_x = 4
velocita_palla_y = 4

# Punteggi
punteggio_sinistra = 0
punteggio_destra = 0

# Funzione per rimettere la palla al centro
def resetta_palla():
    global velocita_palla_x, velocita_palla_y
    palla.center = (LARGHEZZA//2, ALTEZZA//2)
    velocita_palla_x *= -1
    velocita_palla_y *= -1

# Ciclo principale del gioco
while True:
    # Chiudi il gioco se premi la X
    for evento in pygame.event.get():
        if evento.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # Controlli tastiera
    tasti = pygame.key.get_pressed()

    # Giocatore sinistra: W e S
    if tasti[pygame.K_w] and giocatore_sinistra.top > 0:
        giocatore_sinistra.y -= velocita_racchetta
    if tasti[pygame.K_s] and giocatore_sinistra.bottom < ALTEZZA:
        giocatore_sinistra.y += velocita_racchetta

    # Giocatore destra: FRECCIA SU e GIÙ
    if tasti[pygame.K_UP] and giocatore_destra.top > 0:
        giocatore_destra.y -= velocita_racchetta
    if tasti[pygame.K_DOWN] and giocatore_destra.bottom < ALTEZZA:
        giocatore_destra.y += velocita_racchetta

    # Muovi la palla
    palla.x += velocita_palla_x
    palla.y += velocita_palla_y

    # Rimbalzo sulle pareti sopra/sotto
    if palla.top <= 0 or palla.bottom >= ALTEZZA:
        velocita_palla_y *= -1

    # Rimbalzo preciso sulle racchette
    if palla.colliderect(giocatore_sinistra):
        palla.left = giocatore_sinistra.right
        velocita_palla_x *= -1

    if palla.colliderect(giocatore_destra):
        palla.right = giocatore_destra.left
        velocita_palla_x *= -1

    # Se la palla esce a sinistra o destra, aggiorna il punteggio
    if palla.left <= 0:
        punteggio_destra += 1
        resetta_palla()
    if palla.right >= LARGHEZZA:
        punteggio_sinistra += 1
        resetta_palla()

    # Disegna tutto sullo schermo
    finestra.fill(NERO)
    pygame.draw.rect(finestra, BIANCO, giocatore_sinistra)
    pygame.draw.rect(finestra, BIANCO, giocatore_destra)
    pygame.draw.ellipse(finestra, BIANCO, palla)

    # Disegna il punteggio
    testo_punteggio = font.render(f"{punteggio_sinistra}   {punteggio_destra}", True, BIANCO)
    finestra.blit(testo_punteggio, (LARGHEZZA//2 - testo_punteggio.get_width()//2, 20))

    # Aggiorna lo schermo
    pygame.display.flip()
    clock.tick(FPS)

:ugeek: Versione retro in stile anni'80

Semplicità = Lineare, chiaro, con variabili leggibili
Comprensibilità = È facile seguire il flusso, anche per chi conosce poco Pygame
Separazione logica = Buona base, ma le parti di gioco (input, logica, disegno) sono tutte in un blocco
Stile retro/visivo = Ottima personalizzazione: colori, effetti, estetica arcade
Commenti = Minimi. Qualche commento in più aiuterebbe per la didattic

Codice: Seleziona tutto

import pygame 
import sys

# Inizializza Pygame
pygame.init()

# Costanti della finestra
LARGHEZZA = 800
ALTEZZA = 500
FPS = 60

# Crea la finestra
finestra = pygame.display.set_mode((LARGHEZZA, ALTEZZA))
pygame.display.set_caption("Classic Pong")

# Colori stile retro
NERO = (0, 0, 0)
BIANCO = (255, 255, 255)
CAMPO_VERDE = (0, 128, 0)
GIALLO_NEON = (255, 255, 0)
AZZURRO_NEON = (0, 255, 255)
ROSSO_NEON = (255, 0, 0)
SPESSORE_BORDO = 10

# Font pixel-style
try:
    font = pygame.font.Font("PressStart2P-Regular.ttf", 18)  # Se hai un font arcade
except:
    font = pygame.font.SysFont("Courier New", 28, bold=True)

# Clock
clock = pygame.time.Clock()

# Racchette
larghezza_racchetta = 10
altezza_racchetta = 100
velocita_racchetta = 5

giocatore_sx = pygame.Rect(20, ALTEZZA // 2 - altezza_racchetta // 2, larghezza_racchetta, altezza_racchetta)
giocatore_dx = pygame.Rect(LARGHEZZA - 30, ALTEZZA // 2 - altezza_racchetta // 2, larghezza_racchetta, altezza_racchetta)

# Palla
DIM_PALLA = 8
palla = pygame.Rect(LARGHEZZA // 2 - DIM_PALLA // 2, ALTEZZA // 2 - DIM_PALLA // 2, DIM_PALLA * 2, DIM_PALLA * 2)
vel_x = 4
vel_y = 4
velocita_y_massima = 5

# Punteggi
punti_sx = 0
punti_dx = 0

# Effetto CRT scanlines
scanline_surface = pygame.Surface((LARGHEZZA, ALTEZZA), pygame.SRCALPHA)
for y in range(0, ALTEZZA, 4):
    pygame.draw.line(scanline_surface, (0, 0, 0, 40), (0, y), (LARGHEZZA, y))

# Reset palla
def resetta_palla():
    global vel_x, vel_y
    palla.center = (LARGHEZZA // 2, ALTEZZA // 2)
    vel_x *= -1
    vel_y = 4

# Linea centrale tratteggiata
def disegna_centro_tratteggiato():
    for y in range(0, ALTEZZA, 20):
        pygame.draw.rect(finestra, BIANCO, (LARGHEZZA // 2 - 1, y, 2, 10))

# Loop principale
while True:
    for evento in pygame.event.get():
        if evento.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # Controlli
    tasti = pygame.key.get_pressed()
    if tasti[pygame.K_w] and giocatore_sx.top > 0:
        giocatore_sx.y -= velocita_racchetta
    if tasti[pygame.K_s] and giocatore_sx.bottom < ALTEZZA:
        giocatore_sx.y += velocita_racchetta
    if tasti[pygame.K_UP] and giocatore_dx.top > 0:
        giocatore_dx.y -= velocita_racchetta
    if tasti[pygame.K_DOWN] and giocatore_dx.bottom < ALTEZZA:
        giocatore_dx.y += velocita_racchetta

    # Muovi la palla
    palla.x += vel_x
    palla.y += vel_y

    # Collisioni con pareti
    if palla.top <= 0 or palla.bottom >= ALTEZZA:
        vel_y *= -1

    # Collisioni con racchetta sinistra (con effetto angolo)
    if palla.colliderect(giocatore_sx):
        palla.left = giocatore_sx.right
        vel_x *= -1
        differenza = palla.centery - giocatore_sx.centery
        vel_y = (differenza / (altezza_racchetta / 2)) * velocita_y_massima

    # Collisioni con racchetta destra (con effetto angolo)
    if palla.colliderect(giocatore_dx):
        palla.right = giocatore_dx.left
        vel_x *= -1
        differenza = palla.centery - giocatore_dx.centery
        vel_y = (differenza / (altezza_racchetta / 2)) * velocita_y_massima

    # Punti
    if palla.left <= 0:
        punti_dx += 1
        resetta_palla()
    if palla.right >= LARGHEZZA:
        punti_sx += 1
        resetta_palla()

    # Sfondo con effetto scia
    finestra.fill(CAMPO_VERDE)

    # Cornice campo (solo sopra e sotto)
    pygame.draw.rect(finestra, ROSSO_NEON, (0, 0, LARGHEZZA, SPESSORE_BORDO))
    pygame.draw.rect(finestra, ROSSO_NEON, (0, ALTEZZA - SPESSORE_BORDO, LARGHEZZA, SPESSORE_BORDO))

    # Linea tratteggiata centrale
    disegna_centro_tratteggiato()

    # Racchette colorate
    pygame.draw.rect(finestra, GIALLO_NEON, giocatore_sx)
    pygame.draw.rect(finestra, AZZURRO_NEON, giocatore_dx)

    # Palla
    pygame.draw.rect(finestra, BIANCO, palla)

    # Punteggio
    testo = font.render(f"{punti_sx}   {punti_dx}", True, BIANCO)
    finestra.blit(testo, (LARGHEZZA // 2 - testo.get_width() // 2, 20))

    # Overlay CRT scanlines
    finestra.blit(scanline_surface, (0, 0))

    # Mostra il frame
    pygame.display.flip()
    clock.tick(FPS)

Re: Creare giochi in Python con PyGame - Breakout

Inviato: 13/04/2025, 20:48
da FrancyDotNet
:arrow: Breakout

Codice: Seleziona tutto

import pygame
from pygame.locals import *

# Inizializza Pygame
pygame.init()

# Definisci le costanti
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
BALL_SPEED = [5, 5]
PADDLE_SPEED = 10
WHITE = (255, 255, 255)

# Crea la finestra del gioco
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Breakout Game')

# Carica le immagini
#background = pygame.image.load('images/background_1.jpg')
ball = pygame.image.load('images/mini_ball.png')
paddle = pygame.image.load('images/paddle.png')

# Posiziona la racchetta al centro
paddle_rect = paddle.get_rect()
paddle_rect.midbottom = (SCREEN_WIDTH // 2, SCREEN_HEIGHT - 20)

# Posiziona la palla sopra la racchetta
ball_rect = ball.get_rect()
ball_rect.midbottom = paddle_rect.midtop

# Avvia il loop del gioco
running = True
clock = pygame.time.Clock()

while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False

    keys = pygame.key.get_pressed()
    if keys[K_LEFT]:
        paddle_rect.x -= PADDLE_SPEED
    if keys[K_RIGHT]:
        paddle_rect.x += PADDLE_SPEED

    # Muovi la palla
    ball_rect.move_ip(BALL_SPEED)

    # Gestisci le collisioni
    if ball_rect.left <= 0 or ball_rect.right >= SCREEN_WIDTH:
        BALL_SPEED[0] = -BALL_SPEED[0]
    if ball_rect.top <= 0:
        BALL_SPEED[1] = -BALL_SPEED[1]

    if ball_rect.colliderect(paddle_rect):
        BALL_SPEED[1] = -BALL_SPEED[1]

    # Disegna tutto
    #screen.blit(background, (0, 0))
    screen.blit(ball, ball_rect)
    screen.blit(paddle, paddle_rect)

    pygame.display.update()

    # Imposta il limite di frame per regolare la velocità del gioco
    clock.tick(60)

# Chiudi Pygame
pygame.quit()

Re: Creare giochi in Python con PyGame - Firebird

Inviato: 13/04/2025, 20:49
da FrancyDotNet
:arrow: Firebird clone di Space Invaders

Codice: Seleziona tutto

import pygame
import random

pygame.init()

screen_width = 800
screen_height = 600

screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Firebird - A space odyssey")

background_image = pygame.image.load("images/background_space.png")

font = pygame.font.Font(None, 28)

ship_width = 60
ship_height = 100
ship_x = (screen_width - ship_width) / 2
ship_y = screen_height - ship_height - 20
ship_speed = 5
ship_image = pygame.transform.scale(pygame.image.load('images/spaceship.png'), (ship_width, ship_height))

block_min_size = 8
block_max_size = 32
block_speed = 2
block_list = []
block_spawn_delay = 1000
last_block_spawn_time = pygame.time.get_ticks()

clock = pygame.time.Clock()
FPS = 60

score = 0
game_over = False

while not game_over:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and ship_x > 0:
        ship_x -= ship_speed
    elif keys[pygame.K_RIGHT] and ship_x < screen_width - ship_width:
        ship_x += ship_speed
    if keys[pygame.K_UP] and ship_y > 0:
        ship_y -= ship_speed
    elif keys[pygame.K_DOWN] and ship_y < screen_height - ship_height:
        ship_y += ship_speed

    if pygame.time.get_ticks() - last_block_spawn_time > block_spawn_delay:
        block_size = random.randint(block_min_size, block_max_size)
        block_list.append({
            'x': random.randint(0, screen_width - block_size),
            'y': random.randint(-screen_height, 0),
            'size': block_size
        })
        last_block_spawn_time = pygame.time.get_ticks()

    for block in block_list:
        block['y'] += block_speed
        if block['y'] > screen_height:
            block_list.remove(block)

    for block in block_list:
        if ship_x < block['x'] + block['size'] and \
           ship_x + ship_width > block['x'] and \
           ship_y < block['y'] + block['size'] and \
           ship_y + ship_height > block['y']:
            game_over = True

    screen.blit(background_image, (0, 0))
    screen.blit(ship_image, (ship_x, ship_y))
    for block in block_list:
        block_image = pygame.transform.scale(pygame.image.load('images/block.png'), (block['size'], block['size']))
        screen.blit(block_image, (block['x'], block['y']))
    score_text = font.render('Score: ' + str(score), True, (255, 255, 255))
    screen.blit(score_text, (10, 10))
    pygame.display.update()

    clock.tick(FPS)

pygame.quit()

Re: Creare giochi in Python con PyGame - Snake

Inviato: 13/04/2025, 20:50
da FrancyDotNet
:alien_13: Snake

Codice: Seleziona tutto

import pygame
import sys
import random

# Inizializza Pygame
pygame.init()

# Costanti
LARGHEZZA = 400
ALTEZZA = 400
BLOCCO = 20
FPS = 60
STEP_MOVIMENTO = 10  # Ogni quanti frame muovere lo Snake

# Colori
NERO = (0, 0, 0)
VERDE = (0, 255, 0)
ROSSO = (255, 0, 0)
BIANCO = (255, 255, 255)

# Setup finestra e clock
finestra = pygame.display.set_mode((LARGHEZZA, ALTEZZA))
pygame.display.set_caption("Snake Classico 60 FPS")
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 30)

# Posizione iniziale Snake
x = LARGHEZZA // 2
y = ALTEZZA // 2
dx = 0
dy = 0
direzione = None
corpo = [[x, y]]
lunghezza = 1

# Cibo
cibo_x = random.randint(0, (LARGHEZZA - BLOCCO) // BLOCCO) * BLOCCO
cibo_y = random.randint(0, (ALTEZZA - BLOCCO) // BLOCCO) * BLOCCO

game_over = False
frame = 0

# Game loop
while True:
    # Gestione eventi
    for evento in pygame.event.get():
        if evento.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if evento.type == pygame.KEYDOWN:
            if evento.key == pygame.K_LEFT and direzione != "destra":
                dx = -BLOCCO
                dy = 0
                direzione = "sinistra"
            elif evento.key == pygame.K_RIGHT and direzione != "sinistra":
                dx = BLOCCO
                dy = 0
                direzione = "destra"
            elif evento.key == pygame.K_UP and direzione != "giu":
                dx = 0
                dy = -BLOCCO
                direzione = "su"
            elif evento.key == pygame.K_DOWN and direzione != "su":
                dx = 0
                dy = BLOCCO
                direzione = "giu"
            elif game_over:
                if evento.key == pygame.K_q:
                    pygame.quit()
                    sys.exit()
                elif evento.key == pygame.K_r:
                    # Reset gioco
                    x = LARGHEZZA // 2
                    y = ALTEZZA // 2
                    dx = 0
                    dy = 0
                    direzione = None
                    corpo = [[x, y]]
                    lunghezza = 1
                    cibo_x = random.randint(0, (LARGHEZZA - BLOCCO) // BLOCCO) * BLOCCO
                    cibo_y = random.randint(0, (ALTEZZA - BLOCCO) // BLOCCO) * BLOCCO
                    game_over = False
                    frame = 0

    # Movimento a intervalli
    if not game_over:
        frame += 1
        if frame >= STEP_MOVIMENTO:
            frame = 0
            x += dx
            y += dy
            testa = [x, y]
            corpo.append(testa)
            if len(corpo) > lunghezza:
                corpo.pop(0)

            # Controllo collisioni
            if x < 0 or x >= LARGHEZZA or y < 0 or y >= ALTEZZA:
                game_over = True
            if testa in corpo[:-1]:
                game_over = True
            if x == cibo_x and y == cibo_y:
                lunghezza += 1
                cibo_x = random.randint(0, (LARGHEZZA - BLOCCO) // BLOCCO) * BLOCCO
                cibo_y = random.randint(0, (ALTEZZA - BLOCCO) // BLOCCO) * BLOCCO

    # Disegno
    finestra.fill(NERO)
    pygame.draw.rect(finestra, ROSSO, (cibo_x, cibo_y, BLOCCO, BLOCCO))
    for parte in corpo:
        pygame.draw.rect(finestra, VERDE, (*parte, BLOCCO, BLOCCO))

    testo = font.render(f"Punteggio: {lunghezza - 1}", True, BIANCO)
    finestra.blit(testo, (10, 10))

    if game_over:
        msg1 = font.render("Game Over", True, ROSSO)
        msg2 = font.render("Premi Q per uscire o", True, BIANCO)
        msg3 = font.render("R per ricominciare", True, BIANCO)
        finestra.blit(msg1, (130, 150))
        finestra.blit(msg2, (90, 200))
        finestra.blit(msg3, (100, 230))

    pygame.display.flip()
    clock.tick(FPS)

Re: Creare giochi in Python con PyGame - Dino Runner

Inviato: 13/04/2025, 20:50
da FrancyDotNet
:ugeek: Dino Runner

Codice: Seleziona tutto

import pygame
import random
import sys

# Inizializza pygame
pygame.init()

# Costanti aggiornate
LARGHEZZA = 800
ALTEZZA = 450
FPS = 60
SFONDO_ALTO = (180, 220, 255)
SFONDO_BASSO = (255, 255, 255)
MARRONE = (150, 75, 0)
VERDE = (0, 200, 0)
ROSSO = (200, 0, 0)
NERO = (0, 0, 0)

ALTEZZA_TERRENO = 60  # altezza terreno
ALTEZZA_DINO = 50     # nuova altezza dino per proporzione

# Finestra
finestra = pygame.display.set_mode((LARGHEZZA, ALTEZZA))
pygame.display.set_caption("Dino Runner")

# Clock
clock = pygame.time.Clock()

# Dino
dino = pygame.Rect(50, ALTEZZA - ALTEZZA_TERRENO - ALTEZZA_DINO, 40, ALTEZZA_DINO)
gravità = 0
salti_disponibili = 2

# Ostacoli
ostacoli = []
ostacolo_timer = 0
intervallo_prossimo_ostacolo = random.randint(60, 150)

# Font
font = pygame.font.SysFont(None, 36)

# Punteggio
punteggio = 0
game_over = False

# Funzione background sfumato
def disegna_sfondo():
    for y in range(ALTEZZA):
        ratio = y / ALTEZZA
        r = int(SFONDO_ALTO[0] * (1 - ratio) + SFONDO_BASSO[0] * ratio)
        g = int(SFONDO_ALTO[1] * (1 - ratio) + SFONDO_BASSO[1] * ratio)
        b = int(SFONDO_ALTO[2] * (1 - ratio) + SFONDO_BASSO[2] * ratio)
        pygame.draw.line(finestra, (r, g, b), (0, y), (LARGHEZZA, y))

# Loop principale
while True:
    clock.tick(FPS)
    disegna_sfondo()

    # Eventi
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if not game_over and event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE and salti_disponibili > 0:
                gravità = -12
                salti_disponibili -= 1
        if game_over and event.type == pygame.KEYDOWN:
            if event.key == pygame.K_r:
                # Reset
                dino.y = ALTEZZA - ALTEZZA_TERRENO - ALTEZZA_DINO
                gravità = 0
                salti_disponibili = 2
                ostacoli.clear()
                punteggio = 0
                game_over = False
                ostacolo_timer = 0
                intervallo_prossimo_ostacolo = random.randint(60, 150)

    if not game_over:
        # Gravità e movimento Dino
        gravità += 0.6
        dino.y += gravità
        if dino.y >= ALTEZZA - ALTEZZA_TERRENO - ALTEZZA_DINO:
            dino.y = ALTEZZA - ALTEZZA_TERRENO - ALTEZZA_DINO
            gravità = 0
            salti_disponibili = 2

        # Timer ostacoli
        ostacolo_timer += 1
        if ostacolo_timer >= intervallo_prossimo_ostacolo:
            ostacolo_timer = 0
            intervallo_prossimo_ostacolo = random.randint(60, 150)
            larghezza = random.randint(20, 30)
            altezza = random.randint(40, 80)
            nuovo = pygame.Rect(
                LARGHEZZA,
                ALTEZZA - ALTEZZA_TERRENO - altezza,
                larghezza,
                altezza
            )
            ostacoli.append(nuovo)

        # Movimento ostacoli
        for ostacolo in ostacoli:
            ostacolo.x -= 5
            pygame.draw.rect(finestra, ROSSO, ostacolo)

        # Rimuovi ostacoli fuori schermo
        ostacoli = [o for o in ostacoli if o.x + o.width > 0]

        # Collisioni
        for ostacolo in ostacoli:
            if dino.colliderect(ostacolo):
                game_over = True

        # Punteggio
        punteggio += 1
        testo = font.render(f"Punteggio: {punteggio // 10}", True, NERO)
        finestra.blit(testo, (10, 10))

    else:
        messaggio = font.render("Game Over! Premi R per riprovare", True, NERO)
        finestra.blit(messaggio, (LARGHEZZA // 2 - 180, ALTEZZA // 2 - 20))

    # Terreno
    pygame.draw.rect(finestra, MARRONE, (0, ALTEZZA - ALTEZZA_TERRENO, LARGHEZZA, ALTEZZA_TERRENO))

    # Dino
    pygame.draw.rect(finestra, VERDE, dino)

    # Aggiorna display
    pygame.display.flip()

Re: Creare giochi in Python con PyGame - Pack-Gnam

Inviato: 13/04/2025, 21:36
da FrancyDotNet
Titolo del Gioco: Pack-Gnam

Clone minimalista di Pac-man.

Codice: Seleziona tutto

import pygame 
import sys
import random

# Costanti
DIM_CELLA = 32
GRIGLIA_ORIGINALE = [
    "000000000000000",
    "011111111111110",
    "010010000010010",
    "010010000010010",
    "011111111111110",
    "010000010000010",
    "010000010000010",
    "011111111111110",
    "010010000010010",
    "010010000010010",
    "011111111111110",
    "000000000000000"
]

LARGHEZZA = len(GRIGLIA_ORIGINALE[0]) * DIM_CELLA
ALTEZZA = len(GRIGLIA_ORIGINALE) * DIM_CELLA
FPS = 60
PACMAN_VELOCITA = 4
FANTASMA_VELOCITA = 2
DURATA_TIMER = 60

NERO = pygame.Color("black")
GRIGIO = pygame.Color("lightgrey")
GIALLO = pygame.Color("gold")
BIANCO = pygame.Color("ghostwhite")
ROSSO = pygame.Color("red")
VERDE = pygame.Color("limegreen")
BLU = pygame.Color("royalblue")

pygame.init()
schermo = pygame.display.set_mode((LARGHEZZA, ALTEZZA))
pygame.display.set_caption("Pack-Gnam")
clock = pygame.time.Clock()

direzione = (0, 0)
prossima_direzione = (0, 0)
GRIGLIA = []
pos_x = 0
pos_y = 0
punta_punteggio = 0
game_over = False
motivo_gameover = ""
tempo_rimanente = DURATA_TIMER
start_ticks = 0

fantasmi = []

def reset_livello():
    global GRIGLIA, pos_x, pos_y, direzione, prossima_direzione, punta_punteggio, game_over, motivo_gameover
    global tempo_rimanente, start_ticks, fantasmi

    GRIGLIA = [riga[:] for riga in GRIGLIA_ORIGINALE]
    pos_x = 1 * DIM_CELLA
    pos_y = 1 * DIM_CELLA
    direzione = (0, 0)
    prossima_direzione = (0, 0)
    punta_punteggio = 0
    game_over = False
    motivo_gameover = ""
    tempo_rimanente = DURATA_TIMER
    start_ticks = pygame.time.get_ticks()

    fantasmi = [
        {"x": 6 * DIM_CELLA, "y": 4 * DIM_CELLA, "dir": random.choice([(1,0), (-1,0), (0,1), (0,-1)]), "colore": VERDE},
        {"x": 9 * DIM_CELLA, "y": 7 * DIM_CELLA, "dir": random.choice([(1,0), (-1,0), (0,1), (0,-1)]), "colore": BLU}
    ]

def disegna_mappa():
    for y, riga in enumerate(GRIGLIA):
        for x, cella in enumerate(riga):
            px = x * DIM_CELLA
            py = y * DIM_CELLA
            if cella == '0':
                pygame.draw.rect(schermo, GRIGIO, (px, py, DIM_CELLA, DIM_CELLA))
            else:
                pygame.draw.rect(schermo, NERO, (px, py, DIM_CELLA, DIM_CELLA))
                if cella == '1':
                    pygame.draw.circle(schermo, BIANCO, (px + DIM_CELLA//2, py + DIM_CELLA//2), 4)

def is_muro(px, py):
    grid_x = px // DIM_CELLA
    grid_y = py // DIM_CELLA
    if 0 <= grid_y < len(GRIGLIA) and 0 <= grid_x < len(GRIGLIA[0]):
        return GRIGLIA[grid_y][grid_x] == '0'
    return True

def puo_muoversi(dx, dy):
    nuovo_x = pos_x + dx * PACMAN_VELOCITA
    nuovo_y = pos_y + dy * PACMAN_VELOCITA
    punti_controllo = [
        (nuovo_x, nuovo_y),
        (nuovo_x + DIM_CELLA - 1, nuovo_y),
        (nuovo_x, nuovo_y + DIM_CELLA - 1),
        (nuovo_x + DIM_CELLA - 1, nuovo_y + DIM_CELLA - 1)
    ]
    return all(not is_muro(x, y) for x, y in punti_controllo)

def aggiorna_pacman():
    global pos_x, pos_y, direzione, punta_punteggio

    if pos_x % DIM_CELLA == 0 and pos_y % DIM_CELLA == 0:
        if puo_muoversi(*prossima_direzione):
            direzione = prossima_direzione

    nuovo_x = pos_x + direzione[0] * PACMAN_VELOCITA
    nuovo_y = pos_y + direzione[1] * PACMAN_VELOCITA

    punti_controllo = [
        (nuovo_x, nuovo_y),
        (nuovo_x + DIM_CELLA - 1, nuovo_y),
        (nuovo_x, nuovo_y + DIM_CELLA - 1),
        (nuovo_x + DIM_CELLA - 1, nuovo_y + DIM_CELLA - 1)
    ]

    if all(not is_muro(x, y) for x, y in punti_controllo):
        pos_x = nuovo_x
        pos_y = nuovo_y

        if pos_x % DIM_CELLA == 0 and pos_y % DIM_CELLA == 0:
            cx = pos_x // DIM_CELLA
            cy = pos_y // DIM_CELLA
            if GRIGLIA[cy][cx] == '1':
                GRIGLIA[cy] = GRIGLIA[cy][:cx] + '2' + GRIGLIA[cy][cx+1:]
                punta_punteggio += 1

def aggiorna_fantasmi():
    for fantasma in fantasmi:
        dx, dy = fantasma["dir"]
        nuovo_x = fantasma["x"] + dx * FANTASMA_VELOCITA
        nuovo_y = fantasma["y"] + dy * FANTASMA_VELOCITA

        punti_controllo = [
            (nuovo_x, nuovo_y),
            (nuovo_x + DIM_CELLA - 1, nuovo_y),
            (nuovo_x, nuovo_y + DIM_CELLA - 1),
            (nuovo_x + DIM_CELLA - 1, nuovo_y + DIM_CELLA - 1)
        ]

        if all(not is_muro(x, y) for x, y in punti_controllo):
            fantasma["x"] = nuovo_x
            fantasma["y"] = nuovo_y
        else:
            fantasma["dir"] = random.choice([(1,0), (-1,0), (0,1), (0,-1)])

def controlla_collisione_con_fantasmi():
    pacman_rect = pygame.Rect(pos_x, pos_y, DIM_CELLA, DIM_CELLA)
    for fantasma in fantasmi:
        fantasma_rect = pygame.Rect(fantasma["x"], fantasma["y"], DIM_CELLA, DIM_CELLA)
        if pacman_rect.colliderect(fantasma_rect):
            return True
    return False

def disegna_pacman():
    pygame.draw.circle(schermo, GIALLO, (pos_x + DIM_CELLA//2, pos_y + DIM_CELLA//2), DIM_CELLA // 2 - 2)

def disegna_fantasmi():
    for fantasma in fantasmi:
        pygame.draw.circle(schermo, fantasma["colore"], (fantasma["x"] + DIM_CELLA//2, fantasma["y"] + DIM_CELLA//2), DIM_CELLA // 2 - 2)

def mostra_punteggio():
    font = pygame.font.SysFont(None, 24)
    testo = font.render(f"Punteggio: {punta_punteggio}", True, NERO)
    schermo.blit(testo, (10, 10))

def mostra_timer():
    font = pygame.font.SysFont(None, 24)
    testo = font.render(f"Tempo: {tempo_rimanente}s", True, NERO)
    schermo.blit(testo, (LARGHEZZA - 130, 10))

def controllo_game_over():
    for riga in GRIGLIA:
        if '1' in riga:
            return False
    return True

def mostra_game_over():
    font = pygame.font.SysFont(None, 48)
    if motivo_gameover == "vittoria":
        testo = font.render("Hai vinto!", True, ROSSO)
    else:
        testo = font.render("Game Over!", True, ROSSO)
    rect = testo.get_rect(center=(LARGHEZZA // 2, ALTEZZA // 2))
    schermo.blit(testo, rect)

reset_livello()
esegui = True

while esegui:
    for evento in pygame.event.get():
        if evento.type == pygame.QUIT:
            esegui = False
        elif evento.type == pygame.KEYDOWN:
            if evento.key == pygame.K_r:
                reset_livello()
            elif not game_over:
                if evento.key == pygame.K_UP:
                    prossima_direzione = (0, -1)
                elif evento.key == pygame.K_DOWN:
                    prossima_direzione = (0, 1)
                elif evento.key == pygame.K_LEFT:
                    prossima_direzione = (-1, 0)
                elif evento.key == pygame.K_RIGHT:
                    prossima_direzione = (1, 0)

    if not game_over:
        aggiorna_pacman()
        aggiorna_fantasmi()

        if controlla_collisione_con_fantasmi():
            game_over = True
            motivo_gameover = "sconfitta"

        if controllo_game_over():
            game_over = True
            motivo_gameover = "vittoria"

        secondi_passati = (pygame.time.get_ticks() - start_ticks) // 1000
        tempo_rimanente = max(0, DURATA_TIMER - secondi_passati)
        if tempo_rimanente == 0 and not game_over:
            game_over = True
            motivo_gameover = "sconfitta"

    schermo.fill(NERO)
    disegna_mappa()
    disegna_pacman()
    disegna_fantasmi()
    mostra_punteggio()
    mostra_timer()
    if game_over:
        mostra_game_over()
    pygame.display.flip()
    clock.tick(FPS)

pygame.quit()
sys.exit()