我一直在尝试自己编写生命游戏,因为我想学习python,我认为这可能是一个很好的练习,我刚刚完成,除了我需要将一个变量传递给另一个方法,但我真的不知道我怎么知道这看起来很愚蠢 但等一下,看看代码并不那么容易,除非对我而言
import random,time
f=3
c=3
contador = 0
tablero = []
tablero_dibujado = []
class juego(object):
def tablero(self): #Create the Board
for i in range(f):
tablero.append([0]*c)
tablero_dibujado.append([0]*c)
def rellenar_tablero_random(self): #Fill the board with random 0 and 1
for i in range(f):
for j in range(c):
tablero[i][j] = random.randint(0,1)
print(tablero)
def rellenar_tablero_manual(self): #Just to fill the board manually if I want for some reason
tablero[0][1] = 1
for i in range(2):
tablero[1][i] = 1
print(tablero)
def distancia_vecino(self,cell_f,cell_c): #Measure Distance for possible neighbours
distancia_vecino = [(-1,-1),(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1)]
for i 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 do I 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 to iterate all the board to check the values
for i in range(f):
for j in range(c):
game.distancia_vecino(i,j)
a = input() #In order to the screen dont close after executing it
def vida(self, cell_f, cell_c): #Check if they are alive and if they should be 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 the board in a more clearly way
contador1 = 0
for i in range(f):
for j in range(c):
if tablero[i][j] == 1:
tablero_dibujado[i][j] = "§"
else:
tablero_dibujado[i][j] = "■"
for i in tablero_dibujado:
print(" ")
for j in i:
print(j, end=" ")
print("")
time.sleep(2)
game = juego()
game.tablero()
game.rellenar_tablero_manual()
game.iterar_tablero()
我需要的是,在detectar_vecino中必须得到一个单元格的所有邻居,问题在于我得到了:在赋值之前引用了局部变量'contador'。而且我知道它为什么会发生。但是我无法找到任何替代方法,所以如果有人知道我该如何解决它。
我只是想澄清一下,这不是任何地方的任何工作,我只是作为一个业余爱好这样做,我只想完成感谢你的时间我很感激
答案 0 :(得分:0)
如下所示添加此行global contador
def detectar_vecino(self, cell_f, cell_c, x, y):
global contador # Add this 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