Skip to content

Instantly share code, notes, and snippets.

@JeffersGlass
Created September 27, 2020 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JeffersGlass/451f57ee0a2d168e4cfa09e5dbf066c8 to your computer and use it in GitHub Desktop.
Save JeffersGlass/451f57ee0a2d168e4cfa09e5dbf066c8 to your computer and use it in GitHub Desktop.
import pygame
import sys #will use the exit function
from random import randint
#Loads all the main pygame modules and initializes them
pygame.init()
clock = pygame.time.Clock()
screen_width=640
screen_height=480
#Sidelength of all of our squares
sideLength = 40
rectDict = dict()
for x in range(0, screen_width, sideLength):
for y in range (0, screen_height, sideLength):
rectDict[(x,y)] = {'rect':pygame.Rect(x, y, sideLength, sideLength),
'color':(255,0,0)}
#Create a new Surface with the dimensions listed above
screen=pygame.display.set_mode((screen_width, screen_height))
#Loop forever:
while True:
clock.tick(60)
#The following makes the window close when clicking the "X" or exit button
#Without this, the window will not close, and will need to be killed
#with the task manager
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
clickLocation = pygame.mouse.get_pos()
#print(clickLocation)
nearestX = clickLocation[0] - (clickLocation[0] % sideLength)
nearestY = clickLocation[1] - (clickLocation[1] % sideLength)
clickedRect = rectDict[(nearestX, nearestY)]
clickedRect['color'] = (randint(0,255),
randint(0,255),
randint(0,255))
for r in rectDict:
pygame.draw.rect(screen, rectDict[r]['color'], rectDict[r]['rect'])
pygame.display.flip()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment