Question

How can I get my Python code to check to make sure there are no ships...

How can I get my Python code to check to make sure there are no ships overlapping in my Battleship code?

I am having a really hard time with a game of battleship that I have due for class. Each time I run my code, It will print the ships on the board but it will at times overlap them. I know I have to use some kind of nested if statements but I just don't get how or where I would do this at. Here is my code so far.

#This makes the board
import random
board = []
for i in range(0,10):
    board.append(['0'] *10)
def print_board(board):
    for row in board:
        print((" ").join(row))


ship={'S':5,'A':4,'B':3,'C':3,'D':2}

for i, j in ship.items():
    row = random.randint(0, len(board) - j)
    col= random.randint(0, len(board) - j)
    for k in range(j):
        board[row][col+k] = i
        
            

print_board(board)

Here is what happens when I print it out:

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 C C C 0 0
0 S S S S S 0 0 0 0
0 B B B 0 0 0 0 0 0
0 0 0 A A D D 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 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0

As you can see, D overlapped A in this example. What I would like the code to do is before it places the letters down I want it to check and if the there is a letter where it is trying to place to try using a different position. Then if that doesn't work just try a whole new section. so far the only thing I can think of for a code is something like this:

for i, j in ship.items():
    row = random.randint(0, len(board) - j)
    col = random.randint(0, len(board)- j)
    for k in range(j):
        if board[row][col+k] != '0':
            if board[row+k][col] != '0':
                if board[row+k][col+k] != '0':
                    x = random.randint(0, len(board) - j)
                    y = random.randint(0, len(board)- j)
                else:
                    board[row+k][col+k] = i
            else:
                board[row+k][col] = i
        else:
            board[row][col+k] = i

print_board(board)

which when I try this code it get me results like this:

D D 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 A A A A C 0 0
0 0 0 0 0 C 0 0 0 0
S S S S S 0 0 0 0 0
0 B 0 0 0 0 0 0 0 0
0 B 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 0 0 0
0 0 0 0 0 0 0 0 0 0

I am still getting overlaps and now my ships are snapping in half like what happened with C.

Am I just completely off base with my thought? Or am I just missing some big key parts?

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hi, Here is the code which works correctly to insert the 5 battleships in the grid, in either horizontal or vertical position, with no overlap.

I have used most of your code as-is. It was buggy in the logic of checking whether you have enough free squares either horizontally or vertically for the selected random row and col. You were checking through an "if" condition, but it has to be a "while" loop which has to keep on trying till it finds the free set of squares.

So I added an infinite while loop (while True) which will check if the selected row and col have free squares to accommodate the ship - first check horizontally, if not available check vertically. If space is available, it will exit the while loop and insert the ship into the grid at the row and col (either horizontally or vertically based on where it found the space)

I have added the comments in the code. Look for the new code between the #added comment lines which is new. The while loop and 3 boolean flags are also newly added.

Have tested it quite a few times and it is working. You can try to further optimize the code if you wish.

Complete program is given below.

------------

#This makes the board
import random
board = []
for i in range(0,10):
board.append(['0'] *10)
  
def print_board(board):
for row in board:
print((" ").join(row))


ship={'S':5,'A':4,'B':3,'C':3,'D':2}

for i, j in ship.items():
while True:
'''
added 3 booleans
found = to indicate whether we were able to find free squares to fit the ship
used as a boolean to exit from loop
vertical = flag to indicate if the free squares are vertical
horizontal = flag to indicate if the free squares are horizontal
Logic of the while loop:
program will first check for horizontal free squares. If found, it
will exit the while loop after setting horizontal = True
Else, it will check for vertical free squares. If found, it will exit
the while loop after setting vertical = True
If neither vertical nor horizontal is found, the infinite while loop
will continue with another set of random choices for row and col
'''
found = True
vertical = False
horizontal = False
row = random.randint(0, len(board) - j)
col= random.randint(0, len(board) - j)
#added code to check for free squares here
#check horizontally if k squares are free from the selected row
for k in range(j):
if board[row][col+k] != '0': #occupied
found = False
break
if (found):
#this means that the earlier for loop exited after finding free space
#hence we can exit the while loop. Else the infinite while loop will continue
horizontal = True
break
#horizontal not free, so check vertically if k squares are free
found = True
for k in range(j):
if board[row+k][col] != '0': #occupied
found = False
break
if (found):
#this means that the earlier for loop exited after finding free space
#hence we can exit the while loop. Else the infinite while loop will continue
vertical = True
break
#end addition
  
#now we are out of while loop after confirming that the squares are free, so update
if (horizontal):
for k in range(j):
board[row][col+k] = i
elif (vertical):
for k in range(j):
board[row+k][col] = i
  
  
  
print_board(board)

Add a comment
Know the answer?
Add Answer to:
How can I get my Python code to check to make sure there are no ships...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need help finishing my C++ coding assignment! My teacher has provided a template but I...

    I need help finishing my C++ coding assignment! My teacher has provided a template but I need help finishing it! Details are provided below and instructions are provided in the //YOU: comments of the template... My teacher has assigned a game that is similar to battleship but it is single player with an optional multiplayer AI... In the single player game you place down a destroyer, sub, battleship, and aircraft carrier onto the grid.... Then you attack the ships you...

  • python: how would I format the grid below so that it is aligned correctly? as you...

    python: how would I format the grid below so that it is aligned correctly? as you see, I tried to center it but it is still not correct. import random row=random.randint(1,10) col=random.randint(1,10) for r in range(row): for c in range(col): if r %2==0 and c %2==0: print(format('a','^3'),end=' ') elif r %2!=0 and c %2!=0: print(format("/x\\",'^3'),end=' ') elif c%2!=0: print(format('-','^3'),end='')    else: print(format('s','^3'),end=' ')    print() #go to next line current Output is: (example if random function choses col=4 and row=3)...

  • Using a sort method and my previous code (put inside of addHours method if possible), how...

    Using a sort method and my previous code (put inside of addHours method if possible), how would I get the list of each employee's total hours to display in order of least amount of hours to greatest. An explanation for each step would also be great. import random #Create function addHours def addHours(lst): #Display added hours of employees print("\nEmployee# Weekly Hours") print("----------------------------") print(" 1 ",sum(lst[0])) print(" 2 ",sum(lst[1])) print(" 3 ",sum(lst[2])) #Create main function def main(): #Create first empty list...

  • how would i write my code in Pseudocode? I am pretty much a beginner, therefore this...

    how would i write my code in Pseudocode? I am pretty much a beginner, therefore this is my first major computer science assignment and im not really understanding the written way of code.. please help and explain. Thank you! this is my working code: # Guess The Number HW assignment import random guessesTaken = 0 names=[] tries=[] print("Welcome! ") question = input("Would you like to play the guessing game? [Y/N]") if question == "N": print("Sorry to see you go so...

  • This is my code for my game called Reversi, I need to you to make the...

    This is my code for my game called Reversi, I need to you to make the Tester program that will run and complete the game. Below is my code, please add comments and Javadoc. Thank you. public class Cell { // Displays 'B' for the black disk player. public static final char BLACK = 'B'; // Displays 'W' for the white disk player. public static final char WHITE = 'W'; // Displays '*' for the possible moves available. public static...

  • Python Programming: Why do I get UnboundLocalError? What does this mean and how can I fix...

    Python Programming: Why do I get UnboundLocalError? What does this mean and how can I fix it? Question: Write a function check_move(column, row) which returns a string describing a chess move to a given row and column on the chess board. Your program must check if the row and column entered are both valid. The column in a chess board is a letter ranging from A to H or a to h (inclusive) and the row is a number between...

  • This is my code for a TicTacToe game. However, I don't know how to write JUnit...

    This is my code for a TicTacToe game. However, I don't know how to write JUnit tests. Please help me with my JUnit Tests. I will post below what I have so far. package cs145TicTacToe; import java.util.Scanner; /** * A multiplayer Tic Tac Toe game */ public class TicTacToe {    private char currentPlayer;    private char[][] board;    private char winner;       /**    * Default constructor    * Initializes the board to be 3 by 3 and...

  • I need help modifying this program. How would I make sure that the methods is being...

    I need help modifying this program. How would I make sure that the methods is being called and checked in my main method? Here is what the program needs to run as: GDVEGTA GVCEKST The LCS has length 4 The LCS is GVET This is the error that I'm getting: The LCS has length 4 // I got this right The LCS is   //the backtrace is not being called for some reason c++ code: the cpp class: /** * calculate...

  • In python how could I update my code to tell me the number of guesses it...

    In python how could I update my code to tell me the number of guesses it took my to get the correct number here is my working code so far import random number = random.randint(1,100) total_guess = 0 while total_guess<=100: guess = int(input("what is your guess?")) print (guess) total_guess = total_guess + 1 if guess<number: print("Too low") if guess>number: print("Too high") if guess==number: print("Correct!") break

  • this python code below is to find the longest common subsequence from two input string !!!...

    this python code below is to find the longest common subsequence from two input string !!! however it give me the wrong answer, can any one fix it thanks def lcs(s1, s2): matrix = [["" for x in range(len(s2))] for x in range(len(s1))] for i in range(len(s1)): for j in range(len(s2)): if s1[i] == s2[j]: if i == 0 or j == 0: matrix[i][j] = s1[i] else: matrix[i][j] = matrix[i-1][j-1] + s1[i] else: matrix[i][j] = max(matrix[i-1][j], matrix[i][j-1], key=len) cs =...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT