Battleship programacion ayuda help

# Packages
from random import randint

# Creating the board 
def create_board(Rows, Columns): 
    board = []
    for row in range(Rows):
        row = []
        for col in range(Columns):
            row.append(' ')
        board.append(row)
    return board

#Format of the board
def display_board(board):
    column_names = []
    for column in range(len(board[0])):
        column_names.append(str(column))
    print('  | ' + ' | '.join(column_names) + ' |')
    for number, row in enumerate(board):
        print(number, '| ' + ' | '.join(row) + ' |')


# Define battleships 
class Battleships(object):
    @staticmethod
    def build(coordinate, length, direction):
        body = []
        for i in range(length):
            if direction == "N":
                el = (coordinate[0], coordinate[1] - i)
            elif direction == "S":
                el = (coordinate[0], coordinate[1] + i)
            elif direction == "W":
                el = (coordinate[0] - i, coordinate[1])
            elif direction == "E":
                el = (coordinate[0] + i , coordinate[1])
            body.append(el)
        return Battleships(body)
    def __init__(self,body):
        self.body = body
        # [False, False, True, False]
        self.hits = [False] * len(body)
    def body_index(self, location):
        try:
            return self.body.index(location)
        except ValueError:
            return None
    def is_destroyed(self):
        return all(self.hits)

# Define shots
class Shot(object):
    def __init__(self, location, is_hit):
        self.location = location
        self.is_hit = is_hit

# Define a game
class GameBoard(object):
    def __init__(self, battleships, board_width, board_height):
        self.battleships = battleships
        self.shots = []
        self.board_width = board_width
        self.board_height = board_height
    def take_shot(self, shot_location): 
        is_hit = False
        for b in self.battleships:
            idx = b.body_index(shot_location)
            if idx is not None:
                is_hit = True
                b.hits[idx] = True
                break 
        self.shots.append(Shot(shot_location, is_hit))
    def is_game_over(self):
        return all([b.is_destroyed() for b in self.battleships])
        for b in self.battleships:
            if b.is_destroyed():
                return False
        return True 


##############################

#Game Start
username = input("What is your name?: ")
print("welcome to the game",username)

# Specifying the size of the board
Rows = int(input("Please enter the number of rows you want. \n"))
Columns = int(input("Please enter the number of columns you want. \n"))

boardPlayer = create_board(Rows,Columns)
boardCPU = create_board(Rows,Columns)
print("Your board")
display_board(boardPlayer)
print("CPU's board")
display_board(boardCPU)


# Storing the coordinates of your ships
print("There are 3 battleships you can set.")
print("There are 3 battleships you can set: Battleship 1 is 2 units, Battleship 2 is 3 units, and Battleship 3 is 5 units long.")
print("Specify their starting coordinates and direction:")
BattleshipsPlayer = [
    Battleships.build((int(input("Battleship 1 Row ")),int(input("Battleship 1 Columns "))), 2, input("N?S?E?W?")),
    Battleships.build((int(input("Battleship 2 Row ")),int(input("Battleship 2 Columns "))), 3, input("N?S?E?W?")),
    Battleships.build((int(input("Battleship 3 Row ")),int(input("Battleship 3 Columns "))), 5, input("N?S?E?W?"))
]
game_boardPlayer = GameBoard(BattleshipsPlayer, Rows, Columns)


# Coordinates of the CPU's battleship
BattleshipsCPU = [
    Battleships.build((randint(1,Columns-1),randint(0,Columns-1)), 2, "N"),
    Battleships.build((randint(2,Columns-1),randint(0,Columns-1)), 3, "N"),
    Battleships.build((randint(0,Columns-6),randint(0,Columns-1)), 5, "S")
]
game_boardCPU = GameBoard(BattleshipsCPU, Rows, Columns)


#Shooting the ships   
print("let's start")
while True:
    print("Your turn")
    x = int(input("Guess Row:"))
    y = int(input("Guess Column:"))
    game_boardCPU.take_shot((x,y))
    boardCPU[x][y]="X"
    display_board(boardCPU)
    if game_boardCPU.is_game_over():
        print("YOU WIN!")
        break
    else:
        print("CPU turn")
        a = randint(0,8)
        b = randint(0,8)
        game_boardPlayer.take_shot((a,b))
        boardPlayer[a][b]="X"
        display_board(boardPlayer)
        if game_boardPlayer.is_game_over():
            print("YOU LOSE!")
            break


Hola soy muy nueva en phyton y necesito agregar cuando una nave ha recibido un hit o miss en este codigo, muchas gracias por cualquier ayuda

1 Like

Esta muy bueno y el hecho de que seas nueva en python y arribar este juego, demuestra que te gusta programar. Ahora, el codigo no puedo entenderlo porque no se como se juega battleship.

Con este video entendi mejor, y creo que puede serte util, para conceptualizar la idea un poco mejor y ver que puedes o tienes ya en funcionamiento en el codigo. Luego, creo que lo que puedes hacer es crear un metodo que informe, segun sea el CPU o el jugador, luego de disparar, si fallo o no. Esto lo harás comparando la posicion de la nave enemiga, dependiendo del jugador o CPU, y la del disparo. Esto te servirá para fortalecer el juego del CPU, ya que será un poco más dinamico su juego