Home > database >  How to calculate the coordinates inside a square grid in python
How to calculate the coordinates inside a square grid in python

Time:02-05

I am trying to get the coordinates of each square inside a 8x8 square, if the first square(a1) starts at coordinates 455,785. A chessboard is a very fitting analogy.

The Grid

I've looped through the rows but I cant get the correct result.


# Set the size of each square
square_size = 100

# Set the starting point for clicking
start_x, start_y = 455, 785

# Define a list of letters for the x axis
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

# Loop through all 8 rows
for row in range(8):
    # Loop through all 8 columns
    for col in range(8):
        # Calculate the x and y coordinate of the current square
        x = start_x   col * square_size
        y = start_y - row * square_size
        # Print the coordinates of the current square
        print(f"{letters[col]}{8-row}: ({x}, {y})")

Cannot get the axes value to line up with the board

CodePudding user response:

>>> start_x, start_y = 455, 785
>>> square_size = 100
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
>>> for row in range(8):
    for col in range(8):
        x = start_x   col * square_size
        y = start_y - row * square_size
        print(f"{letters[col]}{row 1}: ({x}, {y})")

This works for me. I changed 8-row to row 1 as you're counting up and not down. I also think theres something wrong with the coordinates in the picture you posted. Hope this helps :)

CodePudding user response:

does this help you?

square_size = 100
grid_size = 8

start_x = 455
start_y = 785

letters = ["a", "b", "c", "d", "e", "f", "g", "h"]

for y_offset in range(grid_size):
    for x_offset in range(grid_size):
        x = start_x   square_size * x_offset
        y = start_y   square_size * (grid_size - 1 - y_offset)

        x_index = x_offset
        y_index = grid_size - y_offset

        print(f"{letters[x_index]}{y_index} ({x}, {y})", end=" ")
    print()
  • Related