python - Stuck in a stupid phase of coding game of life -
i've been trying code game of life own want learn python , thought practice , have finish except need pass variable method dont know how know seem dumb wait bit , see code not easy sound unless me
import random,time f=3 c=3 contador = 0 tablero = [] tablero_dibujado = [] class juego(object): def tablero(self): #create board in range(f): tablero.append([0]*c) tablero_dibujado.append([0]*c) def rellenar_tablero_random(self): #fill board random 0 , 1 in range(f): j in range(c): tablero[i][j] = random.randint(0,1) print(tablero) def rellenar_tablero_manual(self): #just fill board manually if want reason tablero[0][1] = 1 in range(2): tablero[1][i] = 1 print(tablero) def distancia_vecino(self,cell_f,cell_c): #measure distance possible neighbours distancia_vecino = [(-1,-1),(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1)] in range(8): string = distancia_vecino[i] comparar_string = str(string) x,y = comparar_string.split(",") x = str(x).replace(",","") y = str(y).replace(",","") x = x.replace("(","") y = y.replace(")","") y = y.replace(" ","") x = int(x) + cell_f y = int(y) + cell_c if x>=f or x<0: continue else: if y>=c or y<0: continue else: game.detectar_vecino(cell_f,cell_c,x,y) game.vida(cell_f,cell_c) def detectar_vecino(self, cell_f, cell_c, x, y): #check how many neighboards have vecinos = 0 if tablero[cell_f][cell_c] == 1: if tablero[cell_f][cell_c] == tablero[x][y]: vecinos+=1 else: if tablero[cell_f][cell_c] != tablero[x][y]: vecinos+=1 contador = contador + vecinos def iterar_tablero(self): #just iterate board check values in range(f): j in range(c): game.distancia_vecino(i,j) = input() #in order screen dont close after executing def vida(self, cell_f, cell_c): #check if alive , if should alive or dead print(contador) if tablero[cell_f][cell_c] == 1: if contador > 3 or contador < 2: tablero[cell_f][cell_c] = 0 else: if contador == 3: tablero[cell_f][cell_c] = 1 game.dibujar_tablero() def dibujar_tablero(self): #draw board in more way contador1 = 0 in range(f): j in range(c): if tablero[i][j] == 1: tablero_dibujado[i][j] = "§" else: tablero_dibujado[i][j] = "■" in tablero_dibujado: print(" ") j in i: print(j, end=" ") print("") time.sleep(2) game = juego() game.tablero() game.rellenar_tablero_manual() game.iterar_tablero() what need in detectar_vecino have neighbour of cell in board , problem doing got : local variable 'contador' referenced before assignment. , know why happen.however couldnt find alternative way of doing please if know how can solve it.
i want clarify isnt work anywhere,im doing own hobby , want finish thank time appreciate it
add line global contador below
def detectar_vecino(self, cell_f, cell_c, x, y): global contador # add line. vecinos = 0 if tablero[cell_f][cell_c] == 1: if tablero[cell_f][cell_c] == tablero[x][y]: vecinos+=1 else: if tablero[cell_f][cell_c] != tablero[x][y]: vecinos+=1 contador = contador + vecinos
Comments
Post a Comment