Sure, I can help you with that! Here is a Python script for the game of Battleships, using the libraries simple-term-menu, pyfiglet, and termcolor. The code is structured across multiple files to make it easier to edit and manage. The game offers three modes of play: Singleplayer, Bot, and Local two-player. The Singleplayer mode includes ships and mines, and the game can be played at different difficulties.
Here is the code for the game:
main.py:
import os
import random
from menu import Menu
from game import Game
def clear_screen():
os.system('cls' if os.name == 'nt' else 'clear')
if __name__ == '__main__':
menu_items = [
'Singleplayer',
'Bot',
'Local two-player',
'Exit'
]
menu = Menu('Battleships', menu_items)
while True:
clear_screen()
menu.show()
if menu.selected_item == 'Exit':
break
game = Game(menu.selected_item)
game.play()
menu.py:
from simple_term_menu import TerminalMenu
from termcolor import colored
class Menu:
def __init__(self, title, items):
self.title = title
self.items = items
self.menu = TerminalMenu(self.items, title=self.title)
def show(self):
print(colored('='*20, 'green'))
print(colored(self.title, 'yellow'))
print(colored('='*20, 'green'))
self.menu.show()
@property
def selected_item(self):
return self.items[self.menu.selected_option]
game.py:
import os
import random
from pyfiglet import Figlet
from termcolor import colored
class Game:
SHIP = 'S'
MINE = 'M'
EMPTY = '-'
HIT = 'X'
MISS = 'O'
SHIP_LENGTHS = [5, 4, 3, 3, 2]
MAX_DIFFICULTY = len(SHIP_LENGTHS)
ROW_LABELS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
COL_LABELS = '0123456789'
def __init__(self, game_type):
self.game_type = game_type
if self.game_type == 'Singleplayer':
self.difficulty = self.select_difficulty()
self.grid_size = 10
else:
self.grid_size = self.select_grid_size()
self.grid1 = self.create_grid()
self.grid2 = self.create_grid()
self.f = Figlet(font='slant')
self.turn = 1
def select_difficulty(self):
options = [f'Difficulty {i+1}' for i in range(self.MAX_DIFFICULTY)]
menu = TerminalMenu(options, title='Select difficulty')
menu.show()
return menu.selected_option + 1
def select_grid_size(self):
menu = TerminalMenu(['Small', 'Medium', 'Large'], title='Select grid size')
menu.show()
if menu.selected_option == 0:
return 6
elif menu.selected_option == 1:
return 8
elif menu.selected_option == 2:
return 10
def create_grid(self):
grid = []
for i in range(self.grid_size):
row = []
for j in range(self.grid_size):
row.append(self.EMPTY)
grid.append(row)
return grid
def place_ships(self, grid):
for length in self.SHIP_LENGTHS:
while True:
x