11. Danger, Will Robinson!



11. Danger, Will Robinson!!

Can someone tell me what's wrong with my code?
Don't know what's the point of the sentences before the instructions.

from random import randint

board = []

for x in range(0, 5):
    board.append(["O"] * 5)

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

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

def random_col(board):
    return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)

guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))

# Write your code below!
if guess_row == ship_row and guess_col == ship_col:
    print "Congratulations! You sank my battleship!"
    print "You missed my battleship!"
    X = [guess_row, guess_col]


    board[guess_row][guess_col] = "X"


But I still don't understand what does this part mean: "board[guess_row][guess_col] = "X""?
Does it mean replacing the randomly generated point or the point typed by the player with "X"?


Let me try :slight_smile:

I think it means to replace the point typed by the player with "X".

When you key in board[guess_row][guess_col], you are directing Python to a specific element in the (guess_row+1)th row and the (guess_col+1)th column. If I am not wrong, this is because you are using the index system whereby list[1] refers to the 2nd element in the list, list[3] refers to the 4th element in the list and so on. By equating board[guess_row][guess_col] to "X", you are requesting Python to assign the element there to become X, thereby marking out the spot where the player has guessed.

We can wait for @mtf to confirm this :stuck_out_tongue:


Thanks umopapsidn. That's really helpful.


Let y be the row and x be the col:


Consider that each row is a list, and each column is a member of a row list, hence the double index. One to distinguish the row, the other to distinguish the column. Pretty much what @umopapsidn said.