我真的需要一些帮助来理解我在二维列表理解中出错的地方。我花了几个小时,但我仍然无法弄清楚为什么它不起作用。
下面的代码是一个非常基本的Lights out game需要输入
runGenerations2d([0,1,1,0],[1,0,1,0],[1,0,1,0])
设置游戏板 N x N
通过单击,它需要更改被单击框的值。
我认为问题是 设置新元素
正在获取 x,y 数据,而我的其余函数不知道如何处理传递的值
import time # provides time.sleep(0.5)
from csplot import choice
from random import * # provides choice( [0,1] ), etc.
import sys # larger recursive stack
sys.setrecursionlimit(100000) # 100,000 deep
def runGenerations2d(L , x = 0,y=0):
show(L)
print( L ) # display the list, L
time.sleep(.1) # pause a bit
newL = evolve2d( L ) # evolve L into newL
print(newL)
if min(L) == 1:
#I like read outs to be explained so I added an extra print command.
if x<=1: # Takes into account the possibility of a 1 click completition.
print ('BaseCase Reached!... it took %i click to complete' % (x))
print (x)
done()#removes the need to input done() into the shell
else:
print ('BaseCase Reached!... it took %i clicks to complete' % (x))
print (x)
done()#removes the need to input done() into the shell
return
x = x+1 # add 1 to x before every recusion
runGenerations2d( newL , x,y ) # recurse
def evolve2d( L ):
N = len(L) # N now holds the size of the list L
x,y = sqinput2() # Get 2D mouse input from the user
print(x,y) #confirm the location clicked
return [ setNewElement2d( L, i,x,y ) for i in range(N) ]
def setNewElement2d( L, i, x=0,y=0 ):
if i == (x,y): # if it's the user's chosen column,
if L[i]==1: # if the cell is already one
return L[i]-1 # make it 0
else: # else the cell must be 0
return L[i]+1 # so make it 1
点击后出现错误
[None, None, None, None]
[None, None, None, None]
The data does not seem 2d.
Try using sqinput instead.
setNewElement2d
返回单个数字,但调用代码需要两个数字。
这一行
return [ setNewElement2d( L, i,x,y ) for i in range(N) ]
将 i 设置为 0,然后为 1,然后为 2,...然后为 N-1。这些是单个数字。
然后将单个数字与该行上的两个数字进行比较:
if i == (x,y):
您似乎假设 i 是 x,y 对,但事实并非如此。
以下是如何为 3x3 网格创建每个 x-y 对:
# Makes (0,0),(0,1)...(2,2)
[(x,y) for x in range(3) for y in range(3)]
我认为这段代码更接近您想要的,但仍然可能需要更改:
def evolve2d( L ):
N = len(L)
x,y = sqinput2()
print(x,y)
return [setNewElement2d(L, xx, yy, x, y) for xx in range(N) for yy in range(N)]
def setNewElement2d( L, xx, yy, x=0,y=0 ):
if (xx,yy) == (x,y): # if it's the user's chosen row and column
# If it's already 1 return 0 else return 1
return 0 if L[xx][yy]==1 else 1
我是一名优秀的程序员,十分优秀!