Let's say that I am trying to make a BattleShip game in Python. I have a list of lists called board. Each list in board is a list of the spaces in that row of the board, for this example, it will be 5x5:
[['clear', 'clear', 'clear', 'clear', 'clear'],
['clear', 'clear', 'clear', 'clear', 'clear'],
['clear', 'clear', 'clear', 'clear', 'clear'],
['clear', 'clear', 'clear', 'clear', 'clear'],
['clear', 'clear', 'clear', 'clear', 'clear']]
I want to create a function to return a random clear space in the board.
def pl_point(board):
place = [randrange(0,5),randrange(0,5)] #heh, found out these aren't inclusive.
if board[place[0]][place[1]] == "clear": return place
else:
return pl_point() #calls itself until a clear place is found
Here are my questions: Is it inefficient to have a function call itself until it gets the value it wants (even if the board is almost entirely filled)? Is there a better way I should do this instead?
I couldn't figure out how to use a while statement with this because the statement would always reference 'place' before it was assigned, and I couldn't think of any value for place that wouldn't reference an out-of-range or unassigned 'board' value.
My apologies if this is a duplicate topic, I tried to find a similar one but couldn't. This is also my first time using this site to ask a question instead of answer one.
boardat the top is invalid; you need commas between the rows. And you might as well edit therandranges to use5to avoid there being any irrelevant problems here. (But I don't want to nitpick without pointing out that this is impressive for a first-time question. I don't know whether you pored over the help section, or just have good instincts for what's important to put into a question, but either way, nice job.)