To Your Battle Stations! 18/19 + 19/19


#1

I am trying to include a feature where I can keep track of the Hits and Misses of two players for the game. Please can you advise how I can approach it with my current code. Thank you!

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 # you can shut this hint off if you'd like
print ship_col # you can shut this hint off if you'd like

print ""
turns = 5

for turn in range(turns):

Everything from here on should go in your for loop!

Be sure to indent four spaces!

print "Turn", turn + 1
guess_row = int(raw_input("Guess Row:"))-1
guess_col = int(raw_input("Guess Col:"))-1

if guess_row == ship_row and guess_col == ship_col:
    print "Congratulations! You sunk my battleship!"
    board[guess_row][guess_col] = 'Y'
    break
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", turn + 1
if turn == turns-1:
    print "Game Over"

print_board(board)


#2

First off, ensure that code which you post is intact, otherwise it's a mostly useless mess.

How you "should" store it depends on how you are planning to use that information later. Consider what you need to do and pick an appropriate data structure that supports those operations. If you just want to keep history, then you could add strings to a list.


#3

This is my code. It works for one user with handling exceptions!
turn = 0
while turn < 4:
print '-----------'
try:
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
except:
print "You didn't make a guess"
continue

if guess_row == ship_row and guess_col == ship_col:
    print "Congratulations! You sunk my battleship!"
    board[guess_row][guess_col] = "S"
    print_board(board)
    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 guessed that one already."
else:
    print "You missed my battleship!"
    board[guess_row][guess_col] = "X"
    print_board(board)
    print "Turn ", turn + 1
    turn += 1
    if turn == 4:
        print "Game Over"
        board[ship_row][ship_col] = "S"
        print_board(board)
        break