在Gam上创建灯光

2024-10-02 20:42:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个名为Lights on的游戏编写代码,这个游戏的想法是产生一个由随机点亮的方块组成的棋盘,并且要赢得所有方块都必须点亮(1为开0为关)。单击一个正方形可反转该正方形及其上、下、左或右与其相邻的任何正方形。但是,我有困难,在使用我的代码正确地反转董事会

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)  
    x,y = sqinput2()
    return [[ setNewElement2d( L, i, j,x,y ) for i in range(N)]for j in range(N) ]

def setNewElement2d( L, i, j, x=0, y=0 ):
    if y==j and (i == x-1 or i == x+1 or i ==x):
        return 1-L[i][j] 
    elif x==i and (j == y-1 or j == y+1):  
        return 1-L[i][j] 
    else:
        return L[i][j] 

我相信问题出在我的setNewElement2d函数上,但我似乎无法解决它。在


Tags: orthetoimport游戏returniftime
1条回答
网友
1楼 · 发布于 2024-10-02 20:42:05

简而言之:您已经在evolve2d()中交换了i和j。在

长回答:当evolve2d()创建新矩阵时,i需要在外循环中,而不是在内循环中。否则,交换i和{}。例如,如果我将调用更改为

return [[ setNewElement( L, j, i, x, y ) for i in range(N) ] for j in range(N) ]

然后我得到了你的例子的正确答案。在

这与二维数组的组织有关。在Python中,L[i][j]查找第i行(垂直倒计时)和jth列(水平计数右)。但是您希望ix值进行比较,在您的心目中该值是水平的。所以你要测试的点的坐标和你想测试的点的坐标互换了。在

最后一次编辑,我发誓:基本上,程序做了它应该做的。但是当你看到它时,你想象x和{}在数组中有相反的含义时,它们具有传统意义(分别是水平和垂直):L[x][y]向下看x行和y列。在

相关问题 更多 >