Skip to main content
 首页 » 编程设计

python之我需要 Python 的帮助来检查列表的边界

2025年05月04日7TianFang

所以我正在尝试编写一个代码来确定形状在板上的放置位置,如果板上已经有 block ,它会知道它们是否重叠。

所以我现在拥有的是通过用户输入来获取板的长度和宽度的代码。

然后假设用户知道棋盘的大小,它会提示您输入棋盘上已有的任何棋子。

所以如果棋盘是 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] 

但我需要帮助的是检查溢出的错误。换句话说,如果棋子脱离棋盘,程序将打印失败。

例如:如果我想在 5 处放置一个 L block ,坐标将输出 [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] 

如果棋子从棋盘上掉下来,我怎样才能让它打印失败?我已经做到了,你不能输入负坐标,你不能让一 block 比最大坐标更远。

这是我的代码:

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 

请您参考如下方法:

我同意其他人的看法,这闻起来像作业。所以这里有一个提示。想一想是什么导致形状脱离棋盘。用户输入您验证的“默认”值;你知道他们在董事会上。但是随后该片段向右移动了一些空格 (x),并向下移动了一些空格 (y)。如果默认形状 (w) 加上 x 的宽度大于棋盘的宽度,那么您就知道它已经从棋盘右侧移出。如果默认形状的高度 (h) 加上 y 大于板的高度,那么您就知道它已经离开板的底部。

所以你必须做三件事:确定x和y,确定w和h,以及然后将 x + w 与 user2 和 y + h 与 user1 进行比较。