# Play It, Sam

#1

``````from random import randint

board = []

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

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

print "Let's play Battleship!"
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)
print ship_row
print ship_col

# Everything from here on should go in your for loop!
# Be sure to indent four spaces!

for turn in range(4):

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

if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship!"
else:
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
print "Oops, that's not even in the ocean."
elif(board[guess_row][guess_col] == "X"):
print "You guessed that one already."
else:
print "You missed my battleship!"
board[guess_row][guess_col] = "X"
# Print (turn + 1) here!
print (turn+1)
print_board(board)``````

When I execute the code it shows me (e.g.) the following:

Let's play Battleship!
O O O O O
O O O O O
O O O O O
O O O O O
O O O O O
1
1
Guess Row: 5
Guess Col: 1
Oops, that's not even in the ocean.
1
Guess Row: 4
Guess Col: 0
You missed my battleship!
2
Guess Row: 2
Guess Col: 1
You missed my battleship!
3
Guess Row: 4
Guess Col: 0
4
O O O O O
O O O O O
O X O O O
O O O O O
X O O O O
None

Two problems:
1. Why Is it printing the location "print_board(board)" after it shows the battlefield. I took the code out of the for loop.
2. Shouldn't I have another guess if I guessed a location already? Could be that this comes in the future and I am just impatient. Apologies if this is the case.

Thank you very much in advance.

#2

Your questions are phrased in a way that make it difficult to give any reply. It seems like reading the code would answer them, you can also add print statements if you're unsure about when something runs. You can also create minimal examples so that you can study some individual behaviour in isolation. Minimal examples are also much better if you want to ask about something particular.

1) Unclear which print you refer to
2) Another guess? How many do you think there should be and how many do you think you're asked for right now? Why should it be different?

#3

Sorry ionatan, I'll try to rephrase.

I actually think I solved the problem by adding print statements as you proposed. After my board (see post) the program prints "1" and "1" (which is ship_row and ship_col).

Regarding the second question: Like I said I may be impatient and jumping ahead so nevermind

#4

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