Battleship extra


#1



Hey,

I made my program ask if the user would like to play again and loop which works correctly as far as I can tell from testing. However, I am stuck on how I could reset the board after each game.


# Written by Doc

from random import randint

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


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

Lines 5 through 12 create the board.

"""

print("Let\'s play Battleship!")
print_board(board)


def random_row(board):
    return randint(0, len(board))


def random_col(board):
    return randint(0, len(board))


def main():

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

    """

    Lines 23-24, 27-28, and 33-34 set the location of the ship.

    """
    playAgain = True
    while playAgain:
        for turn in range(1,5):
            print("Turn " + str(turn))

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

            print("The ship was at ", end='')
            print(ship_row, end=',')
            print(ship_col)

            if guess_row == ship_row and guess_col == ship_col:
                print("Congratulations! You sank my battleship!")
                break
            else:
                if guess_row not in range(0,(len(board))) or guess_col not in range(0,(len(board))):
                    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)
            if turn == 4:
                print("Game Over!")
                turn += 1
        playAgain = input("Play again? Y/N: ")
        if playAgain == 'Y' or playAgain == 'y':
            continue
        else:
            playAgain = False
            break
main()


#2

you can add a function called create_board, add your existing code which creates the board to this function. The only change you need to make, is to return board

then in the beginning of your loop, call the create_board function and store the returned result in board variable.


#3

Thank you, I made that change and it works but when the board is printed after the nested if/else, it is not formatted correctly. Any ideas?


#4

please post an updated version of your code

do you run the code in python3? It looks that way


#5

Yea I use python3.

# Written by Doc

from random import randint


def create_board():
    board = []
    for i in range(5):
        board.append(["O"] * 5)
    for row in board:
        print(" ".join(row))
    return board

# Lines 6 through 12 create the board and return it.

print("Let\'s play Battleship!")


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


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


def main():

    # Lines 22-27 and 45-46 set the location of the ship.

    playAgain = True
    while playAgain:
        board = create_board()
        for turn in range(1,5):
            print("Turn " + str(turn))

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

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

            print("The ship was at ", end='')
            print(ship_row, end=',')
            print(ship_col)

            if guess_row == ship_row and guess_col == ship_col:
                print("Congratulations! You sank my battleship!")
                break
            else:
                if guess_row not in range(0, (len(board))) or guess_col not in range(0, (len(board))):
                    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)
            if turn == 4:
                print("Game Over!")
            turn += 1
        playAgain = input("Play again? Y/N: ")
        if playAgain == 'Y' or playAgain == 'y':
            continue
        else:
            playAgain = False
            break
main()

#6

you shouldn't print the board directly, you should call the print_board function, the soul purpose of this function to print the board pretty


#7

Thank you, got it working. Just had to separate the second for loop in create board into a print board function like I had before.


#8

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