是否可以禁用负索引?

时间:2017-01-09 20:18:49

标签: python python-3.x

所以我正在开发游戏连接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点

3 个答案:

答案 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)

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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

请注意,在这种情况下不会打印任何内容,因为所有数字都是否定的,它会忽略负数。