2012-02-14 35 views
2

所以我试图编写一个代码来确定在一个电路板上放置哪些形状,并且如果电路板上已经有一些小块,它们会知道它们是否重叠。我需要Python中的帮助来检查列表的边界

所以我现在有的代码,需要用户输入来获得董事会的长度和。

然后假设用户知道电路板的大小,它会提示您输入电路板上已有的任何零件。

因此,如果板是一个5×4和它有一个L形的,它应该是这样的:

[1,1,0,0,0, 
 1,0,0,0,0, 
 1,0,0,0,0, 
 0,0,0,0,0] 

但是,你会进入[1,1,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0]

然后,它要求你输入在从默认位置开始的形状中,这将是右上角。

当进入形状的板是这样的:

[1, 2, 3, 4, 5, 
 6, 7, 8, 9, 10, 
    11,12,13,14,15, 
    16,17,18,19,20] 

因此,一个L形将有默认坐标:

[1,2,6,11] 

然后问下一个可用的一点是,所以如果你打算把L添加到已经存在L的板上。下一个可用的点就是3,如下所示:

[1,1,X,0,0, 
 1,0,0,0,0, 
 1,0,0,0,0, 
 0,0,0,0,0] 

所以程序的输出形状的新坐标具体做法是:

[3,4,8,13] 

但我需要帮助的错误检查溢出。换句话说,如果一块棋子离开棋盘,程序将打印失败。

例如:如果我想在5处放一个L块,坐标会输出[5,6,11,16],这是不对的。

它应该是什么样子:

[0,0,0,0,X,X 
 0,0,0,0,X, 
 0,0,0,0,X, 
 0,0,0,0,0] 

但会发生什么:

[0,0,0,0,X, 
 X,0,0,0,0, 
 X,0,0,0,0, 
 X,0,0,0,0] 

我怎样才能让如果一块熄灭板其打印失败了吗?我已经这样做了,所以你不能输入负的坐标,并且你不能让一块块比最大的坐标更远。

这里是我的代码:

user1 = input ('Enter the length of the board: ') 
#Length of the board 

user2 = input ('Enter the width of the board: ') 
#Width of the board 

user3 = user1 * user2 
#Area of the board 

board = input ('Enter in the contenets of the board, as a list (i.e. [0,1,....,0,0]): ') 
#Use list to enter in contents of board if any 

listA = input ('Enter the shape, in terms of default coordinates (i.e. [1,2,6,11]): ') 
#Enter in shape of piece you are placing on board 

if listA[-1] > user3: 
    print ('Failed!') 
    #Piece fails if end goes off board 

else: 
    if listA[0] < 1: 
     print ('Failed!') 
     #Piece fails if begining goes off board 

    else: 
     c = int(input ('Enter the next free slot: ')) 
     #Enter where the piece fits next 

     a = int(listA[0]) 
     #First coordinate of piece 

     b = [((x + c) - a) for x in listA] 
     #Finds location of moved piece 

     overlap = False 
     #Boolean to check for piece overlap 

     for y in b: 
      if board[y - 1] == 1: 
       overlap = True 
       #Overlap is true if piece ovelaps 
       #another piece already on the board 

      else: 
       overlap = overlap 
       #If no overlapping occurs then continue 

     if overlap == True: 
      print ('Failed!') 
      #Fails if piece overlaps 

     else: 
      print b 
      #prints the coordinates of the moved piece 
+3

您是否考虑用实际的二维结构(即列表列表)来表示二维“板”? – 2012-02-14 02:24:33

+0

这闻起来像功课。如果是这样,你应该使用'homework'标签。 – millimoose 2012-02-14 02:25:07

+0

@Karl这可能不会真的帮助在这种情况下。你仍然需要明确检查形状的大小,它是否与列表中的len或者存储在变量中的宽度无关。 – millimoose 2012-02-14 02:27:01

回答

0

我同意别人的这种闻起来像作业。所以这里有一个提示。想想是什么导致一个形状脱离董事会。用户输入您验证的“默认”值;你知道他们在董事会。但是这个作品被向右移动了一些空格(x),并且有一些空格(y)被向下移动。如果默认形状(w)加上x的宽度大于电路板的宽度,那么您知道它已经离开电路板的右侧。如果默认形状(h)加上y的高度大于电路板的高度,那么您知道它已经离开电路板底部。

所以,你必须做三两件事:确定xy,确定wh,然后比较x + wuser2y + huser1

0

这是不可能只用新的坐标列表做;您还必须知道这些坐标如何与相关。一旦你这样做了,你可以通过检查从01的转换,或反之亦然,看看边缘是否超出了电路板的边缘。