[Python] What is the best way to generate random ships in an array in Python?

Discussão em 'Python' iniciado por Stack, Agosto 22, 2025.

  1. Stack

    Stack Membro Participativo

    Recently, I've been working on a battleship game for my CS2 class. The focus of this project is to create a board game using arrays, and I decided to create a battleship. I have most of the code, but I cannot figure out how to get ships to get randomly generated on a 10x10 array without the ships being...

    • The wrong length
    • Looping around the array

    Below is the function I currently have.

    def createShips(board):
    shipLen = [5,4,3,3,2]
    shipAvailable = 5
    directionposibilities = ["vertical", "horizontal"]
    j = 0

    for i in range(shipAvailable):
    boatMade = False

    #REGULAR VAR STATMENTS
    direction = random.choice(directionposibilities)
    col = randint(0,9)
    row = randint(0,9)

    while boatMade == False:

    if direction == "vertical":
    buildCount = 0
    if col + int(shipLen) <= 11:
    collision = False
    for i in range(0, int(shipLen)):
    buildCount += 1
    if board[int(row-i)][int(col)-1] == "X":
    if collision:
    pass
    else:
    collision = True
    if collision:
    col = randint(0,9)
    row = randint(0,9)
    else:

    for j in range(buildCount):
    board[int(row-j)][int(col)-1] = "X"

    boatMade = True
    else:
    col = randint(0,9)
    row = randint(0,9)
    if direction == "horizontal":
    if col + int(shipLen) <= 10:
    collision = False
    buildCount = 0
    for i in range(0, int(shipLen)):
    buildCount += 1
    if board[int(row)][int(col)+i-1] == "X":
    if collision:
    pass
    else:
    collision = True
    if collision:
    col = randint(0,9)
    row = randint(0,9)
    else:

    for j in range(buildCount):
    board[int(row)][int(col)+j-1] = "X"
    boatMade = True
    else:
    col = randint(0,9)
    row = randint(0,9)
    shipAvailable = shipAvailable - 1

    return(board)

    board = [["■"] * 10 for x in range(10)]

    print(createShips(board))


    If you have any idea why this may not work please let me know!

    PS: I am using another function that prints the array nicely, if you would like that for convenience, it is seen below:

    def showBoard(board):
    print(" A B C D E F G H I J")
    print(" ------------------------------")

    rownumb = 1
    for r in board:
    if rownumb == 10:
    space = ""
    else:
    space = " "
    print("%d|%s|" % (rownumb, space + "|".join(r)))
    rownumb += 1

    Continue reading...

Compartilhe esta Página