1
votes

I'm learning python. The idea of the app is that there are 8 rectangles which when clicked turn off or on representing binary. Each rectangle representing a bit, and the decimal equivalent will be displayed.

I'm having difficulty translating that into a well written app without hard coding everything. I hard coded the 8 rects using .fill but I would prefer to use a function which does that automatically. I don't want the full code I'd rather have someone point me in the right direction in regards to the structure of the code I should follow. Should I use a class to initiate a new rect then use a render method with a for loop to run through an array of the rectangles, if so, how would I display the rectangles in a row?

To draw the rectangles I am sticking to display.fill()

I considered to hardcore the properties of each rectangle into a tuple of tuples then render each with a for loop, is this a good approach?

1

1 Answers

2
votes

Here is a template you can use:

import pygame
import sys

def terminate():
    pygame.quit()
    sys.exit()

pygame.init()

black = (0,0,0)
white = (0,0,0)

clock = pygame.time.Clock()
fps=30

screen_height = 520
screen_width = 650
screen = pygame.display.set_mode((screen_width,screen_height)

class Rect(pygame.sprite.Sprite):
    def __init__(self,x,y,width,height,color,value):
        super().__init__()
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.value = value
    def change_value(self,color,value):
        self.image.fill(color)
        self.value=value

rects = pygame.sprite.Group()

rect = Rect(50,50,100,100,black)
rects.add(rect)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            terminate()

    screen.fill(white)
    rect.draw(screen)

    pygame.display.flip()

    clock.tick(fps)

Using a group will allow you to draw all the rectangles at once. You can change the rectangles using the change_value function.