Battleships Program


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

This my python code for a battleships game that is for a school project. I need to have two ships. One must have a length of 3 and must be horizontal and the other has to have a length of 5 and vertical. I haven’t been learning python for long. Any help is appreciated.

<In what way does your code behave incorrectly? Include ALL error messages.>

<What do you expect to happen instead?>

```python
import random
store = []
for x in range(9):
    store.append(random.randint (0 , 8))
for y in range(9):
    store.append(random.randint (0 , 8))
                                 
#Setup Global Variables------------------

torpedos = 30
theSea = [["_" for i in range(9)] for j in range(9)] #2D list 9x9
theSea[x][y] = "S" #Place the ship in position x,y
ships = 2 #How many ships to find

#Define procedures and functions --------------------------------

def displayGrid():
    print()
    print("  1  2  3  4  5  6  7  8  9  ") #display column headings
    for y in range(0,9):
        print((y+1), " " , end="") #print without new line
        for x in range(0,9):
            if (theSea[x][y] =="S"):
                print("_", " " , end="") #hide the ship
            else:
                print(theSea[x][y] , " " , end="") #print contents of array
        print() #next line
    print()

#begin main thread -------------------------------------------------
name = input("What is your name:")
print("Welcome to BATTLESHIPS!"  +  name)
print("10 enemy ships are hidden somewhere at sea" + name )
print("You only have 30 torpedos to find it!")
print("You need to sink both hips to win the game" + name)
while ships > 0 and torpedos > 0:

    displayGrid()

    print()

    print("You have " +str(torpedos) + " torpedos left.")

    print("Target coordinates, Captain?")
    
    refx = int(input("Enter the x coordinate: "))
    refy = int(input("Enter the y coordinate: "))

    refx = refx -1 #computers count from 0
    refy = refy -1 #this could be done with fewer lines

    if (theSea[refx][refy] == "S"):
        theSea[refx][refy] = "X"
        print(" DIRECT HIT, CAPTAIN!")
        ships = ships - 1
        print("There are {} ships left at sea".format(ships))
    else:
        theSea[refx][refy] = "M"
        print("You missed..."  +  name)
        print("Sorry, you can't shoot here again as there is no ship here")
        torpedos += 1
    torpedos = torpedos - 1
    input() #wait for user to press enter before redrawing grid

if ships == 0:
    print("Huzah! You sunk all the ships.")
else:
    print("You ran out of torpedos"  +  name)

print("GAME OVER"  +  name )
print("It took {} torpedos to sink this ship".format(torpedos))
<do not remove the three backticks above>

#2

i don’t see the code that places the ships?

You could simplify matters for yourself by making two boars, one that contains the ship and one that we show to the user with there guesses.

Having this second board, also allows us to see that our ships are not overlapping (that can happen, you need to cover this), and that the ship is on the board


#3

Could I have an a piece of code as an example to see how it could be done. Python is my coursework language for school and this is a project.


#4

we could simply generate another board:

ship_board = [["_" for i in range(9)] for j in range(9)] #2D list 9x9

then we generate a random coordinate for the ship:

ship_1 = (random.randint(0,8),random.randint(0,8))
length_ship_1 = 5
x_coordinate = ship_1[0]
y_coordinate = ship_1[1]

lets say ship_1 is (2,3) (which is what i got), then we can check if we place place the ship vertical (the long one, 5 spots):

if x_coordinate + length_ship_1 <= len(ship_board):
    # ship can be placed from top to bottom
    for coordinates in range(x_coordinate, x_coordinate+length_ship_1):
       ship_board[coordinates][y_coordinate] = 'S'

now, if the ship can’t be placed from top to bottom, you have to reverse it and place it from bottom to top (add an elif condition) and a else in case the ship can’t be placed at all (very unlikely, but just to be sure)

for the second ship, also ensure that there are no S overlaps.

This should help you forward


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.