Reputation: 13
I'm trying to complete the loop below where inputs are taken from the user and then sent through the function "shipPlacement" at the top. However, when i run my code, the loop runs for the first term in "shipSizeList" and then after completing the function the user is not prompted for another input for "inputPos". How do i design this so all the differently sized ships positions are appended to "listOfShipsPos"?
listOfShipsPos = []
# adds to the grid where all of the ships are
def shipPlacement(position,size,direction):
listOfShipsPos.append(position)
direction.upper()
i = 1
# for the length of ship (size), repeats adding positions in the
# desired direction (up(U), down(D), left(L) or right(R))
while i < size:
if direction == "U":
listOfShipsPos.append(ship - 8)
if direction == "D":
listOfShipsPos.append(ship + 8)
if direction == "L":
listOfShipsPos.append(ship - 1)
if direction == "R":
listOfShipsPos.append(ship + 1)
i =+ 1
# ask user to input their ship positions
shipSizeList = [2, 3, 3, 4, 5]
for shipSize in shipSizeList:
inputSize = shipSize
inputPos = int(input("Position for " + str(shipSize) + " sized ship? (1 to 64)"))
inputDir = str(input("direction for " + str(shipSize) + " long ship? "))
shipPlacement(position=inputPos, size=inputSize, direction=inputDir)
Upvotes: 0
Views: 907
Reputation: 1637
The function shipPlacement
actually never finishes executing because the loop never completes. The reason is the statement i =+ 1
. It should be i += 1
. Also, I think you should reassign the variable direction
, this is the full code
listOfShipsPos = []
# adds to the grid where all of the ships are
def shipPlacement(position,size,direction):
listOfShipsPos.append(position)
direction = direction.upper()
i = 1
# for the length of ship (size), repeats adding positions in the
# desired direction (up(U), down(D), left(L) or right(R))
while i < size:
if direction == "U":
listOfShipsPos.append(ship - 8)
if direction == "D":
listOfShipsPos.append(ship + 8)
if direction == "L":
listOfShipsPos.append(ship - 1)
if direction == "R":
listOfShipsPos.append(ship + 1)
i += 1
# ask user to input their ship positions
shipSizeList = [2, 3, 3, 4, 5]
for shipSize in shipSizeList:
inputSize = shipSize
inputPos = int(input("Position for " + str(shipSize) + " sized ship? (1 to 64)"))
inputDir = str(input("direction for " + str(shipSize) + " long ship? "))
shipPlacement(position=inputPos, size=inputSize, direction=inputDir)
Upvotes: 1