Advertisement
AntonioVillanueva

Matriz Rusa 5x5 tkinter

Aug 12th, 2019
393
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.62 KB | None | 0 0
  1. """
  2. Antonio Villanueva Segura
  3. Matriz Rusa  5x5 en python3 con clase ...
  4. """
  5. #!/usr/bin/env python
  6. # -*- coding: utf-8 -*-
  7. from tkinter import *
  8. import random
  9.  
  10. class Juego ():
  11.     def __init__(self):
  12.         """constructor del Juego """
  13.         self.matriz=[] #Estructura con numeros,activacion,seleccionado
  14.        
  15.         self.LabelIzq=[] #Etiquetas con el valor de la suma buscado
  16.         self.LabelDer=[] #Etiquetas con el valor de la suma buscado
  17.         self.LabelSup=[] #Etiquetas con el valor de la suma buscado
  18.         self.LabelInf=[] #Etiquetas con el valor de la suma buscado
  19.        
  20.         self.intentos=0 #Intentos del jugador
  21.        
  22.         self.creaJuego() #Construye juego  
  23.  
  24.     def botonFin(self,ventana):
  25.         """ Fin de partida , destruye ventana e reinicializa el juego"""
  26.         ventana.destroy()
  27.         self. __init__()
  28.        
  29.     def callback(self,boton):
  30.         """Accion sobre el boton , lo desactiva para la suma """
  31.  
  32.         if (boton.cget('bg')=='red'):
  33.             boton.configure(bg = 'yellow')
  34.         else:
  35.             boton.configure(bg = "red")
  36.  
  37.         self.intentos+=1
  38.            
  39.         if (self.analisisArray()):#Analiza sumas
  40.             print ("Lo has conseguido en ",self.intentos, "intentos")
  41.             ventanaInformativa = Toplevel()
  42.             ventanaInformativa.resizable(0,0) #No cambiar size ventana
  43.             ventanaInformativa.geometry("300x50+0+0")
  44.             Label(ventanaInformativa ,text="Ok lo has conseguido en  "+str(self.intentos),fg='red').pack()
  45.             Button(ventanaInformativa ,text="OK",fg='red',command= lambda ventana=ventanaInformativa: self.botonFin(ventana)).pack()           
  46.  
  47.     def aleatorio(self,minimo=1,maximo=10):
  48.         """genera un numero aleatorio en rango minimo maximo"""
  49.         return random.randrange(minimo,maximo)
  50.        
  51.     def creaArray(self):
  52.         """crea un array 2D 5x5 Primer Campo es el boton, el segundo si es activo en el resultado suma"""      
  53.         for x in range (0,5):
  54.             linea=[]#Crea una linea vacia          
  55.             for y in range(0,5):   
  56.                 linea.append( [ Button(root,text=str( self.aleatorio() ),bg="yellow"), #Crea un boton
  57.                                 True if (self.aleatorio(0,2)==1) else False ] )
  58.                 #Configura el callback con el ultimo boton en si mismo
  59.                 linea[-1][0].configure(command= lambda boton=linea[-1][0]: self.callback(boton) )  
  60.                 linea[-1][0].grid(row=x+1, column=y+1)# Lo inserta graficamente en la rejilla  
  61.                                        
  62.             self.matriz.append(linea)#Anade  linea a la matriz 2D
  63.  
  64.     def analisisArray(self):
  65.         """Analiza suma en las lineas """
  66.         for x in range (0,5):#Recorre x lineas
  67.             suma=0
  68.             for y in range (0,5):#Recorre y  columnas
  69.                
  70.                 if self.matriz[x][y][0].cget('bg')=='yellow':#Es un boton activo en la suma
  71.                     suma+=int (self.matriz[x][y][0].cget('text'))#Recupera cifra en el boton               
  72.                    
  73.             """ Afecta color etiquetas Izq. y Der. """ 
  74.             if suma == int ( self.LabelIzq[x].cget('text') ):#Si la suma se cumple es verde
  75.                 self.LabelIzq[x].configure(fg='green')
  76.                 self.LabelDer[x].configure(fg='green')                 
  77.             else:
  78.                 self.LabelIzq[x].configure(fg='blue')
  79.                 self.LabelDer[x].configure(fg='blue')      
  80.                    
  81.         """Analiza suma en columnas """
  82.         for y in range (0,5):#Recorre y lineas
  83.             suma=0
  84.             for x in range (0,5):#Recorre x  columnas
  85.                
  86.                 if self.matriz[x][y][0].cget('bg')=='yellow':#Es un boton activo en la suma
  87.                     suma+=int (self.matriz[x][y][0].cget('text'))#Recupera cifra en el boton               
  88.                    
  89.             """ Afecta color etiquetas Sup. e Inf. """ 
  90.             if suma ==  int ( self.LabelSup[y].cget('text') ):#Si la suma se cumple es verde
  91.  
  92.                 self.LabelSup[y].configure(fg='green')
  93.                 self.LabelInf[y].configure(fg='green')                 
  94.             else:
  95.                 self.LabelSup[y].configure(fg='blue')
  96.                 self.LabelInf[y].configure(fg='blue')  
  97.  
  98.  
  99.         """Ha sido completada , las etiquetas son verdes """
  100.         for etiqueta in self.LabelIzq:
  101.             if etiqueta.cget('fg')=='blue':
  102.                 return False
  103.                
  104.         for etiqueta in self.LabelSup:
  105.             if etiqueta.cget('fg')=='blue':
  106.                 return False   
  107.        
  108.         return True        
  109.                                
  110.     def creaEtiquetasSuma(self):       
  111.         """ crea las etiquetas laterales ,superior e inferior con la suma"""           
  112.         for x in range (0,5):#Recorre x las lineas
  113.             suma=0#Inicializa la suma
  114.             for y in range(0,5):#Crea la suma de esta linea
  115.                 if self.matriz[x][y][1]:#Es elemento de suma ?
  116.                     suma+= int (self.matriz[x][y][0].cget('text'))
  117.  
  118.             #Etiquetas en x, 0,1,2,3,4
  119.             self.LabelIzq.append (Label(root,text=str(suma),fg='blue'))
  120.             self.LabelIzq[-1].grid(row=x+1, column=0)#Coordenas
  121.             self.LabelDer.append (Label(root,text=str(suma),fg='blue'))
  122.             self.LabelDer[-1].grid(row=x+1, column=7)#Coordenas
  123.                        
  124.         """Genera etiquetas columna de suma arriba e abajo """
  125.         for y in range (0,5):#Recorre las columnas
  126.             suma=0#Inicializa la suma          
  127.             for x in range(0,5):#Crea la suma de esta linea
  128.                 if self.matriz[x][y][1]:#Es elemento de suma ?
  129.                     suma+= int (self.matriz[x][y][0].cget('text'))
  130.                    
  131.             #Etiquetas en y, 0,1,2,3,4     
  132.             self.LabelSup.append (Label(root,text=str(suma),fg='blue'))
  133.             self.LabelSup[-1].grid(row=0, column=y+1)#Coordenas
  134.             self.LabelInf.append (Label(root,text=str(suma),fg='blue'))
  135.             self.LabelInf[-1].grid(row=7, column=y+1)#Coordenas
  136.                            
  137.     def creaJuego(self):
  138.         """ Crea matriz 5x5 etiquetas y botones """
  139.         self.creaArray()#Inicializa el array de numeros aleatorios de 3 campos
  140.         #self.creaBotones() #Botones con los datos de la matriz
  141.         self.creaEtiquetasSuma() #Labels laterales sup. e inf.
  142.  
  143.  
  144.         #Debug para analizar las casillas seleccionadas
  145.  
  146.         for x in range (5):
  147.             for y in range (5):
  148.                 print (self.matriz[x][y][1], end=",")
  149.             print ("\n")
  150.            
  151. root = Tk()
  152. root.config(bd=5)  # borde exterior de la ventana 10 Pixels
  153. root.title('5x5  A.Villanueva')
  154. root.resizable(0,0) #No cambiar size ventana
  155.  
  156. matrizRusa=Juego() #Instancia el Juego
  157. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement