Ship with length 2 [not an exercise]

#1

I'm trying to get my battleship game working with a ship of length 2. So far everything works most of the time, but on occasion, the below function returns a value of none, instead of an integer between 0 and 4. This occurs approximately 30-40% of the time.

ship_row1, ship_row2, and ship_col1 always have values before the function plays through, so my understanding is that the code should check:
1. If both parts of the ship are in the same row, check if the column difference is one, and only one. If rows are same and column variance is 1, return value.
2. if the ship is verticle (ie, previous functions grant it 2 differing rows), return the column value for existing component.
3. If none of the other conditions are met, re-run the function (creating a loop until success)

``````def ship_maker2():
col2 = random_col(board)
if ship_row1 == ship_row2:
if (col2 == ship_col1 + 1) or (col2 == ship_col1 - 1):
print "valid column found"
return col2
elif ship_row1 != ship_row2:
print "consistent columns"
return ship_col1
else:
ship_maker2()``````

#2

You can add more print statements to verify whether that is what's happening.
You can also use a hard-coded value instead of random while debugging.
If you just look at your code there are two paths which do not return anything, so getting None as result should not be surprising

#3

I'm looking at it myself and I can't find the two paths that don't return anything - my understanding is that the paths that don't return anything simply play the function through again from the beginning. While debugging I found that this portion of the code is where the error lies.

print col2 is printing up a numerical value between 0 and 4, yet return col2 is producing a result of none.

If print interprets the variable as a number and prints the number successfully, shouldn't return also read the variable the same way?

def ship_maker2():
col2 = random_col(board)
if ship_row1 == ship_row2:
if (col2 == ship_col1 + 1) or (col2 == ship_col1 - 1):
print "valid column found"
print col2
return col2

#4

I worked it out. If anyone is curious, the mistake I made was that I was calling the function during the function in order to loop it over, however I was not returning the new function, and as a result the function was playing out and finding the correct results, but they were no longer being returned into the ship_col2 value.

``````def ship_maker2():
col2 = random_col(board)
if ship_row1 == ship_row2:
if (col2 == ship_col1 + 1) or (col2 == ship_col1 - 1):
print "valid column found"
print col2
return col2
print "nope, trying again"
return ship_maker2()
elif ship_row1 != ship_row2:
print "consistent columns"
return ship_col1
else:
print "trying again"
return ship_maker2()``````

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.