Skip to content
This repository was archived by the owner on Apr 24, 2025. It is now read-only.

Commit 61355c2

Browse files
committed
Add battleship cli game
1 parent 0c90614 commit 61355c2

2 files changed

Lines changed: 184 additions & 0 deletions

File tree

projects/Battleship/README.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Py-Battleship
2+
3+
[![License](https://img.shields.io/static/v1?label=License&message=GPL-3-0&color=blue&?style=plastic&logo=appveyor)](https://opensource.org/license/GPL-3-0)
4+
5+
## Table Of Content
6+
7+
- [Description](#description)
8+
- [Installation](#installation)
9+
- [Usage](#usage)
10+
- [GitHub](#github)
11+
- [License](#license)
12+
13+
14+
![GitHub repo size](https://img.shields.io/github/repo-size/robertlent/py_battleship?style=plastic)
15+
16+
![GitHub top language](https://img.shields.io/github/languages/top/robertlent/py_battleship?style=plastic)
17+
18+
19+
20+
## Description
21+
22+
Battleship is a Python command line game.
23+
24+
The player can choose the size of the grid, from 5x5 up to 15x15, and the ship will be randomly placed in that grid. The size of the grid also determines the number of turns the user gets, from 5 to 15.
25+
26+
The game handles incorrect entries and can be replayed repeatedly.
27+
28+
29+
30+
## Installation
31+
32+
Download main.py, change to the directory where you downloaded the file and run it using `python3 main.py`
33+
34+
Py-Battleship is built with the following tools and libraries: <ul><li>Python</li></ul>
35+
36+
37+
38+
## Usage
39+
40+
1. Enter 'yes' or 'y' to start a new game
41+
- Any input besides those two and 'no' or 'n' will be ignored
42+
2. You will be prompted to choose a number from 5 to 15, which sets the game board size and number of guesses to that number
43+
3. You will be prompted to choose a row number and then to choose a column number
44+
- If either guess is less than 5 or more than the previously provided maximum, you will be prompted to choose a valid selection
45+
- If you enter a row or column that you already guessed, you will be told such and you will have used a turn
46+
4. The game continues until you either make a correct guess or run out of guesses
47+
5. You will then be asked if you want to start a new game
48+
49+
50+
## GitHub
51+
52+
<a href="https://github.com/robertlent"><strong>robertlent</a></strong>
53+
54+
55+
## License
56+
57+
[![License](https://img.shields.io/static/v1?label=Licence&message=GPL-3-0&color=blue)](https://opensource.org/license/GPL-3-0)
58+
59+

projects/Battleship/main.py

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
import os
2+
from random import randint
3+
4+
board = []
5+
size = 5
6+
7+
8+
def new_game():
9+
global size
10+
os.system('cls' if os.name == 'nt' else 'clear')
11+
answer = input("Do you want to start a new game of Battleship? ").lower()
12+
13+
if answer not in ['yes', 'y', 'no', 'n']:
14+
new_game()
15+
else:
16+
if answer == 'yes' or answer == 'y':
17+
while True:
18+
try:
19+
os.system('cls' if os.name == 'nt' else 'clear')
20+
size = int(input(
21+
"Enter a number between 5 and 15.\n\nThis will determine how big the playing board is and how many turns you have to find the Battleship. (5 rows, 5 columns, 5 turns, etc.): "))
22+
if size not in range(5, 16):
23+
raise ValueError()
24+
except ValueError:
25+
print("You did not enter a number!")
26+
continue
27+
else:
28+
break
29+
30+
# Creates the playing board's size, based on the size chosen by the player.
31+
for x in range(0, size):
32+
board.append(["O"] * size)
33+
game()
34+
elif answer == 'no' or answer == 'n':
35+
os.system('cls' if os.name == 'nt' else 'clear')
36+
print("Thank you for playing!\n")
37+
input("Press the 'Enter' key to exit the game.")
38+
os.system('cls' if os.name == 'nt' else 'clear')
39+
quit()
40+
41+
42+
def print_board(board):
43+
for row in board:
44+
print(" ".join(row))
45+
46+
47+
def random_row(board):
48+
return randint(0, len(board) - 1)
49+
50+
51+
def random_col(board):
52+
return randint(0, len(board[0]) - 1)
53+
54+
55+
def game():
56+
global board
57+
os.system('cls' if os.name == 'nt' else 'clear')
58+
print(
59+
"Welcome to Battleship.\n\nA ship, one cell long, has been randomly placed on the below %dx%d grid.\nYou have %d turns to find it.\n" % (
60+
size, size, size))
61+
62+
# Randomly places Battleship
63+
ship_row = random_row(board)
64+
ship_col = random_col(board)
65+
66+
# The next two lines are for debugging purposes. They display the position of the battleship.
67+
# print(ship_row + 1)
68+
# print(ship_col + 1)
69+
70+
print_board(board)
71+
72+
# Give the user the amount of turns they chose, between 5 and 10.
73+
for turn in range(size):
74+
print("\nTurn", turn + 1, "of", size, "\n")
75+
76+
# Check if Guess Row and Column are numbers before continuing
77+
while True:
78+
try:
79+
guess_row = int(input("Guess Row: ")) - 1
80+
if guess_row not in range(0, size):
81+
raise ValueError()
82+
except ValueError:
83+
print("Enter a valid selection!")
84+
continue
85+
else:
86+
break
87+
88+
while True:
89+
try:
90+
guess_col = int(input("Guess Column: ")) - 1
91+
if guess_col not in range(0, size):
92+
raise ValueError()
93+
except ValueError:
94+
print("Enter a valid selection!")
95+
continue
96+
else:
97+
break
98+
99+
# Checks if Player wins
100+
if guess_row == ship_row and guess_col == ship_col:
101+
os.system('cls' if os.name == 'nt' else 'clear')
102+
input("Congratulations! You sank my battleship!\n\nPress enter to continue.")
103+
board = []
104+
new_game()
105+
break
106+
else: # Guesses are outside of playing field
107+
if (guess_row > size or guess_row < 0) or (guess_col > size or guess_col < 0):
108+
print("Oops, that's not even in the ocean.")
109+
# Player previously guessed their current guesses
110+
elif board[guess_row][guess_col] == "X":
111+
os.system('cls' if os.name == 'nt' else 'clear')
112+
print("You guessed that one already. Good job, you wasted a turn.\n")
113+
print_board(board)
114+
else: # User misses
115+
os.system('cls' if os.name == 'nt' else 'clear')
116+
print("Miss!\n")
117+
board[guess_row][guess_col] = "X"
118+
print_board(board)
119+
else:
120+
input("\nGame Over\n\nPress enter to continue.")
121+
board = []
122+
new_game()
123+
124+
125+
new_game()

0 commit comments

Comments
 (0)