right now I’m trying to make the battleship board game as practice, and I’ve been using classes for the most part with a few misc standalone functions. Everything below is a standalone. I can’t wrap my mind around it, this works if I attack ships in order from last to first in the list, but if you go in any other order it breaks saying the list index doesn’t exist. Please help.
Basically my system is whenever a ship is “hit” (the move is in the same position as one in the shipList) then it adds a hitList. What these functions is check if any of the items in the hitList against the known positions of the ships…created in a separate list when ship object is made. i been trying to make this work for 2 days
def checkForSunk(shipList, hitList):
#Lists is something like this [[0,1],[0,2],[0,3]]
#ShipList[0] is list, [1] is name of ship
#ShipList is ALL ships.
print 'SHIPLIST : %s' % (shipList)
#[[[[0,1],[0,2],[0,3],[0,4],[0,5],[],[]], 'Destroyer'], [[[0,1],[0,2],[0,3],[0,4],[0,5],[],[]], 'Destroyer'], [[[0,1],[0,2],[0,3],[0,4],[0,5],[],[]], 'Destroyer']]
#[[[0,1],[0,2],[0,3],[0,4],[0,5],[],[]], 'Destroyer']
# 0 1
print 'HITLIST : %s ' % (hitList)
for j in range(len(shipList)):
for i in shipList[j][0]:
if i in hitList:
print 'True in ship # %s' % (shipList[j][1])
del shipList[j][0][shipList[j][0].index(i)] #Delete that part of the ship from the list.
#Check if there's any empty ships, and delete the ship if there are.
for j in range(len(shipList)):
print shipList[j] #Problem around here!!!!!!!!!!!!
if listIsEmpty(shipList[j][0]):
print '%s has been sunk!' % (shipList[j][1])
del shipList[j]
def isGameOver(shiplist):
if shiplist == []:
return True
else:
return False
def listIsEmpty(list):
for i in range(len(list)):
if list[i] != []: #If it finds anything thats not empty, return False. Else true
return False
else:
return True
Am I going about it all wrong? Should I be physically deleting lists?
Thanks
The answer is the same as for issue Delete item in a list using a for-loop :
Iterate backwards: