Battleship Game Code in Python

Battleship Game Code in Python

Introduction

Hello friends, in this tutorial we are going to create a Battleship Game Code in Python. This project is not beginner friendly for python learners who just started learning python. But as we are providing the comments and a detailed explanation of the code you may find it easy to understand the python code. So watch the tutorial till the end.

This game is the single-player battleship code written in Python programming language. In this source code of the battleship game in python, we have made used grids. This grid consists of 7 rows and 7 columns of the battleship where you can destroy and sink the ships.

This battleship game written in python is really interesting and challenging.  The python learners must try this and get the code executed on the online compiler or you can execute it on the Pycharm IDE terminal which I have used.

You can click here to copy code directly for the battleship game in python.

Let’s begin to understand the code for the python battleship game in detail

Import the module

#Import randint function from random module
from random import randint

The random module is used in which we are importing the randint function which randomly selects the values from the given range.

Defining the patterns

Hidden_Pattern=[[' ']*8 for x in range(8)]
Guess_Pattern=[[' ']*8 for x in range(8)]

let_to_num={'A':0,'B':1, 'C':2,'D':3,'E':4,'F':5,'G':6,'H':7}

In this block of code, we are defining two patterns of size 8 each one pattern that is hidden and another one is the guessed pattern.

The letter to numbers is the dictionary which is enclosed in curly braces which is the form of key-value pair.

Function for printing the board

#Function is defined to print the board of battleship
def print_board(board):
    print(' A B C D E F G H')
    print(' ***************')
    row_num=1
    for row in board:
        print("%d|%s|" % (row_num, "|".join(row)))
        row_num +=1

Here in this piece of code, we are creating a function for printing the board for the battleship game where we are providing 2 print functions for printing the column from A – H  and printing the row number and  “|” symbol for each row on the board.

Function for getting the ship location for hitting the ship in the Battleship Game Code in Python

def get_ship_location():
    #Enter the row number between 1 to 8
    row=input('Please enter a ship row 1-8').upper()

    while row not in '12345678':
        print("Please enter a valid row")
        row=input('Please enter a ship row 1-8')
    #Enter the Ship column from A TO H

    column=input('Please enter a ship column A-H').upper()
    while column not in 'ABCDEFGH':
        print("Please enter a valid column")
        column=input('Please enter a ship column A-H')
    return int(row)-1,let_to_num[column]

In this code block, we are defining the function of the ship’s location. Here we have defined the row and column variable to take the values of the row and the column where we have defined the while loops. In the first while loop, while the row values are not in the range of 1 to 8, It will ask for a valid row number. Similarly with the column. While the value of the column is not in the range of A – H. It will ask to enter a valid column. The return function returns the row less by 1 than the value provided and let_to_num[column].

The function defined for creating the ships

#Function that creates the ships
def create_ships(board):
    for ship in range(5):
        ship_r, ship_cl=randint(0,7), randint(0,7)
        while board[ship_r][ship_cl] =='X':
            ship_r, ship_cl = randint(0, 7), randint(0, 7)
        board[ship_r][ship_cl] = 'X'

Here we have defined the function create ships. The for loop function creates 5 ships where the ship_r is the shipping row and ship_cl is the ship column, the randint(0,7) function randomly assigns the values to the ship’s row and column. In the while loop, the function continues until the boards ship_r and ship_cl == ‘X’, The ship row and ship column values get the random values. The board will get the values ‘X’ once the hidden pattern and guess pattern hits the same ship.

Function for counting the hit ships

def count_hit_ships(board):
    count=0
    for row in board:
        for column in row:
            if column=='X':
                count+=1
    return count

In this piece of code, we have defined a function count_hit_ships. The count is assigned to 0. Here for each row on the board and each column in the row if the column ==’X’ the count increases by 1 and returns the count. This function counts the number of ships hit and sunk.

Code for running the battleship code in python

create_ships(Hidden_Pattern)
#print_board(Hidden_Pattern)
turns = 10
while turns > 0:
    print('Welcome to Battleship')
    print_board(Guess_Pattern)
    row,column =get_ship_location()
    if Guess_Pattern[row][column] == '-':
        print(' You already guessed that')
    elif Hidden_Pattern[row][column] =='X':
        print(' Congratulations you have hit the battleship')
        Guess_Pattern[row][column] = 'X'
        turns -= 1
    else:
        print('Sorry,You missed')
        Guess_Pattern[row][column] = '-'
        turns -= 1
    if  count_hit_ships(Guess_Pattern) == 5:
        print("Congratulations you have sunk all the battleships")
        break
    print(' You have ' +str(turns) + 'turns remaining')
    if turns == 0:
        print('Game Over')
        break

In this code block, we are calling the function create_ship that creates the ship. The turns variable is assigned to 10. While the turns > 0 The user can continue to hit the ships.  The print_board (Guess_Pattern) creates the guess_pattern board. The row and column values get the values for the location of the ships.

Here if the guess_pattern == ‘-‘  then it prints “You have already guessed”. If the hidden patterns Hidden_Pattern[row][column] == ‘X’: then it prints ‘ Congratulations you have hit the battleship’  the turns count is decreased by 1 else it prints “’Sorry, You missed‘ . If the count_hit_ships and the guess_pattern are exactly same i.e 5 then it will print “Congratulations you have sunk all the battleships” Once the turns value becomes zero the program will print “ Game over”.

Complete source code for Battleship Game Code in Python

#Random module for randomly accepting the values
# ‘X’ indicates the ships hit
# ‘-‘ indicates the hits missed
from random import randint

Hidden_Pattern=[[' ']*8 for x in range(8)]
Guess_Pattern=[[' ']*8 for x in range(8)]

let_to_num={'A':0,'B':1, 'C':2,'D':3,'E':4,'F':5,'G':6,'H':7}

def print_board(board):
    print(' A B C D E F G H')
    print(' ***************')
    row_num=1
    for row in board:
        print("%d|%s|" % (row_num, "|".join(row)))
        row_num +=1

def get_ship_location():
    #Enter the row number between 1 to 8
    row=input('Please enter a ship row 1-8 ').upper()
    while row not in '12345678':
        print("Please enter a valid row ")
        row=input('Please enter a ship row 1-8 ')
    #Enter the Ship column from A TO H
    column=input('Please enter a ship column A-H ').upper()
    while column not in 'ABCDEFGH':
        print("Please enter a valid column ")
        column=input('Please enter a ship column A-H ')
    return int(row)-1,let_to_num[column]

#Function that creates the ships
def create_ships(board):
    for ship in range(5):
        ship_r, ship_cl=randint(0,7), randint(0,7)
        while board[ship_r][ship_cl] =='X':
            ship_r, ship_cl = randint(0, 7), randint(0, 7)
        board[ship_r][ship_cl] = 'X'



def count_hit_ships(board):
    count=0
    for row in board:
        for column in row:
            if column=='X':
                count+=1
    return count

create_ships(Hidden_Pattern)
#print_board(Hidden_Pattern)
turns = 10
while turns > 0:
    print('Welcome to Battleship')
    print_board(Guess_Pattern)
    row,column =get_ship_location()
    if Guess_Pattern[row][column] == '-':
        print(' You already guessed that ')
    elif Hidden_Pattern[row][column] =='X':
        print(' Congratulations you have hit the battleship ')
        Guess_Pattern[row][column] = 'X'
        turns -= 1
    else:
        print('Sorry,You missed')
        Guess_Pattern[row][column] = '-'
        turns -= 1
    if  count_hit_ships(Guess_Pattern) == 5:
        print("Congratulations you have sunk all the battleships ")
        break
    print(' You have ' +str(turns) + ' turns remaining ')
    if turns == 0:
        print('Game Over ')
        break

Output:

Output, when the ships are not sunk, lose the game

Output 1 for battleship code in python
Output 1 for battleship code in python

Output, when all the ships are sunk, wins the game

Output 2 for battleship code in python
Output 2 for Battleship Game Code in Python

Conclusion

Hence, here we successfully completed the Battleship Game Code in Python. Everyone must try this code. Hope you find this tutorial on the python program of battleship game useful.

For more programs on python please keep visiting our website copyassignment.com

Thank you for reading battleship game python.

Keep Learning, Keep Coding


Also Read:

  • Sequel Programming Languages(SQL)
    In this article, we are going to learn about Sequel Programming Languages(SQL). Big enterprises like Facebook, Instagram, and LinkedIn, use SQL for storing the data in the back-end. So, If you want to get a job in the field of data, then it is the most important query language to learn. Before getting started, let…
  • Run Python Code, Install Libraries, Create a Virtual Environment | VS Code
    Visual Studio Code is one of the most efficient code compilers/interpreters. It is very promising because of the vast and widely available go-to extensions that help programmers. This article is an elaborative detail about how we can run Python code, install Python libraries, and create a virtual environment in Visual Studio Code. Write and Run…
  • Calendar using Java with best examples
    In this article, we are going to learn how to code Calendar using Java. The calendar application is occasionally asked in interviews to be built by the candidate. If you are intermediate in Java, it helps to improve your coding skills also, it is interesting to make this application. Let’s get started! Calendar class in…
  • How to make a Process Monitor in Python?
    In this article, we will build an application, Process Monitor in python using psutil. Python has a wide range of libraries and packages, which makes it the best choice for many developers. In the same way, we are going to make use of the psutil package to build our application, Process Monitor in Python. What…
  • C++ Array Assignment
    Today, we will learn C++ Array Assignment. We can assign multiple values to C++ Arrays. There are many ways you can initialize a C++ array. You can create different datatypes of arrays in C++ e.g. string, int, etc are the two most common types of C++ arrays that are commonly used. Today, we will see…
  • Employee Management System Project in Java
    Introduction We are going to develop an Employee Management System Project in Java. This project is great for those who are at an intermediate level and want to advance their coding skills. We will be creating a GUI interface using the swing package. This will be a GUI-based program with MySQL as a database. Administrators…
  • NxNxN Matrix in Python 3
    A 3d matrix(NxNxN) can be created in Python using lists or NumPy. Numpy provides us with an easier and more efficient way of creating and handling 3d matrices. We will look at the different operations we can provide on a 3d matrix i.e. NxNxN Matrix in Python 3 using NumPy. Create an NxNxN Matrix in…
  • Calculator Program in Python | On Different IDEs
    Welcome to copyassignment.com. In this tutorial, we are going to write a simple Calculator Program in Python and run it on different IDEs of python for creating a calculator we are using the mathematical operators, functions, conditional statements, and handling of user input to create our calculator. In this tutorial, we are going to see…
  • Naive Bayes in Machine Learning
    In the Machine Learning series, following a bunch of articles, in this article, we are going to learn about the Naive Bayes Algorithm in detail. This algorithm is simple as well as efficient in most cases. Before starting with the algorithm get a quick overview of other machine learning algorithms. What is Naive Bayes? Naive Bayes…
  • Lee Algorithm in Python | Solution to Maze Routing Problem in Python
    Introduction Definition: The Lee algorithm is one feasible solution for maze routing problems based on a breadth-first search. It always gives an optimal solution, if one exists, but is slow and requires considerable memory. We will learn Lee Algorithm in Python by Solution to Maze Routing Problem. The Lee algorithm has the properties of a)…
Share:
Avatar of pranjal dev

Author: pranjal dev