pyqt5 gui battleship code in python

Here's an example of a simple PyQt5 Battleship game. This game features a 10x10 grid where you can place your ships and try to sink the opponent's ships.

main.py
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QGridLayout, QWidget


class Battleship(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Battleship")

        # Create 10x10 grid for player1's board
        self.grid_layout1 = QGridLayout()
        self.grid_layout1.setSpacing(0)
        self.grid_layout1.setContentsMargins(0, 0, 0, 0)
        self.board1 = QWidget()
        self.board1.setLayout(self.grid_layout1)
        for i in range(10):
            for j in range(10):
                button = QPushButton()
                button.setObjectName(f"1_{i}_{j}")  # object name format: "player_row_col"
                button.setFixedSize(40, 40)
                self.grid_layout1.addWidget(button, i, j)

        # Create 10x10 grid for player2's board
        self.grid_layout2 = QGridLayout()
        self.grid_layout2.setSpacing(0)
        self.grid_layout2.setContentsMargins(0, 0, 0, 0)
        self.board2 = QWidget()
        self.board2.setLayout(self.grid_layout2)
        for i in range(10):
            for j in range(10):
                button = QPushButton()
                button.setObjectName(f"2_{i}_{j}")
                button.setFixedSize(40, 40)
                self.grid_layout2.addWidget(button, i, j)

        # Set up main window layout
        central_widget = QWidget()
        central_layout = QGridLayout()
        central_layout.setSpacing(20)
        central_widget.setLayout(central_layout)
        central_layout.addWidget(self.board1, 0, 0)
        central_layout.addWidget(self.board2, 0, 1)
        self.setCentralWidget(central_widget)

    def play(self):
        self.show()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    game = Battleship()
    game.play()
    sys.exit(app.exec_())
1825 chars
54 lines

This is just the basic layout of the game. You will still need to add the logic for placing and moving ships, shooting missiles, and detecting hits and misses.

related categories

gistlibby LogSnag