14. Test Run


#1

I have some questions regarding some of the code.

  1. when trying to set the user’s guess to an “X”, why does guess_row = “X” not work, and I have to do board[guess_row][guess_col] = “X”? I’m not sure what the brackets are doing, I don’t understand that part at all

  2. for the computer to pick a random integer, why would it start at 0, wouldn’t it be most logical to start from 1 because there’s no (0,0) coordinate on the board, there’s only (1,1) right? I think anyways. Therefore the code would be like how i have it: return randint(1, len(board) - 1). Obviusly please explain this in lamens terms if possible.

  3. How do I make it stop printing ‘none’ right after the board prints?

from random import randint

board = []

"""for a number in range 0 to 5, it's going to append 5 O's"""
for x in range(0, 5):
  board.append(["O"] * 5)

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

print (print_board(board))

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

def random_col(board_in):
  return randint(1, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)
print (ship_row)
print (ship_col)

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

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

if guess_row not in range(5) or guess_col not in range(5):
  print ("Oops, that's not even in the ocean.")
elif guess_row == 'X' and guess_col == 'X':
  print ("You guessed that one already.")
else:
  board[guess_row][guess_col] = "X"


print (print_board(board))

#2

the board is a multi-dimensional list, lets do a simplified example:

x = ['a', 'b', 'c']

then to update first element in the list:

x[0] = 'd'

We need to update the board which we are going to print to the user, just doing guess_row = "X" won’t updated board

as seen by point 1, lists are zero indexed based, so (0, 0) certainly exist. If you want to compensate for the fact that users start counting at one, manipulate the user input. Attempting to manipulate the lists is way more difficult.

by default functions return None, so if you don’t want to print the returned result of the function don’t put a print statement in front of the function call


#3

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