Wednesday, 18 September 2013

How do I place the elements of a list into the middle of another list? A one dimensional battleship game. (Python)

How do I place the elements of a list into the middle of another list? A
one dimensional battleship game. (Python)

So I'm creating this simple little battleship program. I'm getting a
little frustrated at the aspect of a player placing their boats. What I'd
like is for the function ship_place() to take a boat as a parameter, ask
for the index of the array the player would like to place the boat, and
then place the boat in the ocean starting at the specified index. I want
the contents of the boat (which is a list) to be "exported" to the ocean
(which is also a list).
I created this function and it's been giving me two errors. The first is
that for some reason it's placing the entire boat array into the specified
index. The second is that the list taken_spots1 is not receiving all of
the taken spots it should be.
P.S. I originally had for loops within the function but was getting the
same error, so I tried while loops to see if anything would change.
Nothing did.
ocean = ['O']*100
taken_spots1 = []
boat1 = ['<','>'],
boat2 = ['<','=','>'],
boat3 = ['<','::','>'],
boat4 = ['<','@','@','>'], #cannons
boat5 = ['<','G','U','N','>']
ship_yard = [boat1,boat2,boat3,boat4,boat5]
def ship_place(boat):
spot = ""
while spot == "":
spot = input("Place a boat: ")
spot = eval(spot)
if spot in taken_spots1:
spot = ""
print("That spot's already taken, dummy")
else:
j=0
while j < len(boat):
taken_spots1.append(spot + j)
j += 1
i = 0
while i < len(boat):
ocean[spot - 1 + i] = boat[i]
i += 1
for i in range(5):
ship_place(ship_yard[i])
print(ocean)
print(taken_spots1)

No comments:

Post a Comment