Problem setting up loop on array in python (tuples/lists)

My continuing saga on attempting to build a next "simple" step evolution for the 2D "Battleship" game.

I can't seem to get the syntax correct for the following code segment:

######################################################################################
#   Place ships on target grid
######################################################################################

### FUTURES:    Logic to build at-risk Grid from ships selected by user to form his fleet

### TEST DATA
atRiskGridRows = fleetAssetCount+1
atRiskGrid[
            [ '(3,18)', '(4,18)', '(5,18)', '(6,18)' ],
            [ '(9,12)', '(10,12)', '(11,12)' ],
            [ '(7,21)', '(8,21)', '(9,21)', '(10,21)', '(11,21)', '(12,21)' ]
          ]


######################################################################################
#   Engage Enemy
######################################################################################

###
### Method 1 - failed
###
#    for x,y in itertools.product( range(6), range(10) ) :
#        if salvo == atRiskGrid[i][j] :
#            printConsole( "\t", atRiskGrid[i][j], " Hit on fleet asset ", i, ".  Damage control teams have been dispatched ..." )
#            salvoHit=1
#            goToNextSalvo = 1
#            break
#    # end for i

###
### Method 2 - failed
###
for salvo in '(9,21)' :
    salvoHit=0
    goToNextSalvo = 0
    for (i,row) in enumerate( atRiskGrid ) :
        for (j,col) in enumerate(row) :
            if salvo == atRiskGrid[i][j] :
                printConsole( "\t", atRiskGrid[i][j], " Hit on fleet asset ", i, ".  Damage control teams have been dispatched ..." )
                salvoHit=1
                goToNextSalvo = 1
                break
        # end for j
        if goToNextSalvo == 1 :
            break
    # end for i
    if salvoHit == 0 :
        printConsole( "\t", salvo, " Salvo has missed fleet assets ..." )
# end for salvo

Log segment with error message:

	 ['CGAF', (3, 18), (6, 18), [5, 4, 'Frigate', 'Halifax Class', 'FFH', 3], 'FFH 335', 'HMCS Calgary']
	 ['CGJJ', (9, 12), (11, 12), [3, 3, 'CoastalDefense', 'Kingston Class', 'MM', 3], 'MM 711', 'HMCS Summerside']
	 ['CFN7327', (7, 21), (12, 21), [7, 6, 'Replenishment', 'Protecteur Class', 'CFN', 4], 'CFN 7327', 'HMCS Asterix']

Traceback (most recent call last):
  File "/DB001_F4/WORK__Game_Battleship/./myBattleShip.py", line 296, in <module>
    atRiskGrid[
TypeError: list indices must be integers or slices, not tuple
1 Like

You're missing an equals sign here:

atRiskGrid[
# should be atRiskGrid = [

I lazily copied the rest of your code with some minor pythonification, seems to work fine!

at_risk_grid = [
    [ '(3,18)', '(4,18)', '(5,18)', '(6,18)' ],
    [ '(9,12)', '(10,12)', '(11,12)' ],
    [ '(7,21)', '(8,21)', '(9,21)', '(10,21)', '(11,21)', '(12,21)' ]
]
salvos = [ '(9,21)' ]

def print_booyah_when_hit(salvo, at_risk_grid):
    for i, ship in enumerate(at_risk_grid):
        for j, coord in enumerate(ship):
            if salvo == coord:
                print(f'Booyah at {coord}, take that ship {i}!')
                return
    print(f'salvo at {salvo} did not achieve booyah :(')

def do_salvos(salvos, at_risk_grid):
    for salvo in salvos:
        print_booyah_when_hit(salvo, at_risk_grid)

do_salvos(salvos, at_risk_grid)

# Booyah at (9, 21), take that ship 2!
2 Likes

I'd replace that with

#for j, coord in enumerate(ship):
            if salvo in ship:
                print(f'Booyah at {salvo}, take that ship {i}!')
                return

because

$ python3
...
>>> lst = [(1,2), (1,3), (1,4)]
>>> (1,2) in lst
True
1 Like

Thank you, Eugene. Using the "in" approach doesn't reveal the coordinates, which would be needed in order to place "animation" into a OpenGL theatre of operations.

That gives a hint of some of the "toned-down" features that I want to include in my version of the game. :slight_smile:

Thank you, Stephen! I must have been brain-dead to miss that. :frowning:

Continuing with the above logic, I have another code segment that doesn't seem to generate the same format for the matrix.

The earlier code has single quotes around the tuples.

This segment does not have those quotes, and I don't know how to get there. Any feedback would be appreciated.

######################################################################################
def getSalvos( pattern, col, row ) :
######################################################################################
    newl = ord('\n')
    tabc = ord('\t')
    template = "\t%3d %3d    %s"
    targets = []
    targetCount = 0

    print("\n")
        
    ###
    ###     for "match case" example  https://stackoverflow.com/a/30881320
    ###

    match pattern :
        case 8 :
            ### Firing Pattern -> Randomized on target
            munitions_cost = 10
            for i in range(0,munitions_cost) :
                x = random.randrange(0,7) - 3
                y = random.randrange(0,7) - 3
                ###
                ### FUTURES:    verify coordinates for repeats and generate additional set of numbers when that happens
                ###
                target = ( col+x, row+y ) ; print( template % (x, y, target ) ) ; targets.append( target ) ; targetCount += 1
            return targets



Session log:

ericthered@OasisMega1:/DB001_F4/WORK__Game_Battleship$ ./myBattleShip.py

 Enter the coordinates of square for ship start -> D18

 Choose the type of vessel you want to create [1-7] -> 5

	 [5, 4, 'Frigate', 'Halifax Class', 'FFH', 3]

	 Ship's bow starts at (3, 18)

	 Ship's stern ends at (6, 18)

	 Ship launched into service: 
	 ['CGAF', (3, 18), (6, 18), [5, 4, 'Frigate', 'Halifax Class', 'FFH', 3], 'FFH 335', 'HMCS Calgary']

	 Ship launched into service: 
	 ['CGJJ', (9, 12), (11, 12), [3, 3, 'CoastalDefense', 'Kingston Class', 'MM', 3], 'MM 711', 'HMCS Summerside']

	 Ship launched into service: 
	 ['CFN7327', (7, 21), (12, 21), [7, 6, 'Replenishment', 'Protecteur Class', 'CFN', 4], 'CFN 7327', 'HMCS Asterix']


 Fleet orders have been tranmitted.
 The following vessels have been allocated to Task Force ORION.
 Proceed upon designated course until destination
 at which point the fleet will join Standing NATO Maritime Group 2
 and fulfill previous commitments to its objectives.

	 ['CGAF', (3, 18), (6, 18), [5, 4, 'Frigate', 'Halifax Class', 'FFH', 3], 'FFH 335', 'HMCS Calgary']
	 ['CGJJ', (9, 12), (11, 12), [3, 3, 'CoastalDefense', 'Kingston Class', 'MM', 3], 'MM 711', 'HMCS Summerside']
	 ['CFN7327', (7, 21), (12, 21), [7, 6, 'Replenishment', 'Protecteur Class', 'CFN', 4], 'CFN 7327', 'HMCS Asterix']

 Enter targetting coordinates -> D18
3 18

	 
Select targeting pattern (munitions expenditures shown):


	 	1    ['Square', 8]

	 	2    ['X', 9]

	 	3    ['Cross-Hairs', 9]

	 	4    ['Diagonal Right', 10]

	 	5    ['Diagonal Left', 10]

	 	6    ['Bars Horizontal', 10]

	 	7    ['Bars Vertical', 10]

	 	8    ['Randomized Around Target', 10]

 Select targetting pattern -> 1


	 -2  -2    (1, 16)
	 -2   2    (1, 20)
	  2   2    (5, 20)
	  2  -2    (5, 16)
	 -2   0    (1, 18)
	  0   2    (3, 20)
	  2   0    (5, 18)
	  0  -2    (3, 16)
[(1, 16), (1, 20), (5, 20), (5, 16), (1, 18), (3, 20), (5, 18), (3, 16)]

	 (1, 16) Salvo has missed fleet assets ...

	 (1, 20) Salvo has missed fleet assets ...

	 (5, 20) Salvo has missed fleet assets ...

	 (5, 16) Salvo has missed fleet assets ...

	 (1, 18) Salvo has missed fleet assets ...

	 (3, 20) Salvo has missed fleet assets ...

	 (5, 18) Salvo has missed fleet assets ...

	 (3, 16) Salvo has missed fleet assets ...

ericthered@OasisMega1:/DB001_F4/WORK__Game_Battleship$ 

I think that the source of confusion is in the fact that elements of the
at_risk_grid = [ [ '(3,18)', '(4,18)'...] [...] ]
are not tuples in quotes, but strings.

$ python3
...
>>> type('(10,12)')
<class 'str'>
>>> str((10,12))
'(10, 12)'

1 Like

Thank you, Eugene. I used that hint to correct my issue.