HOMEWORK:
Finish your battleship project code. Here are the requirements for what it should be able to do:
Show the proper coordinate grid.
Show the number of turns remaining.
Accept user input.
Check if it is your nested list -- ships.
Either print "hit" or "miss".
End the program after five turns.
Extra features:
Don't allow duplicate guesses. For this, you'll need a nested list that appends each of the guesses. Then, check if every new guess is in this guess list (like checking against the ships list).
Handle out-of-bounds cases. For example, if the player guesses [6, 8], it should say their coordinates need to be from 0 to 4.
End before five turns if the player guesses all of the ships. Multiple approaches -- easiest one is to have a counter for ships found and check if that has reached a certain threshold.
RESOURCES: Class slides: https://docs.google.com/presentation/d/1r1J1ArzL7Xyv1ifIxuNHqwSwGNrpt7QUx3QM0W2IXCU/edit?usp=sharing Class code: https://replit.com/@ShravyaS/BattleshipGame#main.py
(This code is different from my answer key, so it doesn't include extra features/isn't the most organized. It's what we typed in class!)
Post your answers as a comment! Solutions will be up soon. 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.
Solution:
ships = [[0, 0], [2, 0], [3, 4], [1, 2]]
# grid = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [], [], []]
grid = []
for i in range(5):
row = []
for j in range(5):
row.append(0) # row = [0, 0, 0, 0, 0]
grid.append(row)
turns = 0
game = True
g = []
h=0
while game:
if h == 4:
print("you won")
break
turns += 1
print("Turn number: " + str(turns))
if turns >= 5:
game = False
for i in range(5):
for j in range(5):
print(grid[i][j], end=' ')
print("\n")
while 1:
b=False
x=input()
if x not in g:
g.append(x)
guess = x.split()
for i in range(len(guess)):
guess[i] = int(guess[i])
for i in guess:
if i > 4:
print("Pick numbers between 0 and 4")
else:
b = True
else:
print("You already guessed that")
print(g)
if b == True:
break
if guess in ships: # guess = [3, 3] guess[0] = 3 guess[1] = 3
grid[guess[0]][guess[1]] = 1
print("HIT!")
h+=1
else:
grid[guess[0]][guess[1]] = -1
print("MISS!")