class MusicaSpec(unittest.TestCase): def setUp(self): self.eu = Pessoa() self.gato = Gato() self.dona_chica = Pessoa() def spec_atirei_o_pau_no_gato_mas_o_gato_nao_morreu(self): self.eu.atirar_o_pau_no(self.gato) self.gato.esta_vivo() |should| be(True) def spec_dona_chica_adimirar_se_com_o_berro_que_o_gato_deu(self): self.eu.atirar_o_pau_no(self.gato) self.gato.berrou() |should| be(True) self.dona_chica.adimirar_se(self.gato) |should| be(True)
def start(self): self.b['text'] = "Reiniciar" self.txt.grid(column=0, row=0) self.txt2.grid(column=0, row=1) self.player1 = Player(self.txt.get(), "X") self.player2 = Player(self.txt2.get(), "O") self.juego = Gato(self.player1, self.player2) self.btn = [["-" for x in range(3)] for x in range(3)] self.text = [["-" for x in range(3)] for x in range(3)] list = [self.player1, self.player2] self.currentPlayer = random.choice(list) i =0 j=0 for x in self.btn: for y in x: self.btn[i][j] = Button(self.frame, text= "".format(i,j), font=('Times 20 bold'), bg="gray", fg="white", height=4, width=8, command= lambda x1=i, y1=j : self.click(x1,y1) ) self.btn[i][j].grid(column=j, row=i) j+=1 j=0 i+=1 messagebox.showinfo("Jugador elegido al azar", "El jugador : \n{} comienza".format(self.currentPlayer.name))
class main(root): def __init__(self): root.__init__(self) def start(self): self.b['text'] = "Reiniciar" self.txt.grid(column=0, row=0) self.txt2.grid(column=0, row=1) self.player1 = Player(self.txt.get(), "X") self.player2 = Player(self.txt2.get(), "O") self.juego = Gato(self.player1, self.player2) self.btn = [["-" for x in range(3)] for x in range(3)] self.text = [["-" for x in range(3)] for x in range(3)] list = [self.player1, self.player2] self.currentPlayer = random.choice(list) i =0 j=0 for x in self.btn: for y in x: self.btn[i][j] = Button(self.frame, text= "".format(i,j), font=('Times 20 bold'), bg="gray", fg="white", height=4, width=8, command= lambda x1=i, y1=j : self.click(x1,y1) ) self.btn[i][j].grid(column=j, row=i) j+=1 j=0 i+=1 messagebox.showinfo("Jugador elegido al azar", "El jugador : \n{} comienza".format(self.currentPlayer.name)) def click(self, x,y): self.btn[x][y]['text'] = self.currentPlayer.symbol self.text[x][y] = self.currentPlayer.symbol self.btn[x][y]['state'] = 'disabled' self.btn[x][y]['disabledforeground'] = 'white' if self.juego.checkIfPlayerWon( self.text, self.currentPlayer): res = messagebox.askyesno("Tenemos un ganador", "El jugador {} gano \n ¿Quieres jugar de nuevo?".format(self.currentPlayer.name)) if res: self.start() else: self.window.quit() elif self.currentPlayer == self.player1: self.currentPlayer = self.player2 elif self.currentPlayer == self.player2: self.currentPlayer = self.player1
def __init__(self): self.window = Tk() self.window.title("Juego del gato") self.frame = Frame(self.window) self.frame.grid(row=3, column=0) self.lbl = Label(self.window, text="Player 1: X") self.lbl2 = Label(self.window, text="Player 2: O") self.txt = Entry(self.window, width=15, state='normal') self.txt2 = Entry(self.window, width=15, state='normal') self.lbl.grid(sticky="W", column=0 ,row=0) self.lbl2.grid(sticky="W",column=0 ,row=1) self.txt.grid(column=1, row=0) self.txt2.grid(column=1, row=1) self.b = Button(self.window, text="Comenzar", command=self.start) self.b.grid(column=0, row=2) self.player1 = Player("","") self.player2 = Player("","") self.juego = Gato(self.player1, self.player2) self.currentPlayer = "" self.btn = "" self.text = "" self.window.mainloop()
def main(): g = Gato() g.mover() g.comer()
class Sala(): #Atributo que representa um cenario do objeto Sala __cenario = [] #Atributo que representa um objeto Rato padrao para facilitar a inicializacao do cenario __rato_default = Rato(0, 0, 0, "", TipoElemento.Rato.value, "rato") # Atributo que representa um objeto Gato padrao para facilitar a inicializacao do cenario __gato_default = Gato("", TipoElemento.Gato.value, 0, "") # Atributo que representa um objeto Queijo padrao para facilitar a inicializacao do cenario __queijo_default = TipoElemento.Queijo.value def __init__(self, cenario=None): if cenario is None: cenario = [] self.__cenario = cenario @property def cenario(self): return self.__cenario @cenario.setter def cenario(self, cenario): self.__cenario = cenario @cenario.deleter def cenario(self): del self.__cenario @property def rato(self): return self.__rato_default @rato.setter def rato(self, rato): self.__rato_default = rato @rato.deleter def rato(self): del self.__rato_default @property def gato(self): return self.__gato_default @gato.setter def gato(self, gato): self.__gato_default = gato @gato.deleter def gato(self): del self.__gato_default @property def queijo(self): return self.__queijo_default @queijo.setter def queijo(self, queijo): self.__queijo_default = queijo @queijo.deleter def queijo(self): del self.__queijo_default #Inicializa um cenario preenchido com elementos Espaco_Vazio e posicoes todos os personagens e objetos #do cenario def inicializar(self, arquivo): #aqui o arquivo e' lido e todas as instrucoes sao executadas na criacao de um cenario with open(arquivo, "r") as file: lista_de_instrucoes = file.readlines() n = int(lista_de_instrucoes[0]) numero_obstaculos = int(lista_de_instrucoes[2]) for i in range(n): self.__cenario.append([]) for i in self.__cenario: for j in range(int(lista_de_instrucoes[0])): i.append(TipoElemento.Espaco_Vazio.value) self.__cenario[int(lista_de_instrucoes[1][0])][int( lista_de_instrucoes[1][2])] = self.gato.tipo_elemento for i in range(0, numero_obstaculos): if lista_de_instrucoes[i + 3][4] is 'R': self.__cenario[int(lista_de_instrucoes[i + 3][0])][int( lista_de_instrucoes[i + 3][2])] = Obstaculo( "multilaser", Eresistencia.resistente) else: self.__cenario[int(lista_de_instrucoes[i + 3][0])][int( lista_de_instrucoes[i + 3][2])] = Obstaculo( "ibyte", Eresistencia.fragil) self.__cenario[0][0] = self.rato.tipo_elemento self.__cenario[n - 1][n - 1] = self.queijo #Esse metodo apaga os elementos Espaco_Vazio, da direita para a esquerda, ate encontrar qualquer objeto que nao seja #um Espaco_Vazio def vizualizar_cenario(self): matrix_dinamica = [i for i in self.__cenario] print( "\n#=====================================================================================================#" ) for i in matrix_dinamica: count = 0 for j in i[::-1]: if j is TipoElemento.Espaco_Vazio.value: i.pop() count += 1 else: break print(i) for k in range(0, count): i.append(TipoElemento.Espaco_Vazio.value) print( "#=====================================================================================================#" )
import random import time import tkinter from gato import Gato from ponto import Ponto tk = tkinter.Tk() canvas = tkinter.Canvas(tk, width=800, height=800) canvas.pack() gatos = [Gato(canvas, random.randint(0, 800), random.randint(0, 800))] ultimoClick = Ponto(0, 0) #Função de callback para quando clicar com o Mouse def callback(event): ultimoClick.x = event.x ultimoClick.y = event.y canvas.bind("<Button-1>", callback) ultimoTempo = time.time() while 1: diffTime = int((time.time() - ultimoTempo) * 500) ultimoTempo = time.time() for gato in gatos: gato.update(canvas, diffTime / 1000, ultimoClick) tk.update() time.sleep(0.03)
self.socket.listen(10) def aceptar(self): cont = 0 client, address = self.socket.accept() print("Obtuvimos una conexión desde %s" % str(address)) for i in range(10): data = client.recv(1024) data = data.decode('ascii') print("El jugador O jugo su ficha en {}".format(data)) client.close() if __name__ == "__main__": gato = Gato() pick = input("Ingrese X si quiere ser servidor o O si desea ser cliente: ") if pick == "X": server = Servidor(gato) #server.aceptar() escuchador = threading.Thread(target=server.aceptar) escuchador.daemon = True escuchador.start() while True: mensaje = input( "Jugador {0} debe ingresar la posicion en que desea jugar". format(server.gato.turno)) server.enviar(mensaje) elif pick == "O": client = Cliente(gato)
def spec_o_gato_esta_vivo_ou_nao(self): gato = Gato() gato.esta_vivo() |should| be(True)
import time import tkinter import math from gato import Gato from ponto import Ponto from casa import Casa from rato import Rato #------------------------------------------------------------------------ tk = tkinter.Tk() canvas = tkinter.Canvas(tk, width=800, height=800) canvas.pack() gato = Gato(canvas, random.randint(0, 800), random.randint(0, 800)) ratos = [ Rato(canvas, random.randint(0, 800), random.randint(0, 800)), Rato(canvas, random.randint(0, 800), random.randint(0, 800)), Rato(canvas, random.randint(0, 800), random.randint(0, 800)), Rato(canvas, random.randint(0, 800), random.randint(0, 800)), Rato(canvas, random.randint(0, 800), random.randint(0, 800)), Rato(canvas, random.randint(0, 800), random.randint(0, 800)) ] casas = [] continua = True ultimoClick = Ponto(0, 0)
from perro import Perro from gato import Gato perroChihuahua = Perro("Fido", "Chihuahua") perroChihuahua.imprimirInfo() gatoGris = Gato("Miau", "Mestizo") gatoGris.imprimirInfo()
def mascotas(): #guardado de la ruta dl archivo de mascotas path = input("\nIngrese la ruta del archivo: ") #vaciado del arreglo de mascotas y el contenido del archivo de salida mascotas = [] mascotas_result = " " #validando que la extension del archivo sea la correcta while True: nombre,extension = os.path.splitext(path) if extension == ".mascotas": break else: path = input("\nIngrese la ruta del archivo: ") #apertura y lectura del contenido del archivo de las instrucciones archivo_mascotas = open(path,"r") contenido = archivo_mascotas.read() #division del archivo en lineas division = contenido.split("\n") #recorrido de las lineas del archivo for linea in division: #division del archivo en tipo de instruccion(0) y contenido(1) instruccion = linea.split(":") fecha = datetime.datetime.now() if instruccion[0] == "Crear_Pajaro": #eliminacion del "" en el nombre de la mascota nombre = instruccion[1].strip('"') #creacion del objeto p1 = Pajaro(nombre,1,True,0,0) #agregando el objeto creado al arreglo mascotas.append(p1) #generacion del reporte if mascotas_result != " ": mascotas_result = mascotas_result + "[%s/%s/%s"%(fecha.day,fecha.month,fecha.year) + " %s:%s"%(fecha.hour,fecha.minute)+"] Se creo el pajaro " + nombre +"\n" else: mascotas_result = "[%s/%s/%s"%(fecha.day,fecha.month,fecha.year) + " %s:%s"%(fecha.hour,fecha.minute)+"] Se creo el pajaro " + nombre + "\n" elif instruccion[0] == "Puede_Entregar_Mensaje": ar1 = instruccion[1].split(",") nick = ar1[0].strip('"') for animal in mascotas: #validando el tipo de objeto que se encuentra en el arreglo if type(animal) == Pajaro: if animal.nombre == nick: if mascotas_result != " ": mascotas_result = mascotas_result + animal.validarMensaje( int(ar1[1]) , int(ar1[2])) + "\n" else: mascotas_result = animal.validarMensaje( int(ar1[1]) , int(ar1[2])) + "\n" elif instruccion[0] == "Enviar_Mensaje": ar1 = instruccion[1].split(",") nick = ar1[0].strip('"') for animal in mascotas: if type(animal) == Pajaro: if animal.nombre == nick: if mascotas_result != " ": mascotas_result = mascotas_result + animal.enviarMensaje( int(ar1[1]) , int(ar1[2])) + "\n" else: mascotas_result = animal.enviarMensaje( int(ar1[1]) , int(ar1[2])) + "\n" elif instruccion[0] == "Crear_Gato": nombre = instruccion[1].strip('"') g1 = Gato(nombre,1,True,0,0) mascotas.append(g1) if mascotas_result != " ": mascotas_result = mascotas_result + "[%s/%s/%s"%(fecha.day,fecha.month,fecha.year) + " %s:%s"%(fecha.hour,fecha.minute)+"] Se creo el gato " + nombre +"\n" else: mascotas_result = "[%s/%s/%s"%(fecha.day,fecha.month,fecha.year) + " %s:%s"%(fecha.hour,fecha.minute)+"] Se creo el gato " + nombre + "\n" elif instruccion[0] == "Conviene_Comer_Raton": ar1 = instruccion[1].split(",") nick = ar1[0].strip('"') for animal in mascotas: if type(animal) == Gato: if animal.nombre == nick: if mascotas_result != " ": mascotas_result = mascotas_result + animal.validarComerRaton( int(ar1[1]) , int(ar1[2]) , int(ar1[3]) ) + "\n" else: mascotas_result = animal.validarComerRaton( int(ar1[1]) , int(ar1[2]) , int(ar1[3]) ) + "\n" elif instruccion[0] == "Enviar_Comer_Raton": ar1 = instruccion[1].split(",") nick = ar1[0].strip('"') for animal in mascotas: if type(animal) == Gato: if animal.nombre == nick: if mascotas_result != " ": mascotas_result = mascotas_result + animal.cazarRaton( int(ar1[1]) , int(ar1[2]) , int(ar1[3]) ) + "\n" else: mascotas_result = animal.cazarRaton( int(ar1[1]) , int(ar1[2]) , int(ar1[3]) ) + "\n" elif instruccion[0] == "Dar_de_Comer": ar1 = instruccion[1].split(",") nick = ar1[0].strip('"') for animal in mascotas: if animal.nombre == nick: if mascotas_result != " ": mascotas_result = mascotas_result + animal.comer(int(ar1[1])) + "\n" else: mascotas_result = mascotas_result + animal.comer(int(ar1[1])) + "\n" elif instruccion[0] == "Resumen_Mascota": ar1 = instruccion[1].split(",") nick = ar1[0].strip('"') for animal in mascotas: if animal.nombre == nick: if mascotas_result != " ": mascotas_result = mascotas_result + animal.resumen() + "\n" else: mascotas_result = mascotas_result + animal.resumen() + "\n" elif linea == "Resumen_Global": fecha = datetime.datetime.now() if mascotas_result != " ": mascotas_result = mascotas_result + "[%s/%s/%s"%(fecha.day,fecha.month,fecha.year) + " %s:%s"%(fecha.hour,fecha.minute)+"] " + "----------------- Resumen global -----------------\n" else: mascotas_result = "[%s/%s/%s"%(fecha.day,fecha.month,fecha.year) + " %s:%s"%(fecha.hour,fecha.minute)+"] " + "----------------- Resumen global -----------------" for animal in mascotas: if mascotas_result != " ": mascotas_result = mascotas_result + animal.resumen() + "\n" else: mascotas_result = mascotas_result + animal.F() + "\n" mascotas_result = mascotas_result + "[%s/%s/%s"%(fecha.day,fecha.month,fecha.year) + " %s:%s"%(fecha.hour,fecha.minute)+"] " + "--------------------------------------------------\n" #creacion e impresion del archivo.mascotas_result resultado = open("C:/Users/chepe/Desktop/archivo.mascotas_result","w") resultado.write(mascotas_result) resultado.close() os.system("C:/Users/chepe/Desktop/archivo.mascotas_result") menuPrincipal()
class Sala(): #Atributo que representa um cenario do objeto Sala __cenario = [] #Atributo que representa um objeto Rato padrao para facilitar a inicializacao do cenario __rato_default = Rato(0, 0, 0, "", TipoElemento.Rato.value) # Atributo que representa um objeto Gato padrao para facilitar a inicializacao do cenario __gato_default = Gato("", TipoElemento.Gato.value, 0, "") # Atributo que representa um objeto Queijo padrao para facilitar a inicializacao do cenario __queijo_default = TipoElemento.Queijo.value def __init__(self, cenario=None): if cenario is None: cenario = [] self.__cenario = cenario @property def cenario(self): return self.__cenario @cenario.setter def cenario(self, cenario): self.__cenario = cenario @cenario.deleter def cenario(self): del self.__cenario @property def rato(self): return self.__rato_default @rato.setter def rato(self, rato): self.__rato_default = rato @rato.deleter def rato(self): del self.__rato_default @property def gato(self): return self.__gato_default @gato.setter def gato(self, gato): self.__gato_default = gato @gato.deleter def gato(self): del self.__gato_default @property def queijo(self): return self.__queijo_default @queijo.setter def queijo(self, queijo): self.__queijo_default = queijo @queijo.deleter def quejo(self): del self.__queijo_default #Inicializa um cenario preenchido com elementos Espaco_Vazio e posicoes todos os personagens e objetos #do cenario def inicializar(self, n): for i in range(n): self.__cenario.append([]) for i in self.__cenario: for j in range(n): i.append(TipoElemento.Espaco_Vazio.value) posicoes = int(n / 2) k = 0 tup_list = [] #gera uma posicao randomica e faz uma lista de tuplas com coordenadas randomicas while k <= posicoes: l = randint(1, n - 2) m = randint(1, n - 2) tup = l, m if tup not in tup_list: tup_list.append(tup) k += 1 #Sem perda de generalidade, defino a ultima posicao da lista de tuplas como sendo a tupla de posicao do objeto #gato posicao_gato = tup_list[posicoes] del tup_list[posicoes] #monto o cenario for i in tup_list: self.__cenario[i[0]][i[1]] = TipoElemento.Obstaculo.value self.__cenario[0][0] = self.__rato_default.tipo_elemento self.__cenario[posicao_gato[0]][posicao_gato[1]] = self.__gato_default.tipo_elemento self.__cenario[n - 1][n - 1] = self.__queijo_default o = 0 #verifico se o numero de ebstaculos do cenario esta correto for i in self.__cenario: for j in i: if j is TipoElemento.Obstaculo.value: o += 1 if o < posicoes: self.inicializar(n) else: return #Esse metodo apaga os elementos Espaco_Vazio, da direita para a esquerda, ate encontrar qualquer objeto que nao seja #um Espaco_Vazio def vizualizar_cenario(self): matrix_dinamica = [i for i in self.__cenario] print( "\n#=====================================================================================================#") for i in matrix_dinamica: count = 0 for j in i[::-1]: if j is TipoElemento.Espaco_Vazio.value: i.pop() count += 1 else: break print(" ", '\t'.join(i)) for k in range(0, count): i.append(TipoElemento.Espaco_Vazio.value) print("#=====================================================================================================#")
from gato import Gato from movimento import Movimento from rato import Rato from tipo_elemento import TipoElemento from sala import Sala from queijo import Queijo import random sala = Sala() #depois de executar o modulo sala.inicializar("Entrada1.txt") sala.gato = Gato("Fly-Gone-Gin", TipoElemento.Gato.value, 15, "dormindo", 0) sala.rato = Rato(50, 0, 2000, "Toby One", TipoElemento.Rato.value, "memoria_do_rato.txt") sala.queijo = Queijo(200, "coalho", TipoElemento.Queijo.value) lista_movimento = [] lista_movimento.append(Movimento.up.value) lista_movimento.append(Movimento.down.value) lista_movimento.append(Movimento.left.value) lista_movimento.append(Movimento.right.value) #apaga a memoria do rato toda vez que o programa e' executado sala.rato.memoria = open("memoria_do_rato.txt", "w") sala.rato.memoria.write("") i = 0 while True: if sala.queijo.peso == 0 and sala.cenario[0][0] is sala.rato.tipo_elemento: break else:
from cachorro import Cachorro from gato import Gato cachorro = Cachorro('Tobby', 5, 8) gato = Gato('Lily', 2, 5) print(cachorro.dormir()) #print(cachorro.latir()) print(gato.dormir()) #print(gato.miar()) print(cachorro.fazBarulho()) print(gato.fazBarulho())
def spec_gato_berra_se_for_atingido_por_um_pau(self): gato = Gato() gato.atingido("pau") gato.berrou() |should| be(True)
def setUp(self): self.eu = Pessoa() self.gato = Gato() self.dona_chica = Pessoa()
from gato import Gato from raton import Raton michi = Gato() mickey = Raton() print("El michi tiene", michi.anios, "anios") print("El raton tiene", mickey.anios, "anios")