Extra Credit Work


#1




Extra Credit

There are no error messages. The issue is that the board does not update in between turns, which I suspect is related to the use of functions. However, I thought I had configured the functions correctly to save the board. The cheat code, when entered correctly, also does nothing.

I expect this to work, it should be fairly self-explanatory. My plan was to have two players playing against the board, while a cheat code can be used to give away the real position.


from random import randint

class WinStop(Exception):
    pass

def random_row(board):
    return randint(0, len(board) - 1)
    
def random_col(board):
    return randint(0, len(board) - 1)
    
def print_board(board):
    for row in board:
        print(" ".join(row))
        
def turn(row, col, play):
    print_board(play)
    guess_row = int(input("Guess Row:"))
    guess_col = int(input("Guess Column:"))
    if guess_row == row and guess_col == col:
        print("You sunk the battleship!")
        raise WinStop
    elif play[row][col] == "X":
        print("You guessed that already.")
    elif (row < 0 or row > 10) or (col < 0 or col > 10):
        print("Oops, that's out of bounds.")
    else:
        print("You missed!")
        play[row][col] == "X"
    return play

board = []
for x in range(10):
    board.append(["O"] * 10)
print("Let's play Battleship!")
print_board(board)
ship_row = random_row(board)
ship_col = random_col(board)
counter = 0
code = input("Cheatcode:")
if code == (2 ** 9) - 1:
    print("Ship Row: {}".format(ship_row))
    print("Ship Column: {}".format(ship_col))
else:
    while True:
        try:
            if counter == 100:
                print("Maximum number of turns exceeded.")
                raise WinStop
            elif counter % 2 == 0:
                print("Player 1:")
                board = turn(ship_row, ship_col, board)
            else:
                print("Player 2:")
                board = turn(ship_row, ship_col, board)
            counter += 1
        except WinStop:
            break
if counter == 100:
    print("Game over!")
elif counter % 2 == 0:
    print("Congratulations, Player 1!")
else:
    print("Congratulations, Player 2!")


#2

if you want to print an updated version of the board, you are going to need to call the print_board function:

print_board(board)

somewhere in the loop, so each turn the boards get printed