How would you do this in extra credit?

#1

I am stuck on Battleship, Extra Credit.

My code works just fine, I am just wondering how to get the sideline numbers in there... Currently, this is what I get...
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
Turn 1
Guess Row:

And I want this
1 2 3 4 5
1 O O O O O
2 O O O O O
3 O O O O O
4 O O O O O
5 O O O O O

How do I get that with this code...

``````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)

# Everything from here on should go in your for loop!
# Be sure to indent four spaces!
for turn in range(0, 4):
print "Turn", turn + 1
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 "Well, you are bound to get lucky sometimes...!"
break
elif (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 are stupid, you already did that."
else:
board[guess_row][guess_col] = "X"
print "You suck at this!"
print_board(board)
if turn == 3:
print "Why the heck are you an army general?"``````

#2

Hi, @camdenhamlet ,

Recall that the rows and columns are numbered from `0` to `4`. Here's one solution, but you can come up with more elegant ones that will work for any size board. ...

``````def print_board(board):
print("  0 1 2 3 4")
for row in range(len(board)):
print str(row) + " " + " ".join(board[row])``````

Output:

``````  0 1 2 3 4
0 O O O O O
1 O O O O O
2 O O O O O
3 O O O O O
4 O O O O O``````

#3

I tried that, and it is the same output...
what if you did this:
for x in range(5):
board.append(["1 2 3 4 5"])

I just dont know how to do that, and then have O's everywhere else...

#4

the output for that is
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
Turn 1
Guess Row:

#5

WHat about If I wanted to color something. Say I wanted to make the O's green, and the x's red...

#6

I tried googling it, but I got no good answers... Is that even possible in python?

#7

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