0% found this document useful (0 votes)
139 views

Battleships in Python

This document contains code for a battleships game between two players. It randomly generates and places ships on each player's 10x10 board without showing ship locations. Players take turns attacking each other's boards by guessing row and column coordinates until all ships are sunk. The code tracks hits, misses, remaining ships, and declares a winner when one player sinks all opponent ships.

Uploaded by

Henry Dennis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
139 views

Battleships in Python

This document contains code for a battleships game between two players. It randomly generates and places ships on each player's 10x10 board without showing ship locations. Players take turns attacking each other's boards by guessing row and column coordinates until all ships are sunk. The code tracks hits, misses, remaining ships, and declares a winner when one player sinks all opponent ships.

Uploaded by

Henry Dennis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

from random import randint

from time import sleep

print("\nwelcome to battleships!\n")
print("Both players have a 10x10 board filled with randomly positioned ships,
neither players know where")
print("the ships are and have to guess where the other persons ships are unitl they
are all destroyed.\n\n")
p1Board = []
p2Board = []
p1ships = {}
p2ships = {}

# using y, x for the board


for i in range(7):
p1Board.append((["."] * 7))
p2Board.append((["."] * 7))

def printBoard(board):
temp1 = []
for stuff in range(len(board)):
temp1.append(board[stuff])
temp = []
for i in range(len(temp1[0])):
temp.append(str((i+1)))
temp1.insert(0, temp)
for i in range(len(temp1)):
if i < 10:
temp1[i].insert(0, str(i) + " ")
else:
temp1[i].insert(0, str(i))
for row in temp1:
print(" ".join(row))

def BuildShipList(board, dictionary):


for i in range(5):
for num in range(i + 1):
size = 5 - i
if size == 5:
name = "Carrier" + str(num + 1)
elif size == 4:
name = "Battleship" + str(num + 1)
elif size == 3:
name = "Cruiser" + str(num + 1)
elif size == 2:
name = "Submarine" + str(num + 1)
#elif size == 1:
# name = "Destroyer" + str(num + 1)
complete = False
while complete is False:
complete = True
x = randint(0, len(board[0]))
y = randint(0, len(board))
ship = []
for seg in range(size):
if x in range(len(board[0])) and y in range(len(board)):
ship.append([y, x])
if num % 2 == 0:
x += 1
else:
y += 1
else:
complete = False
for object in dictionary:
for cord in dictionary[object]:
for pos in ship:
if cord == pos:
complete = False
dictionary[name] = ship
return dictionary

p1ships = BuildShipList(p1Board, p1ships)


p2ships = BuildShipList(p2Board, p2ships)

def listShips(ships):
for x, y in ships.items():
print(x, y)

player1 = input("Enter name for player1: ")


player2 = input("Enter name for player2: ")
print("")
p1items = [p1ships, p1Board]
p2items = [p2ships, p2Board]
allItems = [p1items, p2items]
counter = 1

def LoseCondition(ships):
shipnum = 0
for ship in ships:
shipnum += 1
if shipnum == 0:
return True

def checkhit(ships, attack):


for name, poslist in ships.items():
for pos in poslist:
if pos == attack:
print(name)
return True, name
return False, "null"

def editBoard(turn, inverse, attack):


global allItems
hit, ship = checkhit(allItems[inverse][0], attack)
if hit:
# shipCords = allItems[inverse][0][ship]
# board = allItems[turn][1]
for pos in allItems[inverse][0][ship]:
allItems[turn][1][pos[0]][pos[1]] = "H"
allItems[turn][1][attack[0]][attack[1]] = "X"
del allItems[inverse][0][ship]
print("We've hit %s!" % ship)
else:
print("We have missed all of the oppponents ships!")
allItems[turn][1][attack[0]][attack[1]] = "M"
print("")
sleep(1)

StillGame = True
while StillGame:
counter += 1
if counter % 2 == 0:
turn = 0
inverse = 1
name = player1
iname = player2
else:
turn = 1
inverse = 0
name = player2
iname = player1

if LoseCondition(allItems[turn][0]):
print("Oh no {0} you have lost all 15 of your ships and {1} has won! How
could you let this happen!")
break
print("Attack: {0} :: {1} This is your board and where you have
attacked".format(counter-1, name))
print("{0} has {1} ships Left!\n".format(iname, len(allItems[inverse][0])))
sleep(1)
printBoard(allItems[turn][1])

for row in allItems[turn][1]:


row.pop(0)

print("\n")
#listShips(allItems[inverse][0])
var1 = True
attac = []
attac.append(int(input("Please enter row number(1 - 10): ")) - 1)
attac.append(int(input("Please enter column number(1 - 10): ")) - 1)
if 0 <= attac[0] <= 9 and 0 <= attac[1] <= 9:
pass
else:
print("You have to enter a number between 1 and 10")
attac = []
attac.append(int(input("Please enter row number(1 - 10): ")) - 1)
attac.append(int(input("Please enter column number(1 - 10): ")) - 1)
editBoard(turn, inverse, attac)

You might also like