我真的可以帮助理解我在2d列表理解方面出错了。我已经花了几个小时和更精细的点,为什么它没有工作继续逃避我。
以下代码是一个非常基本的Lights out game,它接受输入
runGenerations2d([0,1,1,0],[1,0,1,0],[1,0,1,0])
设置游戏板N x N
单击需要更改单击框的值。
我相信问题是 setNewElement
正在使用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.
答案 0 :(得分:1)
setNewElement2d
返回一个数字,但调用代码需要两个数字。
这一行
return [ setNewElement2d( L, i,x,y ) for i in range(N) ]
将i设置为0,然后设置为1,然后设置为2,...则设置为N-1。这些是单个数字。
然后将这一行中的单个数字与两个数字进行比较:
if i == (x,y):
你似乎假设我是一对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