我需要帮助用Python检查列表边界

2 投票
2 回答
1872 浏览
提问于 2025-04-17 12:59

我正在尝试写一段代码,用来确定形状在棋盘上的位置,如果棋盘上已经有棋子,它还可以判断这些棋子是否重叠。

现在我有的代码是让用户输入棋盘的长度和宽度。

然后假设用户知道棋盘的大小,程序会提示你输入棋盘上已经存在的棋子。

比如,如果棋盘是5 x 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]

但我需要帮助的是检查溢出错误。换句话说,如果棋子超出了棋盘的范围,程序会显示失败。

举个例子:如果我想把一个L形状放在5的位置,输出的坐标会是[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

2 个回答

0

光有新的坐标列表是没办法解决问题的;你还需要知道这些坐标之间是怎么 关联 的。一旦你搞清楚了这些关系,就可以通过检查 pos % WIDTH 的值是否从 0 变成 1 或反过来,来判断一条边是否越过了棋盘的边缘。

0

我同意其他人的看法,这听起来像是作业。所以这里给你一个提示。想想是什么原因导致形状会超出边界。用户输入的“默认”值你需要验证一下;你知道它们是在棋盘上的。但是接着这个形状会向右移动一些格子(x),向下移动一些格子(y)。如果默认形状的宽度(w)加上x大于棋盘的宽度,那就说明它已经超出棋盘的右边了。如果默认形状的高度(h)加上y大于棋盘的高度,那就说明它已经超出棋盘的底部了。

所以你需要做三件事:确定xy的值,确定wh的值,然后把x + wuser2进行比较,把y + huser1进行比较。

撰写回答