11/19


#1

When I write my code out the way it accepts, it places an X in the number + 1 for row and column, For example, when I guess 3, 2, it puts the x in 4,3. It makes sense because of the index starting at 0, but nor for a game. So I put in a -1 for the guess row and guess col change for X, and it doesn't accept it.

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)

print_board(board)

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:"))

print ship_row
print ship_col

Write your code below!

if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sank my battleship!"
else:
print "You missed my battleship!"
board[guess_row-1][guess_col-1] = "X"
print_board(board)


#2

Yep, you got it! Unfortunately, the code is designed for a range of 0 to 4 and if you fix it for a more normal 1 to 5 range you'll break validation.

I'd recommend you save that change for the last lesson. That's a sandbox for applying enhancements like yours to the code.


#3

yep, the truth should be board[guess_row][guess_col]="X",

cause that if you input 3,2,it will think that you are guessing the board[3][2],then it will display as "4,3",but in fact you should code it [guess_row][guess_col],then which you have guessed can be changed


#4

this should work

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)

print_board(board)

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:"))

print ship_row
print ship_col

Write your code below!

if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sank my battleship!"
else:
board[guess_row][guess_col] = 'X'
print_board(board)
print "You missed my battleship!"