UNIDAD 5

 CRISTAL CRUZ CRUZ 

UNIDAD 5



Programa 1

from tkinter import *


ventana = Tk()


ventana.title("Bienvenidos")                     # Establece el título de la ventana como "Bienvenidos"


ventana.mainloop()    



Programa 2


from  tkinter import *


ventana = Tk ()


ventana.title ("Bienvenidos")


lbl = Label(ventana, text="Hola como estas")      #instancia label es un objeto y lo de entre paréntesis son atributos


lbl.grid(column=6, row=2)                               #un grid es una cuadricula


ventana.mainloop()



Programa 3


from tkinter import *

ventana = Tk ()


ventana.title("Programacion visual")


ventana.geometry('350x200')       #Abre ventana


lbl = Label (ventana, text="Hoooooooola, soy Criss")


lbl.grid(column=0, row=0)


btn = Button(ventana, text="Click me")   #añade botón


btn.grid(column=1, row=0)


ventana.mainloop()



Programa 4


from tkinter import *

ventana = Tk ()

ventana.title("programacion visual")

ventana.geometry('350x200')

lbl = Label (ventana, text='Hooooooola')


lbl.grid(column=0, row=0)


def clicked():

lbl.configure(text="El boton fue clicked")        #añade texto



btn = Button (ventana, text="Click Me", command=clicked)

#con los argumentos () se activa el comando


btn.grid(column=1, row=0)


ventana.mainloop()



Programa 5


from tkinter import *

ventana = Tk ()

ventana.title("programacion visual") 

ventana.geometry('350x200')

lbl = Label (ventana, text='Hooooooola')     #AÑADE VENTANA CON TEXTO

lbl.grid(column=0, row=0)

txt =Entry(ventana, width=10)

txt.grid(column=1, row=0)


def clicked():

nombre = txt.get()   #PERMITE INGRESAR NOMBRE

lbl.configure(text="Boton fue clicked")

btn = Button (ventana, text="Click Me", command=clicked)


btn.grid(column=2, row=0)


ventana.mainloop ()


#hagan un programa que pida el nombre en una entrada

#e imprimanlo en una etiqueta. utkej1.py




Programa 6


from turtle import *

#import turtle

t=Turtle()

screen=t.getscreen()

#Turtle.getscreen

setup(640,480)

t.left(90)

t.forward(200)

screen.exitonclick()

t.left(-90)

t.forward(200)

t.left(-200)

t.forward(180)


t.home()

screen.exitonclick()




Programa 7

#Crea un circulo

import turtle

t=turtle.Turtle()

#t.left(90)

r=50

t.circle(r)


screen=t.getscreen

screen.exitonclick() 



Programa 8

#Este programa realiza un circulo, que lleva un relleno de color.


import turtle


t = turtle.Turtle(

r = 50



t.fillcolor('IndianRed')  

t.begin_fill()  


t.circle(r) 


t.end_fill() 


screen = turtle.Screen()  

screen.exitonclick() 



Programa 9

import turtle


t = turtle.Turtle()

r = 50



t.fillcolor('IndianRed')  

t.begin_fill()  


t.circle(r) 


t.end_fill() 


screen = turtle.Screen()  

screen.exitonclick() 




Programa 10

import turtle

"""t=turtle.Turtle()

#t.left(180)

r=10 #radio

n=10                                 #numero de circulos


turtle.colormode(255)

t.color(148,0,211)


for i in range(1,n+1):

#t.begin_fill()

t.circle(r*i)

#t.end_fill()

screen=t.getscreen()

screen.exitonclick()"""


t = turtle.Turtle()

t.speed(0)                                      # Velocidad más rápida

#t.left(180)

r = 20  # Radio

n = 15                                      # Número de círculos (para los pétalos)


turtle.colormode(255)

t.color(255, 105, 180)  



def petalos():

    for i in range(2):

        t.circle(r*1)

        t.left(60)

        t.circle(r*1)

        t.left(120)

for i in range(6):  

    petalos()

    t.left(60)

    t.forward(r*2)

    t.left(60)

    t.backward(r*2)


screen = t.getscreen()

screen.exitonclick()


Programa 11


#Programa hecho en RASP



import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BCM)

GPIO.setup(18, GPIO.OUT)

for i in range (0,5):

GPIO.output(18, GPIO.HIGH)             #encendido

time.sleep(1)

GPIO.output(18, GPIO.LOW)         #apagado

time.sleep(1)

GPIO.cleanup()




Programa 12


#PROGRAMA DE TAREA

#UNLED

#HECHO EN RASP

from tkinter import * 

import turtle 

import RPi.GPIO as GPIO 

import time


t = turtle.Turtle()

t.speed(5)  


ventana = Tk() 

ventana.title("Primer programa en Raspberry")

ventana.geometry('350x200')

lbl = Label(ventana, text="Para empezar...")

lbl.grid(column=0, row=0)


def clicked(): 

    lbl.configure(text="Lista para comenzar")

    

    GPIO.setmode(GPIO.BCM) 

    GPIO.setup(18, GPIO.OUT) 

    

    r = 10  

    n = 5  

    t.clear() 


    for j in range(1): 

        GPIO.output(18, GPIO.HIGH) 

        t.home()

        t.color("Orchid") 

        t.fillcolor("IndianRed")

        

        for i in range(1, n + 1): 

            GPIO.output(18, GPIO.HIGH) 

            t.begin_fill() 

            t.circle(r*i) 

            GPIO.output(18, GPIO.LOW) 

            time.sleep(1) 

            t.end_fill() 

        

        time.sleep(1) 

        GPIO.output(18, GPIO.LOW) 

        t.clear() 

        time.sleep(1) 

    GPIO.cleanup() 


botoncito = Button(ventana, text="Click me", command=clicked)  

botoncito.grid(column=2, row=2) 


ventana.mainloop()


screen = t.getscreen() 

screen.exitonclick()



Programa 13


#Tarjeta día de las madres

#TARJETA DIA DE LAS MADRES

import turtle

import math



screen = turtle.Screen()

screen.bgcolor("lightyellow")

screen.title("Para mi mamá Estela ,Feliz Día de las Madres señora de los gatos")


t = turtle.Turtle()

t.shape('turtle')  

t.speed(9)

t.pensize(2)

t.showturtle()  



def dibujar_corazon(pos_x, pos_y, tamaño, color):                     #para dibujar el corazon del centro

    t.penup()

    t.goto(pos_x, pos_y)

    t.pendown()

    t.color(color)

    t.begin_fill()

    t.left(50)

    t.forward(tamaño)

    t.circle(tamaño/2, 180)

    t.right(90)

    t.circle(tamaño/2, 180)

    t.forward(tamaño)

    t.end_fill()

    t.setheading(0)  



colores = ["#FF6B6B", "#FF8E8E", "#FFA3A3", "#FFC1C1", "#FFD8D8", "#FFE5E5", "#FFEEEE"]


def dibujar_flor(x, y, color, tamaño):

    t.penup()

    t.goto(x, y)

    t.pendown()

    t.color(color)

    for _ in range(6):

        t.begin_fill()

        t.circle(tamaño, 60)

        t.left(120)

        t.circle(tamaño, 60)

        t.left(60)

        t.end_fill()



radio_flores = 200

for i in range(7):

    angulo = 2 * math.pi * i / 7

    x = math.cos(angulo) * radio_flores

    y = math.sin(angulo) * radio_flores

    dibujar_flor(x, y, colores[i], 25)



dibujar_corazon(0, -30, 60, "#FF0000")                  #Funcion para poder dibujar el corazon



t.penup()

t.goto(0, -60)

t.color("#333333")

t.write("Estela", align="center", font=("Arial", 36, "bold"))



t.penup()

t.goto(0, -280)

t.color("#D40000")

t.write("¡Feliz Día de las Madres señora de los gatos!", align="center", font=("Arial", 24, "normal"))


t.penup()

t.goto(200, 200)

t.color("green")

t.write("De Criss", font=("Arial", 10, "italic"))


turtle.done()



Programa 14


from tkinter import*

ventana=Tk()

ventana.geometry("300x300")

ventana.title("Unidad 5")


etiqueta=Label(ventana,text='Minimizar')

etiqueta.pack()

boton=Button(ventana,text='Minimizar',command=ventana.iconify)


boton.pack()

ventana.mainloop()



Programa 15


from tkinter import *

import time 

def parpadear():

ventana.iconify()

time.sleep(2)

ventana.deiconify()

ventana=Tk()

ventana.title("Segunda ventana en tkinter")

btn=Button(ventana,text="Evento", command=parpadear)

btn.pack()

ventana.mainloop()



Programa 16

#PROGRAMA QUE MUESTRA DOS BOTONES DIFERENTES, UNO DE IMPRIMIR Y OTRO DE SALIR

from tkinter import *

def imprime():

print("Acabas de dar click a imprimir ")

cuadro=Tk()

cuadro.geometry("300x300")

cuadro.title("Dos botones")

btnS=Button(cuadro,text="Salir", fg="Red", command=cuadro.quit)

btnS.pack(side=LEFT)

btnI=Button(cuadro,text="Imprime", fg="Blue", command=imprime)

btnI.pack(side=RIGHT)

cuadro.mainloop()



Programa 17



#POSICIONES, MUESTRA TRES DIFERENTES

from tkinter import *


ventana = Tk()

ventana.geometry("300x300")

ventana.title("Posiciones")


btn = Button(ventana, text="posicion uno").grid(row=0, column=0)  

etq1 = Label(ventana, text="posicion dos").grid(row=0, column=1)

etq2 = Label(ventana, text="posicion tres").grid(row=1, column=1)

etq3 = Label(ventana, text="posicion cuatro").grid(row=2, column=1)  


ventana.mainloop()



Programa 18


from tkinter import *

ventana = Tk()

ventana.geometry("300x300")

ventana.title("Posiciones")

btn = Button(ventana, text="posicion uno").place(x=10,y=10)  #muestra posiciones

#Place es el lugar donde se quiere poner

lbl1 = Label(ventana, text="posicion dos").place(x=200, y=10)

lbl2 = Label(ventana, text="posicion tres").place(x=10, y=45)

lbl3 = Label(ventana, text="posición cuatro").place(x=200, y=40) 


ventana.mainloop()



Programa 19

from tkinter import *


def saludo():

print("Te saludo")                               #CMD

def chiquito():

ventana.iconify()

ventana=Tk()

ventana.title("Ejercicio")

ventana.geometry("400x200")

lbl1=Label(ventana,text="Click para saludar", fg="red"), (placex=30,y=50)



Programa 20


#Ejemplo para hacer la tarea


from tkinter import *


def saluda():

    print("Hola: " + nombre.get() + " " + apellidoP.get() + " " + apellidoM.get())


ventana = Tk()

ventana.geometry("400x200")

ventana.title("Capture")


nombre = StringVar()

apellidoP = StringVar()

apellidoM = StringVar()


nombre.set("Escribe tu nombre")


lbln = Label(ventana, text="Nombre: ").place(x=10, y=10)

bxn = Entry(ventana, textvariable=nombre).place(x=170, y=10)


lblap = Label(ventana, text="Apellido Paterno").place(x=10, y=40)

bxap = Entry(ventana, textvariable=apellidoP).place(x=170, y=38)


lblam = Label(ventana, text="Apellido Materno").place(x=10, y=70)

bxam = Entry(ventana, textvariable=apellidoM).place(x=170, y=70)


btns = Button(ventana, text="Te saludo", command=saluda).place(x=10, y=110)


ventana.mainloop()



Programa 21

#TAREA


from tkinter import *


def saluda():

    saludo = "Holaaaaaaaa " + nombre.get() + " " + apellidoP.get() + " " + apellidoM.get()

    lbl_saludo.config(text=saludo, fg="#FF5733") 


ventana = Tk()

ventana.geometry("400x200")

ventana.title("Capture")

nombre = StringVar()

apellidoP = StringVar()

apellidoM = StringVar()

lbln = Label(ventana, text="Nombre:", fg="#2874A6").place(x=10, y=10) 

bxbn = Entry(ventana, textvariable=nombre).place(x=170, y=10)


lblap = Label(ventana, text="Apellido Paterno:", fg="#2874A6").place(x=10, y=40)  

bxap = Entry(ventana, textvariable=apellidoP).place(x=170, y=38)


lblam = Label(ventana, text="Apellido Materno:", fg="#2874A6").place(x=10, y=70) 

bxbam = Entry(ventana, textvariable=apellidoM).place(x=170, y=70)


lbl_saludo = Label(ventana, text="", fg="#FF5733")  

lbl_saludo.place(x=10, y=130)

btns = Button(ventana, 

             text="Te saludo ", 

             command=saluda, 

             bg="#58D68D",  

             fg="#17202A").place(x=10, y=170, width=380)  


ventana.mainloop()




#boton de enviar en cualquier color y la etiqueta de saludo dentro de Tk

#que el boton este hasta abajo




Programa 22


from tkinter import *


def operation():

    try:

        numero = num.get()

        if opcion.get() == 1:

            total = numero * 10

        elif opcion.get() == 2:

            total = numero * 20

        elif opcion.get() == 3:

            total = numero * 30

        elif opcion.get() == 4:

            total = numero * 40

        elif opcion.get() == 5:

            total = numero * 50

        else:

            total = "Opción no válida"

        

        resultado.config(text="Resultado: " + str(total), fg="blue")

        print("El total de las operaciones es: " + str(total))

    except:

        resultado.config(text="Ingresa un número válido", fg="red")


ventana = Tk()

opcion = IntVar()

num = IntVar()

ventana.title("Botones de radio")

ventana.geometry("400x300")


# Widgets

etiqueta1 = Label(ventana, text="Escribe un número:")

etiqueta1.place(x=20, y=20)


cajanumero = Entry(ventana, bd=5, cursor="cross", textvariable=num)

cajanumero.place(x=130, y=20)


etiqueta2 = Label(ventana, text="Elige tu opción:")

etiqueta2.place(x=20, y=50)


# Radio buttons

Radiobutton(ventana, text="X10", value=1, variable=opcion).place(x=20, y=80)

Radiobutton(ventana, text="X20", value=2, variable=opcion).place(x=70, y=80)

Radiobutton(ventana, text="X30", value=3, variable=opcion).place(x=120, y=80)

Radiobutton(ventana, text="X40", value=4, variable=opcion).place(x=20, y=110)

Radiobutton(ventana, text="X50", value=5, variable=opcion).place(x=70, y=110)

Radiobutton(ventana, text="Cuadro", value=6, variable=opcion).place(x=120, y=110)


# Operation button

boton = Button(ventana, text="Realiza operación", command=operation)

boton.place(x=20, y=149)


# Result label

resultado = Label(ventana, text="Resultado: ", fg="blue")

resultado.place(x=150, y=149)


ventana.mainloop()



Programa 23


#imagen en una ventana

from tkinter import*

ventana=Tk()

ventana.title("Uso de imágenes en tkinter")

ventana.geometry("400x300")

foto=PhotoImage(file="A.png")

fondo=Label(ventana, image=foto).place(x=1, y=1)

ventana.mainloop()



Programa 24


#Spinbox y messagebox

from tkinter import*

from tkinter import messagebox


def obtener():

messagebox.showinfo("Mensaje", "Seleccion es: "+valor.get())

ventana=Tk()

valor=StringVar()

ventana.title("Uso del spinbox")

ventana.geometry("400x300")

lbl=Label(ventana, text="Ejemplo 1 Spinbox").place(x=20, y=20)

combo=Spinbox(ventana, values=("uno", "dos", "tres", "cuatro", "cinco")).place(x=20, y=50)

lbl2=Spinbox(ventana, from_=1, to=10, textvariable=valor).place(x=20, y=110)

boton=Button(ventana, text="Obtener valor Spinbox", command=obtener).place(x=50, y=140)

mainloop()


Programa 25

#PROGRAMA 25


'''

from tkinter import *

from tkinter import messagebox


def obtener ():

#print(valor.get())

#lbl3=Label

'''

#PROGRAMA 25

from tkinter import *

import tkinter.messagebox as messagebox


def calcular_imc():

    try:

        peso = float(entry_peso.get())

        altura = float(entry_altura.get())


        if peso <= 0 or altura <= 0:

            messagebox.showerror("Error", "El peso y altura deben ser valores positivos")

            return


        imc = peso / (altura ** 2)

        if imc < 18.5:

            categoria = "Bajo peso"

        elif 18.5 <= imc < 25:

            categoria = "Peso normal"

        elif 25 <= imc < 30:

            categoria = "Sobrepeso"

        else:

            categoria = "Obesidad"


        resultado = f"{nombre.get()}, tu IMC es: {imc:.2f}\nCategoría: {categoria}"

        messagebox.showinfo("Resultado IMC", resultado)


    except:

        messagebox.showerror("Error", "Ingresa valores numéricos válidos")


ventana = Tk()

ventana.title("Calculadora de IMC")

ventana.geometry("380x380")


try:

    foto = PhotoImage(file=r"C:\Users\criss\Pictures\Saved Pictures\vincent.png")


    canvas = Canvas(ventana, width=400, height=400)

    canvas.pack(fill="both", expand=True)

    canvas.create_image(0, 0, image=foto, anchor="nw")


    # Etiquetas y campos de entrada directamente sobre el fondo

    canvas.create_text(100, 50, text="Nombre:", fill="black", font=("Arial", 10, "bold"), anchor="w")

    nombre = Entry(ventana, fg="black")

    canvas.create_window(220, 50, window=nombre)


    canvas.create_text(100, 90, text="Altura (m)", fill="black", font=("Arial", 10, "bold"), anchor="w")

    entry_altura = Entry(ventana, fg="black")

    canvas.create_window(220, 90, window=entry_altura)


    canvas.create_text(100, 130, text="Peso (kg)", fill="black", font=("Arial", 10, "bold"), anchor="w")

    entry_peso = Entry(ventana, fg="black")

    canvas.create_window(220, 130, window=entry_peso)


    # Botón para calcular IMC

    btn_calcular = Button(ventana, text="Calcular IMC", command=calcular_imc,

                          bg="#4CAF50", fg="white", relief="raised", borderwidth=3)

    canvas.create_window(190, 180, window=btn_calcular)


except :

    print("Error")


ventana.mainloop()


Programa 26


#EN RASPBERRY

from tkinter import*

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)    #Lo cambiamos a board para que esten juntos

GPIO.setup(11,GPIO.OUT)#RED        

GPIO.setup(13,GPIO.OUT)#GREEN

GPIO.setup(15,GPIO.OUT)#BLUE


GPIO.output(11,1)

time.sleep(1)

GPIO.output(13,1)

time.sleep(1)

GPIO.output(15,1)

tome.sleep(1)


GPIO.output(11,0)

GPIO.output(13,0)

GPIO.output(15,0)

time.sleep(1)

GPIO.output(11,1)

GPIO.output(13,0)

GPIO.output(15,1)

time.sleep(1)


GPIO.output(11,1)

GPIO.output(13,1)

GPIO.output(15,1)

time.sleep(1)


GPIO.output(11,0)

GPIO.output(13,1)

GPIO.output(15,1)

time.sleep(1)


GPIO.output(11,0)

GPIO.output(13,0)

GPIO.output(15,0)


GPIO.cleanup()


Programa 27

#EJEMPLO PARA PODER REALIZAR EL PROYECTO 

from random import choice

from time import sleep

from turtle import *


from freegames import floor, square, vector


pattern = []

guesses = []

tiles = {

    vector(0, 0): ('red', 'dark red'),

    vector(0, -200): ('blue', 'dark blue'),

    vector(-200, 0): ('green', 'dark green'),

    vector(-200, -200): ('yellow', 'khaki'),

}



def grid():

    """Dibuja cuadros """

    square(0, 0, 200, 'dark red')

    square(0, -200, 200, 'dark blue')

    square(-200, 0, 200, 'dark green')

    square(-200, -200, 200, 'khaki')

    update()



def flash(tile):

    """Flash tile in grid."""

    glow, dark = tiles[tile]

    square(tile.x, tile.y, 200, glow)

    update()

    sleep(0.5)

    square(tile.x, tile.y, 200, dark)

    update()

    sleep(0.5)



def grow():

    """Grow pattern and flash tiles."""

    tile = choice(list(tiles))

    pattern.append(tile)


    for tile in pattern:

        flash(tile)


    print('Pattern length:', len(pattern))

    guesses.clear()



def tap(x, y):

    """Respond to screen tap."""

    onscreenclick(None)

    x = floor(x, 200)

    y = floor(y, 200)

    tile = vector(x, y)

    index = len(guesses)


    if tile != pattern[index]:

        exit()


    guesses.append(tile)

    flash(tile)


    if len(guesses) == len(pattern):

        grow()


    onscreenclick(tap)



def start(x, y):

    """Start game."""

    grow()

    onscreenclick(tap)



setup(420, 420, 370, 0)

hideturtle()

tracer(False)

grid()

onscreenclick(start)

done()

__________________________________________________

import tkinter as tk

from tkinter import filedialog

import pygame


class AudioPlayerApp:

    def __init__(self, root):

        self.root = root

        self.root.title("Reproducir Audio")


        # Create buttons for opening, playing, pausing, and resuming audio files

        self.open_button = tk.Button(root, text="Open Audio File", command=self.open_audio)

        self.play_button = tk.Button(root, text="Play", state=tk.DISABLED, command=self.play_audio)

        self.pause_button = tk.Button(root, text="Pause", state=tk.DISABLED, command=self.pause_audio)



        self.open_button.pack(pady=10)

        self.play_button.pack()

        self.pause_button.pack()



        # Initialize pygame

        pygame.mixer.init()


        # Register a callback to stop audio when the window is closed

        root.protocol("WM_DELETE_WINDOW", self.on_closing)


        # Initialize playback state

        self.paused = False


    def open_audio(self):

        file_path = filedialog.askopenfilename(filetypes=[("Audio Files", "*.mp3 *.wav")])

        if file_path:

            self.audio_file = file_path

            self.play_button.config(state=tk.NORMAL)


    def play_audio(self):

        pygame.mixer.music.load(self.audio_file)

        pygame.mixer.music.play()

        self.play_button.config(state=tk.DISABLED)

        self.pause_button.config(state=tk.NORMAL)


    def pause_audio(self):

        pygame.mixer.music.pause()

        self.pause_button.config(state=tk.DISABLED)

        self.paused = True



    def on_closing(self):

        # Check if audio is currently playing

        if pygame.mixer.music.get_busy():

            # Stop audio playback before closing the application

            pygame.mixer.music.stop()

        self.root.destroy()


if __name__ == "__main__":

    root = tk.Tk()

    app = AudioPlayerApp(root)

    root.mainloop()


Programa 28

#FORMATO PARA SONIDOS DADO POR LA MAESTRA


import tkinter as tk


from tkinter import filedialog


import pygame




class AudioPlayerApp:


    def init(self, root):


        self.root = root


        self.root.title("Reproducir Audio")




        # Create buttons for opening, playing, pausing, and resuming audio files


        self.open_button = tk.Button(root, text="Open Audio File", command=self.open_audio)


        self.play_button = tk.Button(root, text="Play", state=tk.DISABLED, command=self.play_audio)


        self.pause_button = tk.Button(root, text="Pause", state=tk.DISABLED, command=self.pause_audio)






        self.open_button.pack(pady=10)


        self.play_button.pack()


        self.pause_button.pack()






        # Initialize pygame


        pygame.mixer.init()




        # Register a callback to stop audio when the window is closed


        root.protocol("WM_DELETE_WINDOW", self.on_closing)




        # Initialize playback state


        self.paused = False




    def open_audio(self):


        file_path = filedialog.askopenfilename(filetypes=[("Audio Files", "*.mp3 *.wav")])


        if file_path:


            self.audio_file = file_path


            self.play_button.config(state=tk.NORMAL)




    def play_audio(self):


        pygame.mixer.music.load(self.audio_file)


        pygame.mixer.music.play()


        self.play_button.config(state=tk.DISABLED)


        self.pause_button.config(state=tk.NORMAL)




    def pause_audio(self):


        pygame.mixer.music.pause()


        self.pause_button.config(state=tk.DISABLED)


        self.paused = True






    def on_closing(self):


        # Check if audio is currently playing


        if pygame.mixer.music.get_busy():


            # Stop audio playback before closing the application


            pygame.mixer.music.stop()


        self.root.destroy()




if name == "main":


    root = tk.Tk()


    app = AudioPlayerApp(root)



    root.mainloop()



Programa 29


#PROYECTO DE UNIDAD

#SIMON SAY'S


#FINAL, AHORA SI

#ESTE ES EL FINAL

#PROGRAMA TERMINADO CRISS Y ELI




from tkinter import *

import tkinter as tk

import glob                                         #librería que importa para poder manejar archivos con patrones

import time                                        #para poder controlar el tiempo

import ast                                           #sirve para evaluar strings como estructuras de datos Python

import pygame                                   #para poder reproducir sonidos

import RPi.GPIO as GPIO                #controlar los GPIO de Raspberry Pi


GPIO.setmode(GPIO.BOARD)

GPIO.setwarnings(False)

GPIO.setup(11, GPIO.OUT)#salida para led rojo

GPIO.setup(13, GPIO.OUT)#salida para LED verde

GPIO.setup(15, GPIO.OUT)#salida para LED azul


def led_off():#para apagar todos los LEDs

    GPIO.output(11, GPIO.LOW)#apagar led rojo

    GPIO.output(13, GPIO.LOW)#apagar led amarillo

    GPIO.output(15, GPIO.LOW)#apagar lud azul


def led_rojo():                                                                #encender el led rojo

    led_off()

    GPIO.output(11, GPIO.HIGH)


def led_verde():                                                                #encender el led verde

    led_off()

    GPIO.output(13, GPIO.HIGH)


def led_azul():                                                                    #encender el led azul

    led_off()

    GPIO.output(15, GPIO.HIGH)

    

def led_amarillo():                                                            #encender led rojo y verde

    led_off()

    GPIO.output(11, GPIO.HIGH)

    GPIO.output(13, GPIO.HIGH)


def led_azul():

    led_off()

    GPIO.output(15, GPIO.HIGH)


def led_amarillo():

    led_off()

    GPIO.output(11, GPIO.HIGH)

    GPIO.output(13, GPIO.HIGH)


# Configuración ventana principal

ventana = Tk()

ventana.title("Simon dice por Criss y Eli")

ventana.geometry("400x400")

icono = tk.PhotoImage(file=r"C:\Users\criss\Pictures\Saved Pictures\logo.png")

ventana.iconphoto(True, icono)



color = "nada"                                                #para almacenar el color actual seleccionado

lcol = []                                                                            #para almacenar la secuencia de colores

archivito = ""                                                                        #para el nombre del archivo actual

nombre = StringVar()

secuencia_compu = []                                                    #almacenar la secuencia del juego

juego_compu = False                                    #indicar si el juego está en modo reproducción

contar_colores = 0                                                #verificar la secuencia del usuario


# Inicialización de audio


pygame.init()

pygame.mixer.init()


def reproducir_sonido(archivo):               #funcion para reproducir sonidos

    try:

        pygame.mixer.music.load(archivo)             #cargar archivo de sonido

        pygame.mixer.music.play()

    except:

        print(f"No se pudo reproducir el sonido: {archivo}")


def verde():

    reproducir_sonido("Pousalto.mp3")


def rojo():

    reproducir_sonido("Pouno.mp3")


def amarillo():

    reproducir_sonido("Pouagua.mp3")


def azul():

    reproducir_sonido("Poucomiendo.mp3")


archivo_actual_label = Label(ventana, text="Archivo: (ninguno)")

archivo_actual_label.grid(column=0, row=2, columnspan=2)

aviso = Label(ventana, text="")

aviso.grid(column=0, row=5, columnspan=2)


def resaltar_boton(boton, color_num):

    colores_puchados = {

        1: 'dark red',

        2: 'green yellow',

        3: 'goldenrod',

        4: 'midnight blue'

    }

    boton.config(bg=colores_puchados[color_num])                 #cambiar color de fondo del botón

   ventana.update()                                                                        #actualizar ventana

    time.sleep(0.5   )                                        #esperar medio segundo

    boton.config(bg='lightgray'                                )#volver al color original del botón

    ventana.update()

    time.sleep(0.2)

def reproducir_juego():

    global juego_compu, contar_colores

    juego_compu = True

    aviso.config(text="Observa la secuencia...")

    ventana.update()


    for color in secuencia_compu:

        if color == 1:

            resaltar_boton(btnr, 1)

            rojo()

        elif color == 2:

            resaltar_boton(btnv, 2)

            verde()

        elif color == 3:

            resaltar_boton(btna, 3)

            amarillo()

        elif color == 4:

            resaltar_boton(btnaz, 4)

            azul()


    juego_compu = False

    contar_colores = 0

    aviso.config(text="¡Repite la secuencia!")

    lcol.clear()


def leer_y_jugar():

    global secuencia_compu

    try:

        with open(archivito, 'r') as f:

            contenido = f.read().strip()

            print(f"\nContenido del archivo '{archivito}':")

            print(contenido)

            print("-----------------------------\n")

            if contenido:

                secuencia_compu = ast.literal_eval(contenido)

                if isinstance(secuencia_compu, list):

                    ventana.after(1000, reproducir_juego)

                else:

                    aviso.config(text="Formato invalido en el archivo")

                    secuencia_compu = []

            else:

                aviso.config(text="El archivo esta vacio")

                secuencia_compu = []

    except:

        aviso.config(text="Error al leer el archivo...")

        secuencia_compu = []


def repeticion_correcta(color_presionado):

    global contar_colores

    if contar_colores < len(secuencia_compu):

        if color_presionado == secuencia_compu[contar_colores]:

            contar_colores += 1

            if contar_colores == len(secuencia_compu):

                aviso.config(text="Completaste la secuencia :)")

        else:

            aviso.config(text="Intenta de nuevo, te equivocaste")

            ventana.after(1000, reproducir_juego)


def clicked(col):

    global color, lcol, archivito


    if col == 1:

        color = "Rojo"

        lcol.append(1)

        if secuencia_compu and not juego_compu:

            repeticion_correcta(1)

            led_rojo()

    elif col == 2:

        color = "Verde"

        lcol.append(2)

        if secuencia_compu and not juego_compu:

            repeticion_correcta(2)

            led_verde()

    elif col == 3:

        color = "Amarillo"

        lcol.append(3)

        if secuencia_compu and not juego_compu:

            repeticion_correcta(3)

            led_amarillo()

    elif col == 4:

        color = "Azul"

        lcol.append(4)

        if secuencia_compu and not juego_compu:

            repeticion_correcta(4)

            led_azul()

    elif col == 6:

        if archivito:

            leer_y_jugar()

        else:

            aviso.config(text="Selecciona un archivo primero")

        return

    elif col == 5:

        if archivito == "":

            aviso.config(text="Selecciona una partida antes de guardar.")

            return

        try:

            with open(archivito, "w") as archivo:

                archivo.write(str(lcol))

            aviso.config(text=f"Partida guardada en '{archivito}'")

            print(f"Secuencia guardada en '{archivito}': {lcol}")

            lcol.clear()

        except:

            aviso.config(text="Error al guardar...")

        return

    elif col == 7:

        menu_archivote()

        return


    lbl = Label(ventana, text=color)

    lbl.grid(column=0, row=4)


def menu_archivote():

    nuevaventanita = Toplevel(ventana)

    nuevaventanita.title("Seleccionar archivo")

    nuevaventanita.geometry("300x300")


    Label(nuevaventanita, text="Selecciona un archivo:").pack(pady=10)


    archivos = glob.glob("*.txt")

    if not archivos:

        Label(nuevaventanita, text="No hay archivos .txt").pack()

        Button(nuevaventanita, text="Crear nuevo", bg="lightgreen", command=lambda: [nuevaventanita.destroy(), crear_nuevo_archivito()]).pack(pady=10)

        return


    lista_archivos = Listbox(nuevaventanita)

    for archivo in archivos:

        lista_archivos.insert(END, archivo)

    lista_archivos.pack(expand=True, fill=BOTH, padx=10, pady=10)


    frame = Frame(nuevaventanita)

    frame.pack(pady=10)


    Button(frame, text="Seleccionar", bg="light coral", command=lambda: [seleccionar_archivo(lista_archivos), nuevaventanita.destroy()]).pack(side=LEFT, padx=5)

    Button(frame, text="Nuevo", bg="purple", command=lambda: [nuevaventanita.destroy(), crear_nuevo_archivito()]).pack(side=LEFT, padx=5)


def seleccionar_archivo(lista):

    global archivito

    seleccion = lista.curselection()

    if seleccion:

        archivito = lista.get(seleccion[0])

        archivo_actual_label.config(text=f"Archivo: {archivito}")

        aviso.config(text="Presiona Play para reproducir")

        try:

            with open(archivito, 'r') as f:

                contenido = f.read()

                print(f"\nArchivo seleccionado: {archivito}")

                print("Contenido:", contenido)

                print("-----------------------------\n")

        except:

            print("No se pudo leer el archivo...")


def crear_nuevo_archivito():

    nueva = Toplevel(ventana)

    nueva.title("Nuevo archivo")

    nueva.geometry("400x350")

    nueva.foto = PhotoImage(file="simonsays.png")

    fondo = Label(nueva, image=nueva.foto)

    fondo.place(x=0, y=0, relwidth=1, relheight=1)

    frame = Frame(nueva)

    frame.place(relx=0.5, rely=0.5, anchor='center')


    Label(frame, text="Nombre del nuevo archivo:").pack(pady=10)

    entrada = Entry(frame)

    entrada.pack(pady=5)


    def guardar_nuevo():

        global archivito

        nombre = entrada.get().strip()

        if nombre:

            archivito = nombre if nombre.endswith('.txt') else nombre + '.txt'

            with open(archivito, 'w') as f:

                f.write("[]")

            archivo_actual_label.config(text=f"Archivo: {archivito}")

            aviso.config(text="Archivo creado. Guarda tu secuencia")

            nueva.destroy()

        else:

            aviso.config(text="Escribe un nombre valido")


    Button(frame, text="Crear", bg="pale violet red", command=guardar_nuevo).pack(pady=10)


# Botones

r = PhotoImage(file=r"C:\Users\criss\Pictures\Saved Pictures\rojo.png").subsample(3, 3)

btnr = Button(ventana, width=100, height=100, image=r, borderwidth=5, command=lambda: clicked(1), activebackground='dark red')

btnr.grid(column=0, row=0)


v = PhotoImage(file=r"C:\Users\criss\Pictures\Saved Pictures\verde.png").subsample(3, 3)

btnv = Button(ventana, width=100, height=100, image=v, borderwidth=5, command=lambda: clicked(2), activebackground='green yellow')

btnv.grid(column=1, row=0)


a = PhotoImage(file=r"C:\Users\criss\Pictures\Saved Pictures\amarillo.png").subsample(3, 3)

btna = Button(ventana, width=100, height=100, image=a, borderwidth=5, command=lambda: clicked(3), activebackground='goldenrod')

btna.grid(column=0, row=1)


az = PhotoImage(file=r"C:\Users\criss\Pictures\Saved Pictures\azul.png").subsample(3, 3)

btnaz = Button(ventana, width=100, height=100, image=az, borderwidth=5, command=lambda: clicked(4), activebackground='midnight blue')

btnaz.grid(column=1, row=1)


alto = PhotoImage(file=r"C:\Users\criss\Pictures\Saved Pictures\altooo.png").subsample(3, 3)

btnalto = Button(ventana, width=100, height=100, image=alto, borderwidth=5, command=lambda: clicked(5), activebackground='indigo')

btnalto.grid(column=0, row=3)


# Botón Play

play = PhotoImage(file=r"C:\Users\criss\Pictures\Saved Pictures\play.png").subsample(3, 3)

btnplay = Button(ventana, width=100, height=100, image=play, borderwidth=5, command=lambda: clicked(6), activebackground='deep pink')

btnplay.grid(column=1, row=3)


#Botón Menú

menu = PhotoImage(file=r"C:\Users\criss\Pictures\Saved Pictures\menu.png").subsample(3, 3)

btnmenu = Button(ventana, width=100, height=100, image=menu, borderwidth=5, command=lambda: clicked(7), activebackground='light coral')

btnmenu.grid(column=2, row=1)


ventana.mainloop()                                             # Iniciar bucle principal de la aplicación




Comentarios

Entradas populares de este blog

UNIDAD 4

Unidad 2

Unidad 3