HOMEWORK:

Finish adding all the bonus features to your Battleship game if you haven't already

Generate a 4-by-4 nested list with random integers from 1 to 16 inclusive, and print them in a grid format

Use the random module to generate random ships for your Battleship game. Look at the slides from class for more details.

RESOURCES:

Class slides: https://docs.google.com/presentation/d/1iMDChZz-abSDTKaH1ainjqJsDMvZeOb2BJ7Q1baeXFE/edit?

Battleship code: https://replit.com/join/hlutbjbnyh-shravyas

Example code: https://replit.com/join/butpfsjykv-shravyas

Coding platform: replit.com

Post your answers as a comment! I will post the solution before next class.

You can always email us at shravyassathish@gmail.com (mentor) or kingericwu@gmail.com (TA) or message us on Discord if you have any questions about the homework or what we covered in class.

#2:

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

import random

for i in range(0, 4):

for j in range(0, 4):

a = random.choice(list1)

print(str(a) + "\t", end="")

print("\n")

import random

ships = []

for i in range(3):

coordinate = []

for j in range(2):

coordinate.append(random.randint(0, 4))

ships.append(coordinate)

shipsFound = []

guessList = []

grid = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

game = True

turns = 5

while game:

print("Turns left: " + str(turns))

guess = input("Make your guess (row column): ").split()

for i in range(len(guess)):

guess[i] = int(guess[i])

while guess in guessList or guess[0] > 4 or guess[1] > 4:

print("Invalid guess, try again.")

guess = input("Make your guess: ").split()

for i in range(len(guess)):

guess[i] = int(guess[i])

guessList.append(guess)

if guess in ships:

grid[guess[0]][guess[1]] = 1

print("Hit\n")

shipsFound.append(guess)

else:

grid[guess[0]][guess[1]] = "X"

print("Miss\n")

for i in grid:

for j in i:

print(j, end=' ')

print("\n")

found = True

for i in ships:

if i not in shipsFound:

found = False

if found == True:

print("YOU WIN!")

game = False

turns -= 1

if turns <= 0:

print("GAME OVER!")

print(f'The ships were at {ships}.')

game = False