here is a sample code that creates a gui for the battleship game using pyqt5 with logic of ship placement and checking if a ship was hit in python

Here is a sample code that uses PyQt5 for the Battleship game.

main.py
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QWidget, QLabel, QVBoxLayout, QHBoxLayout, QPushButton
)
from typing import Tuple


class Cell(QPushButton):
    def __init__(self, row: int, col: int):
        super().__init__()
        self.row = row
        self.col = col
        self.setFixedSize(40, 40)
        self.setStyleSheet("background-color: lightblue")


class BattleshipGUI(QWidget):
    def __init__(self):
        super().__init__()
        self.cells = []
        self.board = [[0] * 10 for _ in range(10)]

        main_layout = QVBoxLayout()

        board_layout = QHBoxLayout()
        board_layout.addStretch()
        for col in range(10):
            label = QLabel(chr(col + ord('A')))
            board_layout.addWidget(label, alignment=Qt.AlignmentFlag.AlignCenter)
        board_layout.addStretch()
        main_layout.addLayout(board_layout)

        for row in range(10):
            row_layout = QHBoxLayout()
            row_layout.addStretch()
            label = QLabel(str(row))
            row_layout.addWidget(label, alignment=Qt.AlignmentFlag.AlignCenter)
            for col in range(10):
                cell = Cell(row, col)
                cell.clicked.connect(self._handle_cell_clicked)
                row_layout.addWidget(cell)
                self.cells.append(cell)
                self.board[row][col] = 0
            row_layout.addStretch()
            main_layout.addLayout(row_layout)

        board_layout = QHBoxLayout()
        board_layout.addStretch()
        for col in range(10):
            label = QLabel(chr(col + ord('A')))
            board_layout.addWidget(label, alignment=Qt.AlignmentFlag.AlignCenter)
        board_layout.addStretch()
        main_layout.addLayout(board_layout)

        self.setLayout(main_layout)

    def _handle_cell_clicked(self):
        cell = self.sender()
        if self.board[cell.row][cell.col] == 1:
            cell.setStyleSheet("background-color: red")
        else:
            cell.setStyleSheet("background-color: white")


if __name__ == "__main__":
    app = QApplication([])
    gui = BattleshipGUI()
    gui.show()
    app.exec()
2178 chars
70 lines

This code creates a GUI with 10x10 grid of cells that represent the board of Battleship game. When a cell is clicked, the code checks if there is a ship in that cell and updates the background color to red if a ship was hit or white if not.

Note that the code only implements the GUI part of the game, but you can add the logic of ship placement and hit checking separately.

related categories

gistlibby LogSnag