Home > Enterprise >  How to make a grid consisting of rectangles so that each rectangle can be used further in the code u
How to make a grid consisting of rectangles so that each rectangle can be used further in the code u

Time:01-18

I have this:

from tkinter import *
import numpy as np
rows = 10
columns = 10

width, height = rows*18, columns*18
window = Tk()
window.geometry(str(width) "x" str(height))
window.resizable(width=False, height=False)
window.config(background="#A9A9A9")

field_frame = Frame(width=width, height=height, bg="#A9A9A9", colormap="new")
field_frame.pack(side=BOTTOM)
field_frame.grid_propagate(False)

pixelVirtual = PhotoImage(width=1, height=1) #To measure the size in pixels

btnarr = np.zeros(shape=(rows, columns), dtype=object)

def button_click(row, column):
    #<SOME CODE HERE>
    pass
def placebuttons(rows=rows, columns=columns):
    for row in range(rows):
        for column in range(columns):
            btnarr[row, column] = (Button(field_frame, text="", image=pixelVirtual, height = 12, width = 12, command=lambda row=row, column=column:[(button_click(row, column)), btnarr[row,column].place_forget()]))
            btnarr[row, column].place(x=column*18, y=row*18)
placebuttons()

window.mainloop()

I want to do the same, but using pygame and rectagles instead of buttons. But I haven't found anywhere on the Internet how to create a grid of rectangles so that they can then be accessed via array[row, column] or array(row, column). Please help

CodePudding user response:

Here's an example of creating a grid of Rect's in pygame. See comments for more explanation about how it works.

import pygame

import numpy as np
from random import randint
from pygame.constants import *
#define main constants, edit to change window and rect formats
rows=10
columns=10

rectwidth,rectheight=50,50
width,height=rows*rectwidth,columns*rectwidth
#create window and initialise pygame
pygame.init()
screen= pygame.display.set_mode((width,height))
#fill window
bg=pygame.Surface((width,height))
bg.fill("#A9A9A9")
screen.blit(bg,(0,0))
#create btnArr
btnArr=np.zeros(shape=(rows, columns), dtype=object)
def placebuttons(rows=rows, columns=columns):
    for row in range(rows):
        for column in range(columns):
            #create a rect placed on the right place
            btnArr[row, column] = pygame.Rect((row*rectwidth,column*rectheight),(rectwidth,rectheight))
placebuttons()
surf=pygame.Surface((rectwidth,rectheight))
surf.fill((0,0,0))
running=True
while running:
    #notice wether user closed the window
    for event in pygame.event.get():
        if event.type==QUIT:
            
            running=False
    #reset window
    screen.blit(bg,(0,0))
    #place surfaces here, see example
    screen.blit(surf,btnArr[1,1])
    pygame.display.flip()
# main loop finished, time to quit
pygame.quit()
  •  Tags:  
  • Related