Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # date: 2025.05.29
- # stackoverflow: [python - PYGAME Circle changes colour on clicking but changes back on mouse up - Stack Overflow](https://stackoverflow.com/questions/79639247/pygame-circle-changes-colour-on-clicking-but-changes-back-on-mouse-up)
- import pygame
- import random
- # --- constants --- # PEP8: constants after imports
- # display window
- SCREEN_HEIGHT = 800
- SCREEN_WIDTH = 1400
- # colours
- BLUE = (0, 0, 255)
- LIGHTBLUE = (72, 243, 235)
- BLUEBLACK = (20, 21, 77)
- IODINE = (243, 200, 99)
- REDYELLOW = (221, 78, 20)
- BLACK = (0, 0, 0)
- # other
- X = 500
- Y = 400
- SIZE = 40
- X_SPACING = SIZE*2.3
- Y_SPACING = SIZE*2.3
- # --- classes --- # PEP8: classes after constants
- class Experiment():
- def __init__ (self, colour, x, y, size, number):
- self.x = x
- self.y = y
- self.size = size
- self.number = number
- self.colour = colour
- self.rect = pygame.Rect(self.x-self.size, self.y-self.size, self.size*2, self.size*2)
- self.clicked = False
- def draw(self, screen):
- #pygame.draw.rect(screen, LIGHTBLUE, self.rect)
- if self.clicked:
- pygame.draw.circle(screen, BLACK, (self.x, self.y), self.size )
- else:
- pygame.draw.circle(screen, self.colour, (self.x, self.y), self.size)
- pygame.draw.circle(screen, BLACK, (self.x, self.y), self.size, 4)
- def handle_event(self, event):
- if event.type == pygame.MOUSEBUTTONDOWN:
- if self.rect.collidepoint(event.pos):
- self.clicked = True
- # --- functions --- # PEP8: functions after classes
- # --- main --- # # PEP8: main code after functions
- # - variables -
- wellcolour = IODINE
- colour = IODINE
- # - init -
- pygame.init()
- screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
- pygame.display.set_caption('Amylase')
- # - create all instances only once, using for-loop, and keep them on list
- items = []
- for row in range(4):
- wellcolour = (243, row*40+100, 99)
- for col in range(5):
- x = X + (col * X_SPACING)
- y = Y + (row * Y_SPACING)
- number = col + (row * 5) + 1
- item = Experiment(wellcolour, x, y, SIZE, number)
- items.append(item)
- # - main loop -
- run = True
- while run:
- # - events -
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- run = False
- # send every event to all items
- for item in items:
- item.handle_event(event)
- # - updates (without drawing) -
- # update all items
- # for item in items:
- # pass # empty function
- # - draws (without updates) -
- screen.fill(LIGHTBLUE)
- # draw all items
- for item in items:
- item.draw(screen)
- pygame.display.flip()
- # - end -
- pygame.quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement