Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am creating a battleships game and would like to check the positions around the players targeted position to check if any ships are located there,i.e.

!(https://i.sstatic.net/TIB7R.jpg)

on this board the program would check positions (2,0), (1,1), (2,2) and (3,1) for any ships, if there were any present the subroutine would return True, and if not it would return False.

So this is my current code:

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

When checking if the positions around the targeted one are on the board, I use a for loop to increment through the list around, which contains all the surrounding positions, however let's say the second position of around was (10,9), the for loop would remove this position because its not on the board and then increment to the next position in around, i.e. the third position, however there are only the original positions 1, 3, and 4 left in around so it would skip checking the original position 3 and instead go straight to the original position 4.

(Sorry if that's a bit confusing)

So my question is, is there something I can add beneath 'around.remove(i)' that moves back the increment of the for loop 'for i in around' by 1?

like image 559
0isab Avatar asked Nov 20 '25 11:11

0isab


1 Answers

Modifying the item you are iterating over does not work.

I don’t know why you have int(i[x]). Do you expect R or C not to be an integer?

The Board[][] == "-" or "m" or "h" is always True because "m" or "h" is always True

Your loop is better written as:

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
like image 76
AJNeufeld Avatar answered Nov 22 '25 00:11

AJNeufeld