2012-02-14 37 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的轉換,或反之亦然,看看邊緣是否超出了電路板的邊緣。