Coders Packet

Battleship Game in Python

By NIKETH ANNAM

This tutorial will help you play and create a simple and small Battleship Game in Python. The only way to win the game is to find the position of the battleship in the given limited chances.

Let's see how to build this game using the Python code

First, we will import the required library

from random import randint

Now we will create a small board to start the game

board = []
for x in range(5):
  board.append(["O"] * 5)

def Board(board):
  for row in board:
    print((" ").join(row))
Board(board)

We will give the random position for the battleship using randint

battleship_row = randint(0,len(board)-1)
battleship_col = randint(0, len(board[0])-1)
battleship_position = battleship_row,battleship_col

Six chances will be given for the user to guess the position of the battleship

for chance in range(6):
  print(("Chances remaining"), 5-chance)
  position = input("Guess the position of battleship:")

If the input given by the user matches with the battleship position the user has won the game

if int(position[0]) == battleship_position[0] and int(position[2]) == battleship_position[1]:
  print("Congratulations! You sunk the opponent's battleship!")

Let us see the entire code of the game

from random import randint

board = []

for x in range(5):
  board.append(["O"] * 5)

def Board(board):
  for row in board:
    print((" ").join(row))

print("Welcome to the Battleship!")
Board(board)

battleship_row = randint(0,len(board)-1)
battleship_col = randint(0, len(board[0])-1)
battleship_position = battleship_row,battleship_col

for chance in range(6):
  print(("Chances remaining"), 5-chance)
  position = input("Guess the position of battleship:")

  if int(position[0]) == battleship_position[0] and int(position[2]) == battleship_position[1]:
    print("Congratulations! You sunk the opponent's battleship!")
    break
  else:
    if (int(position[0]) < 0 or int(position[0]) > 4) or (int(position[2]) < 0 or int(position[2]) > 4):
      print("Oops, that's out of bounds.")
    elif (board[int(position[0])][int(position[2])] == "X"):
      print("You guessed that one already.")
    else:
      print("You missed the battleship!")
      board[int(position[0])][int(position[2])] = "X"
  if chance == 5:
    print("GAME OVER")
    print("The position of the battleship is", battleship_position)
  Board(board)

 

Download Complete Code

Comments

No comments yet

Download Packet

Reviews Report

Submitted by NIKETH ANNAM (nikethannam)

Download packets of source code on Coders Packet