2017-01-09 83 views
-4

所以我正在開發遊戲連接4,我需要擺脫負面索引,因爲它會導致遊戲行爲有趣。基本上,玩家訪問的列基於一組列表組合成一個列表以形成一個數組。例如是否可以禁用負向索引?

grid1 = ['A','B','C','1'] 
    grid2 = ['D','E','F','2'] 
    grid3 = ['G','H','I','3'] 
    grid4 = ['J','K','L','4'] 

    # Now if we combine all three lists, we get 
    Total_Grid = [['A','B','C','1'] 
        ['D','E','F','2'] 
        ['G','H','I','3'] 
        ['J','K','L','4']] 
    # We have a total of 4 columns and 4 rows in this grid 
    # Here is the format of how we access values in list Total_Grid[row][col] 

因此,要訪問字母'G',我們做Total_Grid [2] [0]。因爲「G」是在第2行,列0抽出實際電網,我們有:

| | | | | 
    ------------- 
    | | | | | 
    ------------- 
    | | | | | 
    ------------- 
    | | | | | 
    ------------- 
    # As you can see, the grid is 4x4 

現在因爲在連接4,你不會選擇什麼排櫃檯進去,(它通常會下降到網格的底部),我們將爲行指定一個值。

row = 3 
    # Lets ask the user for input 
    col = input("What column would you like to drop your counter in? ") 
    # let's say user inputs 3, the counter will drop to [3][3] in the grid 
    col = 3 

    | | | | | 
    ----------------- 
    | | | | | 
    ----------------- 
    | | | | | 
    ----------------- 
    | | | | X | 
    -----------------   

我現在的問題的產生是因爲,例如,如果用戶輸入該列的值是負數,它仍然有效,因爲它的索引落後,但我想禁用此,因爲它打亂了遊戲時的AI嘗試從連接4點

阻止玩家
+2

你有沒有試過'如果我<0'? –

+2

你想要什麼?一個錯誤,或忽略它?你提到兩個。 – roganjosh

+1

您可以更改代碼嗎?我的意思是,您是否可以將「print」替換爲其他自定義方法? –

回答

1
for i in range(5): 
    if i<0: 
     print('ERROR:VALUE IS NEGATIVE') 
     pass 
    else: 
     # Do something 
+0

但是'i'在那個循環中不能<0 ... –

+0

在這個特定的例子中,那麼是的,並且不會有問題。一般情況下,如果列表中包含正數和負數,則可以捕獲它 –

2

你可以封裝你的支票和打印功能於一體,可調用的函數:

def print_only_if_non_negative(x): 
    if x >= 0: 
     print(x) 

for i in range(5): 
    print_only_if_non_negative(i-5) 
0
for i in range(5): 
     if((i-5)>=0): 
      print(i-5) 

請注意,在這種情況下,沒有任何內容會被打印,因爲所有數字都是負數,它將忽略負數。

相關問題