问题变化列表索引

时间:2019-11-15 13:50:21

标签: python arrays object

我正在开发基于对象的战舰计划,但是我认为这并不重要。我将船只放置在我的木板上(二维列表)。我有条件避免船只登上董事会并互相重叠。事实是,相同的机制适用于水平船,但不适用于垂直船(用户必须先输入方向)。该条件将评估所需位置是否为“ 0”或其他,因此索引的范围从用户给出的范围开始,一直到船舶的大小(由用作名称)给出。

以这种方式构造字段/面板/地图

    self.Field = [[0 for i in range(N)] for j in range(N)]

我得到了这些输入,其中一个与字典相关,该字典给出了一个整数,该整数根据名称说明了船只的大小。我将此值ship[size]放在变量tam中。此tam稍后将在第二个if中用于评估。在这里,您可以找到有条件的边和其他重叠部分。当我运行此命令时,这会给“ list index is out of range ”带来错误。第三个if会执行相同的操作,但对于水平方向来说效果很好。问题是,经过一些调试之后,不同之处在于,F[a:b][c]无效而F[a][b:c]无效。那是我的问题,为什么呢?我已经使用numpy数组解决了问题,并且可以正常工作。

    while(o != 5):
        size = input("What is your ship ?").replace(" ", "")
        tam = ship[size]
        orient = input("It is on the vertical or horizontal ? v or h: ").replace(" ", "")
        posit = input("Considering a top/left orientation as the begining, tell me where it starts: Letter and Number as A01  ").replace(" ", "")
        positA, posit1 = posit[:1], int(posit[1:])
        if orient == 'v':                
            if (N - coordv[positA]) < tam or any(self.Field[coordv[positA]:(coordv[positA] + tam - 1)][posit1]) != 0:
                print("Irregular positon, try again")
            else:
                for p in range(tam):
                    self.Field[coordv[positA] + p][posit1] = size[0:2]
                o = o + 1
                npField = np.array(self.Field, dtype=object) 
                print(npField)

        elif orient == 'h':
            if (N - int(posit1)) < tam or any(self.Field[coordv[positA]][posit1:posit1 + tam - 1]) != 0:
                print("Irregular positon, try again")
            else:
                for p in range(tam):
                    self.Field[coordv[positA]][posit1 + p] = size[0:2]
                o = o + 1

                npField = np.array(self.Field, dtype=object) 
                print(npField)

0 个答案:

没有答案