¡Hola, Invitado!


Patrocinantes


Síguenos en Facebook


Síguenos en Twitter

Compartir este tema:
[Código] Rompecabezas
Sifaw En línea
Moderador Global
******

Mensajes: 350
Registro en: Jul 2010
MySpace YouTube
Gracias dados: 25
Gracias recibidos: 32
Mensaje: #1
Rompecabezas
  • Compartir en Delicious
  • Compartir en Digg
  • Compartir en Linkedin
  • Compartir en MySpace
  • Compartir en Technorati
  • Compartir en Tuenti
Este rompecabezas lo realicé por que un amigo, Slek, me dijo que lo hizo en VB y decidí hacer el mío en python ya que era un buen reto y este es el resultado final.

Licenciado bajo Crative Commons Reconocimiento-NoComercial-CompartirIgual 3.0

Para su uso tenemos dos método:
  • Pinchar con el ratón sobre la celda a la que queremos mover el vacío
  • Con las teclas arriba, abajo, izquierda o derecha indicar hacia donde queremos mover el vacío.

Les dejo un vídeo y a continuación del código:

Lenguaje PYTHON
#!/usr/bin/python
 
############################################################​#################
## Creado por: Fernando Gomez                                              ##
## Version: 1.0                                                            ##
## Fecha: 18/05/2011                                                       ##
## Licencia: Creative Commons Reconocimiento-NoComercial-CompartiIgual 3.0 ##
############################################################​#################
 
#Importamos los modulos necesarios
 
import wx, random, time
 
#Frame que contiene la interfaz
 
class Frame(wx.MiniFrame):
	def __init__ (self):
            wx.MiniFrame.__init__(self, None, -1, '', wx.DefaultPosition, (400, 400), (wx.DEFAULT_FRAME_STYLE)^(wx.RESIZE_BORDER|wx.MAXIMIZE_BOX))​
            posiciones = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", ""]
            self.inicio = 0
            self.interfaz(posiciones) #Mandamos iniciar la interfaz
            self.Center()
        def interfaz(self, posiciones): # Creamos la interfaz y colocamos cada elemento
            self.posiciones = posiciones
            self.panel = wx.Panel(self, wx.NewId(), wx.DefaultPosition, (400,400));
            self.sizer = wx.GridBagSizer(4, 5)
            self.uno = wx.Button(self.panel, -1, posiciones[0])
            self.dos = wx.Button(self.panel, -1, posiciones[1])
            self.tres = wx.Button(self.panel, -1, posiciones[2])
            self.cuatro = wx.Button(self.panel, -1, posiciones[3])
            self.cinco = wx.Button(self.panel, -1, posiciones[4])
            self.seis = wx.Button(self.panel, -1, posiciones[5])
            self.siete = wx.Button(self.panel, -1, posiciones[6])
            self.ocho = wx.Button(self.panel, -1, posiciones[7])
            self.nueve = wx.Button(self.panel, -1, posiciones[8])
            self.diez = wx.Button(self.panel, -1, posiciones[9])
            self.once = wx.Button(self.panel, -1, posiciones[10])
            self.doce = wx.Button(self.panel, -1, posiciones[11])
            self.trece = wx.Button(self.panel, -1, posiciones[12])
            self.catorce = wx.Button(self.panel, -1, posiciones[13])
            self.quince = wx.Button(self.panel, -1, posiciones[14])
            self.s = wx.Button(self.panel, -1, "S")
            self.vacio =  wx.Button(self.panel, -1, posiciones[15])
            self.hecho = wx.StaticText(self.panel, -1)
            self.tiempo = wx.StaticText(self.panel, -1)
            self.libre=""
            self.sizer.Add(self.uno,(0,0))
            self.sizer.Add(self.dos,(0,1))
            self.sizer.Add(self.tres,(0,2))
            self.sizer.Add(self.cuatro,(0,3))
            self.sizer.Add(self.s,(0,4))
            self.sizer.Add(self.cinco,(1,0))
            self.sizer.Add(self.seis,(1,1))
            self.sizer.Add(self.siete,(1,2))
            self.sizer.Add(self.ocho,(1,3))
            self.sizer.Add(self.hecho,(1,4))
            self.sizer.Add(self.nueve,(2,0))
            self.sizer.Add(self.diez,(2,1))
            self.sizer.Add(self.once,(2,2))
            self.sizer.Add(self.doce,(2,3))
            self.sizer.Add(self.tiempo,(2,4))
            self.sizer.Add(self.trece,(3,0))
            self.sizer.Add(self.catorce,(3,1))
            self.sizer.Add(self.quince,(3,2))
            self.sizer.Add(self.vacio,(3,3))
            self.panel.SetSizerAndFit(self.sizer)
            self.SetClientSize(self.panel.GetSize())
 
            self.Bind(wx.EVT_BUTTON, self.moverCelda, self.uno)
            self.Bind(wx.EVT_BUTTON, self.moverCelda, self.dos)
            self.Bind(wx.EVT_BUTTON, self.moverCelda, self.tres)
            self.Bind(wx.EVT_BUTTON, self.moverCelda, self.cuatro)
            self.Bind(wx.EVT_BUTTON, self.moverCelda, self.cinco)
            self.Bind(wx.EVT_BUTTON, self.moverCelda, self.seis)
            self.Bind(wx.EVT_BUTTON, self.moverCelda, self.siete)
            self.Bind(wx.EVT_BUTTON, self.moverCelda, self.ocho)
            self.Bind(wx.EVT_BUTTON, self.moverCelda, self.nueve)
            self.Bind(wx.EVT_BUTTON, self.moverCelda, self.diez)
            self.Bind(wx.EVT_BUTTON, self.moverCelda, self.once)
            self.Bind(wx.EVT_BUTTON, self.moverCelda, self.doce)
            self.Bind(wx.EVT_BUTTON, self.moverCelda, self.trece)
            self.Bind(wx.EVT_BUTTON, self.moverCelda, self.catorce)
            self.Bind(wx.EVT_BUTTON, self.moverCelda, self.quince)
            self.Bind(wx.EVT_BUTTON, self.remover, self.s)
            self.Bind(wx.EVT_BUTTON, self.moverCelda, self.vacio)
            self.Bind(wx.EVT_KEY_DOWN, self.moverVacio)
        #Mover celda cuando pulsamos sobre un boton
        def moverCelda(self, evt):
            btn = evt.GetEventObject()
            btnPos = self.sizer.GetItemPosition(btn)
            posiciones = self.posiciones
            label = btn.GetLabel()
            lugVacio = 0
            lugPulsado = 0
            while posiciones[lugVacio] != "":
                lugVacio += 1
            while posiciones[lugPulsado] != label:
                lugPulsado += 1
            if (lugVacio-lugPulsado == 1) or (lugVacio-lugPulsado == -1) or (lugVacio-lugPulsado == 4) or (lugVacio-lugPulsado == -4):
                posiciones[lugPulsado] = ""
                posiciones[lugVacio] = label
            self.panel.Destroy()
            self.interfaz(posiciones)
            if posiciones == ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", ""]:
               	self.hecho.SetLabel("Bravo!")
                self.tiempo.SetLabel("%is"%(time.time()-self.inicio))
        #Mover celda cuando usamos el raton
        def moverVacio(self, event):
            posiciones = self.posiciones
            lugVacio = 0
            while posiciones[lugVacio] != "":
                lugVacio += 1
            if event.GetKeyCode()==314:
                if (((lugVacio-1)!=11) and ((lugVacio-1)!=7) and ((lugVacio-1)!=3) and ((lugVacio-1)!=-1)):
                    posiciones[lugVacio] = posiciones[lugVacio-1]
                    posiciones[lugVacio-1] = ""
            elif event.GetKeyCode()==315:
                if lugVacio-4 >= 0:
                    posiciones[lugVacio] = posiciones[lugVacio-4]
                    posiciones[lugVacio-4] = ""
            elif event.GetKeyCode()==316:
                if (((lugVacio+1)!=16) and ((lugVacio+1)!=12) and ((lugVacio+1)!=8) and ((lugVacio+1)!=4)):
                    posiciones[lugVacio] = posiciones[lugVacio+1]
                    posiciones[lugVacio+1] = ""
            elif event.GetKeyCode()==317:
                if lugVacio+4 <= 15:
                    posiciones[lugVacio] = posiciones[lugVacio+4]
                    posiciones[lugVacio+4] = ""
            self.panel.Destroy()
            self.interfaz(posiciones)
            if posiciones == ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", ""]:
                self.hecho.SetLabel("Bravo!")
                self.tiempo.SetLabel("%is"%(time.time()-self.inicio))
        #Remover todos los elementos y obtener el rompecabeza
        def remover(self, evt):
            moves = 0
            posiciones = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", ""]
            lugar = 15
            while moves < 1000:
                hacia = random.randrange(0, 4)
                if hacia == 0:
                    if lugar > 4:
                        posiciones[lugar] = posiciones[lugar-4]
                        posiciones[lugar-4] = ""
                        lugar -= 4
                elif hacia == 1:
                    if (lugar != 0) and (lugar != 4) and (lugar != 8) and (lugar != 12):
                        posiciones[lugar] = posiciones[lugar-1]
                        posiciones[lugar-1] = ""
                        lugar -= 1
                elif hacia == 2:
                    if lugar < 11:
                        posiciones[lugar] = posiciones[lugar+4]
                        posiciones[lugar+4] = ""
                        lugar += 4
                else:
                    if (lugar != 3) and (lugar != 7) and (lugar != 11) and (lugar != 15):
                        posiciones[lugar] = posiciones[lugar+1]
                        posiciones[lugar+1] = ""
                        lugar += 1
                moves += 1
            self.inicio = time.time()
            self.panel.Destroy()
            self.interfaz(posiciones)
 
#mostramos el frame que contiene la interfaz
 
class App(wx.App):
	def OnInit(self):
		frame = Frame()
		frame.Show()
		self.SetTopWindow(frame)
		return True
 
#Iniciamos si no hay errores
 
if __name__ == '__main__':
    app = App()
    app.MainLoop()

[Imagen: moderadorglobal.png]
22-05-2011 12:57 AM
Buscar Citar
pablomi Sin conexión
Moderador
*****

Mensajes: 208
Registro en: Aug 2010
Gracias dados: 9
Gracias recibidos: 14
Mensaje: #2
RE: Rompecabezas
  • Compartir en Delicious
  • Compartir en Digg
  • Compartir en Linkedin
  • Compartir en MySpace
  • Compartir en Technorati
  • Compartir en Tuenti
Está guay, miraré el código cuando tenga más tiempo, a ver si hago yo uno en otro lenguaje :P

22-05-2011 01:00 AM
Buscar Citar
Sifaw En línea
Moderador Global
******

Mensajes: 350
Registro en: Jul 2010
MySpace YouTube
Gracias dados: 25
Gracias recibidos: 32
Mensaje: #3
RE: Rompecabezas
  • Compartir en Delicious
  • Compartir en Digg
  • Compartir en Linkedin
  • Compartir en MySpace
  • Compartir en Technorati
  • Compartir en Tuenti
(22-05-2011 01:00 AM)pablomi escribió:  Está guay, miraré el código cuando tenga más tiempo, a ver si hago yo uno en otro lenguaje :P

Cualquier duda me dices y te la resuelvo.

[Imagen: moderadorglobal.png]
22-05-2011 01:44 AM
Buscar Citar




Usuario(s) navegando en este tema: 1 invitado(s)