greatdonut greatdonut - 5 months ago 23
Python Question

List Problems in 1 Dimensional Python Battleship

I'm just starting to learn python and have come across some trouble when trying to program a simple 1-D version of single player battleship.

2 things I can't seem to make work:


  1. I have a created a 1 dimensional list (which is the gameplay board), but need to display/print the indices of the repeating element of the list. In other words, how can I print a list that only shows the indices of the elements in my board?

  2. I want to replace a that element with a "*" if it was a wrong guess. For example, if I wrongly guess the position as 4 in a board of 5 elements, I want to display:

    1 2 3 * 5



Moreover, I want to display the winning hit as an "X":

1 2 X * 5


Here's my current code:

from random import randint

ship=randint(0, 5)
board = ["O","O","O","O","O"]

print ("Let's play Battleship!")

attempts = 1
while attempts < 4:
print (board)
guess = int(input("Guess Where My Ship Is: "))
if guess == ship:
print ("Congratulations Captain, you sunk my battleship!")
break
else:
print ("You missed my battleship!")
if attempts<3:
print("Try again!")
elif attempts==3:
print("Better luck next time, Captain!")

attempts+=1


Thank you and apologies for the lame question.

Answer

Good practice: set the board size to a variable so you can reference it regularly. Put this at the top

size = 5 # Can be changed later if you want to make the board bigger

Next, have your ship location be chosen based on that

ship = randint(0, size)

Instead of making a board filled with 0's, Generate the board dynamically so that it's already pre-populated with the possible values.

board = [] # Creating an empty board
for i in range(1, size):
  position = str(i) # Converting integers to strings
  board.append(position) # Adding those items to the board 

Then, inside of the game logic, after the "You missed my battleship" line, change the relevant square on the board

...
print("You missed my battleship!")
number_guess = int(guess) - 1 # Because lists are zero-indexed
board[number_guess] = "*" # Assign "*" to the spot that was guessed
if attempts < 3:
    ...
Comments