如何在 python 中将 for 循环的增量设置为 1?

How can I set the increment on a for loop back by one in python?

我正在创建一个战舰游戏,我想检查玩家目标位置周围的位置,以检查那里是否有任何船只,即

!(https://imgur.com/a/9Dddom0)

在此板上,程序将检查任何船只的位置 (2,0)、(1,1)、(2,2) 和 (3,1),如果存在则子例程将 return 正确,如果不正确,则 return 错误。

所以这是我当前的代码:

def RadarScan(Board, Ships, R, C):
    around = [[C, R - 1], [C + 1, R], [C, R + 1], [C - 1, R]]
    for i in around:
        for x in range(2):
            if int(i[x]) > 9 or int(i[x]) < 0:
                around.remove(i)
    near = False
    for i in range(len(around)):
        if Board[around[i][0]][around[i][1]] == "-" or "m" or "h":
            continue
        else:
            near = True
            break
    if near == True:
        return True
    else:
        return False

当检查目标位置周围的位置是否在棋盘上时,我使用 for 循环递增列表 around,其中包含所有周围的位置,但是假设 around 的第二个位置是 (10, 9), for 循环会删除这个位置,因为它不在板上,然后递增到周围的下一个位置,即第三个位置,但是周围只剩下原来的位置 1、3 和 4,所以它会跳过检查原来的位置3,直接看原来的位置4。

(对不起,如果这有点混乱)

所以我的问题是,我是否可以在 'around.remove(i)' 下面添加一些东西,将 for 循环 'for i in around' 的增量向后移动 1?

如果我正确理解你的问题,一种方法可能是手动索引:

def RadarScan(Board, Ships, R, C):
    around = [[C, R - 1], [C + 1, R], [C, R + 1], [C - 1, R]]
    index = 0
    for i in range(len(around)):
        index += 1
        for x in range(2):
            if int(around[index][x]) > 9 or int(around[index][x]) < 0:
                around.remove(around[index])
                index -= 1

    near = False
    for i in range(len(around)):
        if Board[around[i][0]][around[i][1]] == "-" or "m" or "h":
            continue
        else:
            near = True
            break
    if near == True:
        return True
    else:
        return False

For 循环无法做到这一点。使用 while 循环:

def RadarScan(Board, Ships, R, C):
    around = [[C, R - 1], [C + 1, R], [C, R + 1], [C - 1, R]]
    c= 0
    while c < len(around)-1:
        i = around[c]
        for x in range(2):
            if int(i[x]) > 9 or int(i[x]) < 0:
                around.remove(i)
                c-= 1
        c += 1
    near = False
    for i in range(len(around)):
        if Board[around[i][0]][around[i][1]] == "-" or "m" or "h":
            continue
        else:
            near = True
            break
    if near == True:
        return True
    else:
        return False

这应该可以解决问题

修改您正在迭代的项目不起作用。

我不知道你为什么有int(i[x])。您认为 RC 不是整数吗?

Board[][] == "-" or "m" or "h" 总是 True 因为 "m" or "h" 总是 True

你的循环最好写成:

for x, y in around:
    if x in range(10) and y in range(10):
        if Board[x][y] not in "-mh":
            return True
return False