How to give the player the ability to choose a grid in Battleship?

57 views Asked by At

I am making a battleship project from scratch. What would be a way to identify a specific point on the map, and let you choose it, and then print out the chosen grid, with the "#" replaced with something else like a "X"?

Here's the code:

turns = 10
alphabet = ["A","B","C","D","E","F","G","H","I","J","a","b","c","d","e","f","g","h","i","j"]

def StartScreen():
    print("Welcome to Battleship!")
    print('''
        1. Start
        2. Exit
    ''')
    choice = int(input("Enter your number: "))
    if choice == 1:
        GameScreen()
    elif choice == 2:
        exit()
    else:
        print("Please choose a valid number.")
        StartScreen()

def GameScreen():
    print("\n")
    print("   A  B  C  D  E  F  G  H  I  J")
    row = [" # ", "# ", "# ", "# ", "# ", "# ", "# ", "# ", "# ", "# "]
    i = -1
    while i != 9:
        print(i+1, row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9])
        i = i + 1
    print("\n")
    rowx = input("Choose a letter(A-J): ")
    rowy = int(input("Enter a number(0-9): "))
    if rowx in alphabet and rowy in range(0,10):
        print(f'you chose {rowx.upper()}{rowy}')
    else:
        print("Please choose a valid point(A-J/0-9)\n")
        StartScreen()
2

There are 2 answers

0
lafinur On

It would be better for you to set your board in a different way. So far you have a unique list, row, which you print ten times to simulate a board. This will make it uncomfortable to keep track of changes, as you whish to do. Use a 2d list instead:

board = [[" # ", "# ", "# ", "# ", "# ", "# ", "# ", "# ", "# ", "# "],
       [" # ", "# ", "# ", "# ", "# ", "# ", "# ", "# ", "# ", "# "],
       ...
       ]

Of course, you can generate this board automatically:

board = [["#" for _ in range(10)] for _ in range(10)]

Then you can ask for two integers as input, call them i and j, and set board[i][j] = "X". This will produce the desired result.

0
J. Kadditz On

To manage and print the grid you'll want to use a 2d list. Additionally you should store the battleship alphabet as one string instead of a list of characters, and you don't need to be case specific. Also you should take input 1-10 and not 0-9 because the game uses 1-10 and not 0-9 like normal list indices.

turns = 10
alphabet = "ABCDEFGHIJ"

def create_grid():
    return [[" # " for _ in range(10)] for _ in range(10)]

def print_grid(grid):
    print("   " + "  ".join(alphabet))
    for i, row in enumerate(grid, start=1):
        print(f"{i: >2} " + "".join(row))
    print("\n")

def get_user_choice():
    rowx = input("Choose a letter (A-J): ").upper()
    rowy = input("Enter a number (1-10): ")
    return rowx, rowy

def is_valid_choice(rowx, rowy):
    return rowx in alphabet and rowy.isdigit() and 1 <= int(rowy) <= 10

def update_grid(grid, rowx, rowy):
    x = alphabet.index(rowx)
    y = int(rowy) - 1  # Adjust for 0-indexed grid
    if grid[y][x] == " # ":
        grid[y][x] = " X "
        return True
    return False

def game_screen():
    grid = create_grid()
    print_grid(grid)
    while True:
        rowx, rowy = get_user_choice()
        if is_valid_choice(rowx, rowy) and update_grid(grid, rowx, rowy):
            print(f"You chose {rowx}{rowy}")
            print_grid(grid)
        else:
            print("Please choose a valid point (A-J/1-10) or an unchosen cell.\n")

game_screen()