Challenge solution of the 8 queens in python

3

What the challenge is:
Hello people, I do not know if you know the challenge of the 8 queens. If you do not know it, I'll explain it to you shortly. We have a chess board like any other and you have to place 8 queens on the board without being attacked. If you want to see more about what this challenge is about, here is a link: link

Well what I wanted to do was a program that will give a solution to this problem. I already have the code but I got an error on line 58:

Error:

Traceback (most recent call last):
  File "main.py", line 148, in <module>
    while(solucionado()):
  File "main.py", line 56, in solucionado
    if(tablero[i][j].getReina() != False):
AttributeError: 'NoneType' object has no attribute 'getReina'

A summary of what the program does:
What the program does is create a class box that will contain the Boolean variable 'affected' that indicates whether the box is threatened by a queen or not, another Boolean variable called 'queen' that indicates if there is a queen in the object ' box 'that contains it. Then check box by box looking if it is not affected by a queen and if it has not contained a queen, to be able to put one. When you put one, it affects (change the 'affected' value of the box object to 'True') all the boxes that are involved with that box that contains the queen so that in those boxes you can not put a queen. Well, you know, well, until all the queens are there. Ah! Well one thing, if the number of free squares is less than the number of queens that are missing, it means that the queens structure that is now on the board is wrong, so what it does is affect (change the 'affected' value of the object box to 'True') the first box with a queen that has that structure and then reset all the boxes to the default values: 'False', except for the box already explained (the first box containing a queen in the previous structure of queens) previously so that the following queens structure that is placed is not equal to the previous one and so it can go testing all the cases until finding the solution. If you did not understand it, study my code a bit more so you can understand it a little better. Greetings!

Source code:

class Casilla_: #Cada casilla del tablero de ajedrez 
    afectado = False #Afectacion de la casilla por otra casillas
    reina = False #Si la casilla tiene reina o no
    def __init__(self,afectado = False,reina = False): 
        self.afectado = afectado 
        self.reina = reina

    def setAfectado(self,afectado): 
        self.afectado = afectado

    def getAfectado(self): 
        return self.afectado
    def setReina(self,reina):
        self.reina = reina
    def getReina(self): 
        return self.reina

tablero = [] #Creacion de la matriz
for i in range(0,8):
    tablero.append([None])
    for j in range(0,8):
        tablero[i].append(None)

#Inicializacion de objetos casillas
def reinicializacionTablero():
    global tablero 
    for i in range(0,len(tablero)):
        for j in range(0,len(tablero)):
            tablero[i][j] = Casilla_(False,False) 
def casillasLibres():
    libres = 0
    for i in range(len(tablero)):
       for i in range(len(tablero)):
           #Casilla vacia
           if(tablero[i][j].afectado == False and tablero[i][j].reina 
           == False):
             libres += 1 
    return libres #Retorna el numero de casillas libres             
def primeraReina():
    pos = ""
    for i in range(8):
        for j in range(8):
            if(tablero[i][j].getReina()):
                pos = str(i) + str(j)
                return pos
def solucionado():
    num_reinas = 0
    for i in range(8):
        for j in range(8):
            if(tablero[i][j].getReina() != False):
                num_reinas +=1
    if(num_reinas == 8):
        return False
    else:
        return True             

reinas = 8
primerPos = ""

def afectarCasillas(row,column):
    b = False
    referenceRow = 0; referenceColumn = 0 
    #up (afect)
    referenceRow = row; referenceColumn = column
    while(b == False):
        referenceRow -=1 #Se decrementa los indices
        try: 
            tablero[referenceRow][referenceColumn].afectado = True
        except IndexError as e:
            b = True
            break
    b = False       
    #down (afect)
    referenceRow = row; referenceColumn = column 
    while(b == False):
        referenceRow -=1 #Se decrementa los indices
        try: 
            tablero[referenceRow][referenceColumn].afectado = True
        except IndexError as e:
           b = True
           break    
    b = False
    #left (afect)
    referenceRow = row; referenceColumn = column 
    while(b == False):
         referenceColumn -= 1 #Se decrementa los indices
        try: 
            tablero[referenceRow][referenceColumn].afectado = True
        except IndexError as e:
            b = True
            break   
    b = False
    #rigth (afect)
    referenceRow = row;#Asignacion de los indices
    while(b == False):
        referenceColumn += 1 #Se decrementa las los indices
        try: 
            tablero[referenceRow][referenceColumn].afectado = True
        except IndexError as e:
            b = True
            break
        b = False
        #up-left (afect)
        referenceRow = row; referenceColumn = column 
        while(b == False):
             referenceRow -=1; referenceColumn -= 1 
             try: 
                 tablero[referenceRow][referenceColumn].afectado=True
             except IndexError as e:
                 b = True   
        b = False
        #up-rigth (afect)
        referenceRow = row; referenceColumn = column 
    while(b == False):
        referenceRow +=1; referenceColumn += 1 
        try: 
            tablero[referenceRow][referenceColumn].afectado = True
        except IndexError as e:
            b = True
            break
    b = False
    #down-left (afect)
    referenceRow = row; referenceColumn = column 
    while(b == False):
        referenceRow +=1; referenceColumn -= 1 
        try: 
            tablero[referenceRow][referenceColumn].afectado = True
        except IndexError as e:
            b = True    
            break
    b = False
    #down-rigth (afect)
    referenceRow = row; referenceColumn = column 
    while(b == False):
        referenceRow +=1; referenceColumn += 1 
        try: 
            tablero[referenceRow][referenceColumn].afectado = True
        except IndexError as e:
            b = True    
            break                               
 #Bucle principal
 while(solucionado()):
     num_libres = casillasLibres() #Asigna a num_libres el numero de 
     casillas vacias que hay en el tablero
     bel = 't'
     while(reinas > 0): 
         for i in range(8):
            for j in range(8):
                #Caso de casilla libre
                if(tablero[i][j].getAfectado()==False and tablero[i] 
                [j].getReina()==False):
                    tablero[i][j].setReina(True) 
                    afectarCasillas(i,j) #Afecta todas las casillas relacionadas con la casilla actual
                    reinas -= 1 
                else:
                    num_libres = casillasLibres() 
                    if(num_libres > reinas):
                        bel = 'f'
                        primerPos = primeraReina() 
                        break               
            if(bel == 'f'):
                break
        if(bel == 'f'):
            break   
    if(bel == 'f'):
        reinicializacionTablero()
        fil = int(primerPos[0])
        col = int(primerPos[1])
        tablero[fil][col].setAfectado(True);
        reinas = 8
    else:
        continue    
def imprimiendoSolucion():
    print("SOLUCION: ")
    for i in range(0,8):
        for j in range(0,8):
            if(tablero[i][j].getReina()):
                print(" [R] ",end="")
            else:
                print(" [ ] ",end="")
        print(""); print("")            
imprimiendoSolucion() #Imprime toda la solcion de la matriz
    
asked by Walk Rock 09.06.2018 в 05:13
source

0 answers