game battleships with gui in python

One way to create a Battleships game with a GUI in Python is to use the Pygame library. Here are the steps to follow:

  1. Install Pygame using pip:
main.py
pip install pygame
19 chars
2 lines
  1. Import the necessary modules:
main.py
import pygame
import random
28 chars
3 lines
  1. Initialize Pygame and set the display dimensions:
main.py
pygame.init()
width = 640
height = 480
screen = pygame.display.set_mode((width, height))
89 chars
5 lines
  1. Create the game board and draw it onto the screen:
main.py
board = [[0] * 10 for _ in range(10)]

for row in range(10):
    for col in range(10):
        pygame.draw.rect(screen, (255, 255, 255), (50 + col * 30, 50 + row * 30, 30, 30), 1)
180 chars
6 lines
  1. Add ships to the board:
main.py
ships = [3, 3, 2, 2, 2, 1, 1, 1, 1]
for i in range(len(ships)):
    placed = False
    while not placed:
        orientation = random.randint(0, 1)
        if orientation == 0:
            x = random.randint(0, 9 - ships[i])
            y = random.randint(0, 9)
            if all(board[y][x + j] == 0 for j in range(ships[i])):
                for j in range(ships[i]):
                    board[y][x + j] = i + 1
                placed = True
        else:
            x = random.randint(0, 9)
            y = random.randint(0, 9 - ships[i])
            if all(board[y + j][x] == 0 for j in range(ships[i])):
                for j in range(ships[i]):
                    board[y + j][x] = i + 1
                placed = True
727 chars
20 lines
  1. Create a loop that listens for user input:
main.py
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # Do something when the mouse is clicked
240 chars
8 lines
  1. Respond to user input to simulate gameplay:
main.py
    mouse_pos = pygame.mouse.get_pos()
    row = (mouse_pos[1] - 50) // 30
    col = (mouse_pos[0] - 50) // 30
    if row < 0 or row > 9 or col < 0 or col > 9:
        continue
    if board[row][col] == -1:
        continue
    if board[row][col] == 0:
        board[row][col] = -1
    else:
        board[row][col] = -2
321 chars
12 lines
  1. Update the screen in each iteration of the loop to show any changes:
main.py
    for row in range(10):
        for col in range(10):
            if board[row][col] == -1:
                pygame.draw.rect(screen, (0, 0, 255), (50 + col * 30, 50 + row * 30, 30, 30))
            elif board[row][col] == -2:
                pygame.draw.rect(screen, (255, 0, 0), (50 + col * 30, 50 + row * 30, 30, 30))
                
    pygame.display.update()
367 chars
9 lines

This code just implements the basic functionality of a Battleships game; you can add additional features and improve the GUI as desired.

related categories

gistlibby LogSnag