Appunti di Programmazione

Creative Commons License

Memory: Un gioco di memoria con Tkinter 3

Il programma seguente è la riproduzione di un classico gioco di memoria usando un mazzo di carte, il quale è composto da un certo numero di coppie di foto di oggetti.

Le carte vengono mescolate e poi disposte in modo ordinato con il dorso rivolto verso l'alto. Il giocatore deve scoprire due carte alla volta e se queste sono uguali restano visibili altrimenti vengono rimesse al loro posto e coperte come erano in origine. Il gioco termina quando sono state rivelate tutte le coppie del mazzo.

Il gioco può essere usato secondo quanto dichiarato dalle disposizioni delle CREATIVE COMMONS il cui link è riportato all'inizio della pagina.

Memory

import random, pygame, sys
from pygame.locals import *

pygame.init()
pygame.mixer.init()

FPS=30
LARGHEZZA=800
ALTEZZA=600
VELOCITA_SCOPRI_CARTA=5
DIMENSIONE_TESSERA=50
DISTANZA_TESSERE=10
CORNICE=(60, 60, 60)
CORNICE_EVIDENZIA=(255, 0, 0)
SFONDO=pygame.image.load("Memory/Sfondo.jpg")
RETRO=pygame.image.load("Memory/Retro_Tessera.png")
ALBERO=pygame.image.load("Memory/Albero.png")
ARANCIA=pygame.image.load("Memory/Arancia.png")
AUTOMOBILINA=pygame.image.load("Memory/Automobilina.png")
BABBO_NATALE=pygame.image.load("Memory/Babbo_Natale.png")
BAMBOLA=pygame.image.load("Memory/Bambola.png")
BARATTOLO=pygame.image.load("Memory/Barattolo.png")
BIGLIA=pygame.image.load("Memory/Biglia.png")
CANOTTO=pygame.image.load("Memory/Canotto.png")
CARRIOLA=pygame.image.load("Memory/Carriola.png")
CASCO=pygame.image.load("Memory/Casco.png")
CHITARRA=pygame.image.load("Memory/Chitarra.png")
CUCU=pygame.image.load("Memory/Cucù.png")
DADI=pygame.image.load("Memory/Dadi.png")
FORMULA_1=pygame.image.load("Memory/Formula_1.png")
GALLO=pygame.image.load("Memory/Gallo.png")
GIOSTRA=pygame.image.load("Memory/Giostra.png")
LAMPADA=pygame.image.load("Memory/Lampada.png")
MANNAIA=pygame.image.load("Memory/Mannaia.png")
MELA=pygame.image.load("Memory/Mela.png")
OCCHIALI=pygame.image.load("Memory/Occhiali.png")
OMBRELLONE=pygame.image.load("Memory/Ombrellone.png")
OPALE=pygame.image.load("Memory/Opale.png")
OROLOGIO=pygame.image.load("Memory/Orologio.png")
ORSACCHIOTTO=pygame.image.load("Memory/Orsacchiotto.png")
PALLA=pygame.image.load("Memory/Palla.png")
PENDOLA=pygame.image.load("Memory/Pendola.png")
PENNA=pygame.image.load("Memory/Penna.png")
PESCE=pygame.image.load("Memory/Pesce.png")
PICCOZZA=pygame.image.load("Memory/Piccozza.png")
ROSA=pygame.image.load("Memory/Rosa.png")
RUSPA=pygame.image.load("Memory/Ruspa.png")
SOLDATINO=pygame.image.load("Memory/Soldatino.png")
STIVALI=pygame.image.load("Memory/Stivali.png")
TELEFONO=pygame.image.load("Memory/Telefono.png")
UVA=pygame.image.load("Memory/Uva.png")

DIVERSI = pygame.mixer.Sound("Memory/Nuovo.wav")
CLICK = pygame.mixer.Sound("Memory/Click.wav")
COPPIA = pygame.mixer.Sound("Memory/Errore.wav")

CARTE=("ALBERO",   "ARANCIA",  "AUTOMOBILINA", "BABBO_NATALE", "BAMBOLA", "BARATTOLO","BIGLIA",    \
       "CANOTTO",  "CARRIOLA", "CASCO",        "CHITARRA",     "CUCU",    "DADI",     "FORMULA_1", \
       "GALLO",    "GIOSTRA",  "LAMPADA",      "MANNAIA",      "MELA",    "OCCHIALI", "OMBRELLONE",\
       "OPALE",    "OROLOGIO", "ORSACCHIOTTO", "PALLA",        "PENDOLA", "PENNA",    "PESCE",     \
       "PICCOZZA", "ROSA",     "RUSPA",        "SOLDATINO",    "STIVALI", "TELEFONO", "UVA")

LIV=-1
MOSSE=0

FONT=pygame.font.SysFont("Z003", 30, bold=False)
SCHERMO=pygame.display.set_mode((LARGHEZZA, ALTEZZA))

def main():

    global  SCHERMO, NUMERO_COLONNE, NUMERO_RIGHE, MARGINE_X, MARGINE_Y
    
    pygame.display.set_caption("Memory Puzzle")

    mousex=0
    mousey=0
    SCHERMO.blit(SFONDO,(0,0))

    schema=[(2,3), (3,4), (4,4), (4,5), (5,6), (5,8), (6,6), (6,7), (6,8), (7,8), (7,10)]

    global LIV
    LIV+=1

    for i in range(len(schema)):
        if LIV==i:
            NUMERO_RIGHE=schema[i][0]
            NUMERO_COLONNE=schema[i][1]
  
    MARGINE_X=int((LARGHEZZA-(NUMERO_COLONNE*DIMENSIONE_TESSERA+(NUMERO_COLONNE-1)*DISTANZA_TESSERE))/2)
    MARGINE_Y=int((ALTEZZA-(NUMERO_RIGHE*DIMENSIONE_TESSERA+(NUMERO_RIGHE-1)*DISTANZA_TESSERE))/2)   

    tessereXY=Posizione_Tessera()
    icone=Genera_Schema_Gioco()
    
    Visualizza_Scacchiera(icone, 0)
    pygame.display.update()

    rivelate=[]
    while True:

        for event in pygame.event.get():
            if event.type==QUIT or (event.type==KEYUP and  event.key==K_ESCAPE):
                pygame.quit()
                sys.exit()
            elif event.type==MOUSEMOTION:
                mousex, mousey=event.pos
            elif event.type==MOUSEBUTTONUP:
                CLICK.play()
                mousex, mousey==event.pos
                carta=Rivela_Tessera(mousex, mousey, tessereXY, icone)
                
                if carta!=-1 :
                    rivelate.append(carta)
                if len(rivelate)==2:
                    Visualizza_Scacchiera(icone, 1)
                    pygame.display.update()
                    pygame.time.wait(1000)
                    Verifica_Coppie(rivelate[0], rivelate[1], icone)
                    rivelate.clear()

        SCHERMO.blit(SFONDO,(0,0))

        n_mosse="N° Mosse: "+str(MOSSE)
        SCHERMO.blit(FONT.render(n_mosse, 0, (189, 168, 118)), (330,560))

        livello="Livello: "+str(LIV+1)
        SCHERMO.blit(FONT.render(livello, 0, (189, 168, 118)), (30,560))
        
        Visualizza_Scacchiera(icone, 1)
        if (Vittoria(icone)==NUMERO_COLONNE*NUMERO_RIGHE):
            pygame.time.wait(2000)
            COPPIA.play()
            main()
  
        pygame.display.update()

# genera lo schema di gioco inserendo tutte le forme nelle tessere della scacchiera
def Genera_Schema_Gioco():
    icone=[]
    for i in range(2):
        numero=int(NUMERO_COLONNE*NUMERO_RIGHE/2)
        for n in range(numero):
            # il 1° valore boolean indica se la tessera è visibile (TRUE) o coperta (FALSE)
            # il 2° valore boolean indica se il mouse è sopra la tessera (TRUE) oppure no (FALSE)
            # in caso affermativo la tessera viene circolettata di Rosso
            icone.append((CARTE[n], False, False))
    random.shuffle(icone)
    return icone

# visualizza sullo schermo la scacchiera:
# se visibile=0 -> visualizza il dorso delle tessere
# se visibile=1 -> visualizza SOLO le carte già scoperte
def Visualizza_Scacchiera(icone, visibile):
    i=0
    for r in range(NUMERO_RIGHE):
        for c in range(NUMERO_COLONNE):
            x=c*(DIMENSIONE_TESSERA+DISTANZA_TESSERE)+MARGINE_X
            y=r*(DIMENSIONE_TESSERA+DISTANZA_TESSERE)+MARGINE_Y
            if visibile==0:
                SCHERMO.blit(RETRO,(x,y))
                pygame.draw.rect(SCHERMO, CORNICE, (x-2, y-2, 54,54), 2)
                
            elif (visibile==1 and icone[i][1]==True):
                if icone[i][0]=="ALBERO": SCHERMO.blit(ALBERO,(x,y))
                elif icone[i][0]=="ARANCIA": SCHERMO.blit(ARANCIA,(x,y))
                elif icone[i][0]=="AUTOMOBILINA": SCHERMO.blit(AUTOMOBILINA,(x,y))
                elif icone[i][0]=="BABBO_NATALE": SCHERMO.blit(BABBO_NATALE,(x,y))
                elif icone[i][0]=="BAMBOLA": SCHERMO.blit(BAMBOLA,(x,y))
                elif icone[i][0]=="BARATTOLO": SCHERMO.blit(BARATTOLO,(x,y))
                elif icone[i][0]=="BIGLIA": SCHERMO.blit(BIGLIA,(x,y))
                elif icone[i][0]=="CANOTTO": SCHERMO.blit(CANOTTO,(x,y))
                elif icone[i][0]=="CARRIOLA": SCHERMO.blit(CARRIOLA,(x,y))
                elif icone[i][0]=="CASCO": SCHERMO.blit(CASCO,(x,y))
                elif icone[i][0]=="CHITARRA": SCHERMO.blit(CHITARRA,(x,y))
                elif icone[i][0]=="CUCU": SCHERMO.blit(CUCU,(x,y))
                elif icone[i][0]=="DADI": SCHERMO.blit(DADI,(x,y))
                elif icone[i][0]=="FORMULA_1": SCHERMO.blit(FORMULA_1,(x,y))
                elif icone[i][0]=="GALLO": SCHERMO.blit(GALLO,(x,y))
                elif icone[i][0]=="GIOSTRA": SCHERMO.blit(GIOSTRA,(x,y))
                elif icone[i][0]=="LAMPADA": SCHERMO.blit(LAMPADA,(x,y))
                elif icone[i][0]=="MANNAIA": SCHERMO.blit(MANNAIA,(x,y))
                elif icone[i][0]=="MELA": SCHERMO.blit(MELA,(x,y))
                elif icone[i][0]=="OCCHIALI": SCHERMO.blit(OCCHIALI,(x,y))
                elif icone[i][0]=="OMBRELLONE": SCHERMO.blit(OMBRELLONE,(x,y))
                elif icone[i][0]=="OPALE": SCHERMO.blit(OPALE,(x,y))
                elif icone[i][0]=="OROLOGIO": SCHERMO.blit(OROLOGIO,(x,y))
                elif icone[i][0]=="ORSACCHIOTTO": SCHERMO.blit(ORSACCHIOTTO,(x,y))
                elif icone[i][0]=="PALLA": SCHERMO.blit(PALLA,(x,y))
                elif icone[i][0]=="PENDOLA": SCHERMO.blit(PENDOLA,(x,y))
                elif icone[i][0]=="PENNA": SCHERMO.blit(PENNA,(x,y))
                elif icone[i][0]=="PESCE": SCHERMO.blit(PESCE,(x,y))
                elif icone[i][0]=="PICCOZZA": SCHERMO.blit(PICCOZZA,(x,y))
                elif icone[i][0]=="ROSA": SCHERMO.blit(ROSA,(x,y))
                elif icone[i][0]=="RUSPA": SCHERMO.blit(RUSPA,(x,y))
                elif icone[i][0]=="SOLDATINO": SCHERMO.blit(SOLDATINO,(x,y))
                elif icone[i][0]=="STIVALI": SCHERMO.blit(STIVALI,(x,y))
                elif icone[i][0]=="TELEFONO": SCHERMO.blit(TELEFONO,(x,y))
                elif icone[i][0]=="UVA": SCHERMO.blit(UVA,(x,y))
                    
            elif (visibile==1 and icone[i][1]==False):
                SCHERMO.blit(RETRO,(x,y))

            i+=1
                    
# per ogni tessera determina le coordinate x,y del suo punto di collocazione (alto-sinistra)
def Posizione_Tessera():
    coordinate=[]
    for r in range(NUMERO_RIGHE):
        for c in range(NUMERO_COLONNE):
            x=c*(DIMENSIONE_TESSERA+DISTANZA_TESSERE)+MARGINE_X
            y=r*(DIMENSIONE_TESSERA+DISTANZA_TESSERE)+MARGINE_Y
            coordinate.append((x,y))
    return coordinate

# mostra la tessera sulla quale l'utente ha cliccato con il mouse
def Rivela_Tessera(x,y, tessereXY, icone):
    for a in tessereXY:
        carta=-1
        if x>=a[0] and x<=a[0]+50 and y>=a[1] and y<=a[1]+50:
            ax=(a[0]-tessereXY[0][0])//60
            ay=(a[1]-tessereXY[0][1])//60
            carta=ay*NUMERO_COLONNE+ax
            icone[carta]=(icone[carta][0], True, False)
            break
    return carta

        

def Verifica_Coppie(a1, a2, icone):
    global MOSSE
    MOSSE+=1
    if icone[a1]==icone[a2]:
        icone[a1]=(icone[a1][0], True, True)
        icone[a2]=(icone[a2][0], True, True)
    else:
        DIVERSI.play()
        icone[a1]=(icone[a1][0], False, True)
        icone[a2]=(icone[a2][0], False, True)

def Vittoria(icone):
    numero=0
    for i in range(NUMERO_RIGHE*NUMERO_COLONNE):
        if (icone[i][1]==True):
            numero+=1
    return numero

if __name__=="__main__":
    main()

Memory

Il codice del programma con le immagine e suoni, sono contenuti nel file .zip disponibile per il download.

Requisiti
  • Python 3.10
  • PyGame 2.5.2
  • Dimensione 1.4 MB
  • Freeware
Download Memory