NewToThis
NewToThis

Reputation: 21

Generating random X,Y coordinates in a grid

I'm fairly new to Python and this site. I'm hoping someone can help me with this and clarify a few things. I'm stuck at this part in my battleship program. I have a 10x10 grid and I want to randomize the locations for each of the 3 ships within my grid . I also want to display the location when I want them revealed. I've been trying to imitate this using other methods but to no avail.

My current grid looks like this:

print(" 0 ","1 ","2 ","3 ","4 ","5 ","6 ","7 ","8 ","9","10")

symbol = " O "
row = 0

for i in range(0,11):
    print(symbol*11 + " " + str(row))
    row += 1

For example, I want the grid to look like this when I choose to reveal the location of ships 1, 2 and 3:

O O O X O O O O O O
O O O X O O O O X O
O O O X O O O O X O
O O O X O O O O X O
O O O O O O O O X O
O O O O O O O O O O
O O X X X X O O O O
O O O O O O O O O O
O O O O O O O O O O
O O O O O O O O O O

Upvotes: 1

Views: 3150

Answers (1)

personjerry
personjerry

Reputation: 1075

You're doing too much manual work. You can store the entire grid as an array, and modify the grid, and then print the grid. Also, you don't need to specify 0 in range. Anyway, check this out.

grid = [['O' for i in range(10)] for j in range(10)] # use generators to create list

def print_grid():
    print("  " + " ".join(str(i) for i in range(10))) # " ".join() puts the " " between each string in the list
    for y in range(10): 
        print(str(y) + " " + " ".join(grid[y]))

print_grid()

# OUTPUT:
#   0 1 2 3 4 5 6 7 8 9
# 0 O O O O O O O O O O
# 1 O O O O O O O O O O
# 2 O O O O O O O O O O
# 3 O O O O O O O O O O
# 4 O O O O O O O O O O
# 5 O O O O O O O O O O
# 6 O O O O O O O O O O
# 7 O O O O O O O O O O
# 8 O O O O O O O O O O
# 9 O O O O O O O O O O

grid[0][3] = 'X'
grid[1][3] = 'X'
grid[2][3] = 'X'
grid[3][3] = 'X'

print_grid()

# OUTPUT:
#   0 1 2 3 4 5 6 7 8 9
# 0 O O O X O O O O O O
# 1 O O O X O O O O O O
# 2 O O O X O O O O O O
# 3 O O O X O O O O O O
# 4 O O O O O O O O O O
# 5 O O O O O O O O O O
# 6 O O O O O O O O O O
# 7 O O O O O O O O O O
# 8 O O O O O O O O O O
# 9 O O O O O O O O O O

Hopefully that's most of what you need!

EDIT: Did not see the randomize aspect, my apologies!

Use random.randint, for example (but move the import to the top of your file):

import random
x = random.randint(1, 8)
y = random.randint(1, 8)

if random.randint(0, 1): # flip coin to determine orientation
    grid[y-1][x] = 'X'
    grid[y][x] = 'X'
    grid[y+1][x] = 'X'
else:
    grid[y][x-1] = 'X'
    grid[y][x] = 'X'
    grid[y][x+1] = 'X'

To check for collision, you might rather than setting those 3 as X off the bat, verify that they are all O first, and if not, reroll the position and orientation.

Upvotes: 2

Related Questions