I am trying to build a checkerboard where the squares underneath my cursor light up. I managed to create the checkerboard, but when I tried to implement the tiles lighting up under my cursor everything went wild. All the code does is that it alternate between light green and dark green and draw a rectangle and if the cursor position is equal to the rectangle about to be written I switch the light and dark greens to lighter greens named: LIGH_LIGHT_GREEN and LIGHT_DARK_GREEN.
# Setup
import pygame,sys
pygame.init()
WIDTH = 500
HEIGHT = 500
cell_size = 50
screen=pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption('HELP')
FPS=pygame.time.Clock()
DARK_GREEN = (76,175,79)
LIGHT_DARK_GREEN = (126,225,129)
LIGHT_GREEN = (139,195,74)
LIGHT_LIGHT_GREEN = (189,245,124)
def mouse_pos():
mx,my = pygame.mouse.get_pos()
mx = int(mx / cell_size)
my = int(my / cell_size)
print(mx,my)
return mx,my
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Colors
BLACK=(0,0,0)
gameOver=False
while not gameOver:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
mx,my = mouse_pos()
LIGHT = LIGHT_GREEN
DARK = DARK_GREEN
COLOR = DARK
for x in range(0,10):
for y in range(0,10):
if mx == x and my == y:
LIGHT = LIGHT_LIGHT_GREEN
DARK = LIGHT_DARK_GREEN
else:
LIGHT = LIGHT_GREEN
DARK = DARK_GREEN
if COLOR == LIGHT:
COLOR = DARK
else:
COLOR = LIGHT
pygame.draw.rect(screen,COLOR,(x*cell_size,y*cell_size,cell_size,cell_size))
if COLOR == LIGHT:
COLOR = DARK
else:
COLOR = LIGHT
pygame.display.update()
FPS.tick(60)
Pleas help.
>Solution :
When you reach your cursor square, you don’t want to interrupt your alternating COLOR toggling. So, keep your alternating stuff static, and use a separate variable to set "what do I draw for this particular square", which can either come from COLOR, or from your altered colors:
mx,my = mouse_pos()
LIGHT = LIGHT_GREEN
DARK = DARK_GREEN
COLOR = DARK
for x in range(10):
for y in range(10):
draw = COLOR
if mx == x and my == y:
if draw == LIGHT_GREEN:
draw = LIGHT_LIGHT_GREEN
else:
draw = LIGHT_DARK_GREEN
if COLOR == LIGHT:
COLOR = DARK
else:
COLOR = LIGHT
pygame.draw.rect(screen,draw,(x*cell_size,y*cell_size,cell_size,cell_size))
if COLOR == LIGHT:
COLOR = DARK
else:
COLOR = LIGHT