Extra credit: Add a 2 seated second ship for each player!


#1

Hey guys, I just need help to understand something.

I'm trying to add a second boat for both players and somehow it ended up adding a boat to Player2's board with the coordinates 4 1, 4 1 which means it's overlapping.

I ranned it several times and it still haven't made the same error again. Nonetheless, I was intrigued and thought you experts might know if there is some flaw on my coding so far.

Thanks!

from random import randint

#boards for each player
boardP1 = []
boardP2 = []

for x in range(5):
    boardP1.append(["O"] * 5)
    boardP2.append(["O"] * 5)

def print_board(board):
    for row in board:
        print " ".join(row)

print "Let's play Battleship!"

def random_row(board):
    return randint(0, len(board) - 1)

def random_col(board):
    return randint(0, len(board[0]) - 1)
#P1 ships
ship1_row = random_row(boardP1)
ship1_col = random_col(boardP1)
ship2_row = random_row(boardP1)
ship2_col = random_col(boardP1)

#find the second half of P1's second ship
if ship2_row == ship1_row and ship2_col == ship1_col:
    ship2_row = random_row(boardP1)
    ship2_col = random_col(boardP1)
elif ship2_row<4 and ship1_row!=(ship2_row+1):
    ship2_row2=ship2_row+1
    ship2_col2=ship2_col
elif ship2_row>0 and ship1_row!=(ship2_row-1):
    ship2_row2=ship2_row-1
    ship2_col2=ship2_col
elif ship2_col<4:
    ship2_row2=ship2_row
    ship2_col2=ship2_col+1
else:
    ship2_row2=ship2_row
    ship2_col2=ship2_col-1

#P2 ships
ship3_row = random_row(boardP2)
ship3_col = random_col(boardP2)
ship4_row = random_row(boardP2)
ship4_col = random_col(boardP2)

#find the second half of P2's second ship
if ship4_row == ship3_row and ship4_col == ship3_col:
    ship4_row = random_row(boardP2)
    ship4_col = random_col(boardP2)
elif ship4_row<4 and ship3_row!=(ship4_row+1):
    ship4_row2=ship4_row+1
    ship4_col2=ship4_col
elif ship4_row>0 and ship3_row!=(ship4_row-1):
    ship4_row2=ship4_row-1
    ship4_col2=ship4_col
elif ship4_col<4:
    ship4_row2=ship4_row
    ship4_col2=ship4_col+1
else:
    ship4_row2=ship4_row
    ship4_col2=ship4_col-1

print "Boat 1x1 P1:", ship1_row, ship1_col
print "Boat 1x2 P1:", ship2_row, ship2_col, ship2_row2, ship2_col2
print "Boat 1x1 P2:", ship3_row, ship3_col
print "Boat 1x2 P2:", ship4_row, ship4_col, ship4_row2, ship4_col2

#define board with the ships
boardP1[ship1_row][ship1_col] = "1"
boardP1[ship2_row][ship2_col] = "2"
boardP1[ship2_row2][ship2_col2] = "2"
boardP2[ship3_row][ship3_col] = "1"
boardP2[ship4_row][ship4_col] = "2"
boardP2[ship4_row2][ship4_col2] = "2"

#i want to know both games - just for fun
print "Player 1 Board:"
print_board(boardP1)
print "Player 2 Board:"
print_board(boardP2)

This is the output that made me come here and expose myself :slight_smile:


#2

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