Home > Software engineering >  Assosiate rects to specific window in pygame
Assosiate rects to specific window in pygame

Time:12-22

in my program i defined main screen. The program will blit new window by clicking on different btn.

i want to undestand if it possible to define many windows and associate to them objects coordinates according the new windows locations.

in other words if it possible to edit "The beginning of the axes" for the object related to new window

for example:

  • screen display is with width of 1000 and height of 800.
  • new window with width,height = 800,800
  • screen.blit(new_window,100,0)

the new window will apeare from x0,y0 = 100,0 - x1,y1 = 900,800

  • i want to create a rect in the new window but not according to screen cords but according to new_window cords where "The beginning of the axes" is the top left of that window.

i pasted the relavant lines for your review.

#before main loop start (this display updating by running in main loop)
screen = screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))

# after main loop start when btn clicked on it
new_window= pygame.Surface((w,h))

#in main loop i use
screen.blit(new_window,(x,y))

if i create a new rect as

window_rect = pygame.Rect(x,y,w,h)

its define x,y coordinates for window_rect according to screen coords and not for new window. how can i associate new rects to new window?(so the new rect coordinate will be acording to new_window)

Note: i know that i can draw on that new window with:

pygame.draw.rect(new_window,color,(window_rect)

in that way it useing the new window coordinate for draw. but i need to define the rect according to new window for other functions

CodePudding user response:

i want to create a rect in the new window but not according to screen cords but according to new_window cords where "The beginning of the axes" is the top left of that window.

Unfortunately, there is no such feature in Pygame. You have to compute the window coordinates yourself. You can do this with pygame.Rect.move.

e.g:: if you have a subwindow with the rectangle sub_window_rect and you have a rectangle inside the subwindow rect_in_sub_window:

sub_window_rect = pygame.Rect(100, 0, 800, 800)
rect_in_sub_window = pygame.Rect(10, 10, 100, 100)

rect_in_window = rect_in_sub_window.move(*sub_window_rect.topleft)

The top left coordinate of rect_in_window is (110, 10).

Converting from window coordinated to subwindow coordinates:

rect_in_sub_window = rect_in_window.move(
    -sub_window_rect.left, -sub_window_rect.top)
  • Related