Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
import pygame
import sys #will use the exit function
from random import randint
#Loads all the main pygame modules and initializes them
clock = pygame.time.Clock()
squareSize = 40
numSquaresEachDir = 15
screen_width = squareSize * numSquaresEachDir
screen_height = squareSize * numSquaresEachDir
rectDict = dict()
dividingLines = list()
for x in range(0, screen_width, squareSize):
for y in range (0, screen_height, squareSize):
rectDict[(int(x/squareSize),int(y/squareSize))] = {'rect':pygame.Rect(x, y, squareSize, squareSize),
'mineState': 'safe'}
for x in range (0, screen_width, squareSize):
dividingLines.append(pygame.Rect(x, 0, 1, screen_height))
for y in range (0, screen_height, squareSize):
dividingLines.append(pygame.Rect(0, y, screen_width, 1))
numMines = 15
for i in range(numMines):
x = randint(0, numSquaresEachDir-1)
y = randint(0, numSquaresEachDir-1)
if rectDict[(x, y)]['mineState'] == 'safe':
rectDict[(x, y)]['mineState'] = 'hidden mine'
#Create a new Surface with the dimensions listed above
screen=pygame.display.set_mode((screen_width, screen_height))
#Loop forever:
while True:
#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()
nearestX = int(clickLocation[0]/squareSize)# - (clickLocation[0] % squareSize)
nearestY = int(clickLocation[1]/squareSize)#clickLocation[1] - (clickLocation[1] % squareSize)
clickedRect = rectDict[(nearestX, nearestY)]
if clickedRect['mineState'] == 'hidden mine':
clickedRect['color'] = (255,0,0)
else: clickedRect['color'] = (0,120,0)
for r in rectDict:
pygame.draw.rect(screen, rectDict[r]['color'], rectDict[r]['rect'])
for l in dividingLines:
pygame.draw.rect(screen, (155,155,155), l)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment