Reputation: 13
I am drawing a checkered board in Pygame, the cells of which should be changed using the mouse cursor. The field itself is initially colored red when the board is launched. Simply put, the mouse cursor should "highlight" a single cell with the yellow color. I would also like that as soon as I move the cursor to any other cell, the one I was just on, back to its original red color.
This is my first question on the site and I apologize in advance for any possible mistakes. I would be very grateful if you could help me how to finally write this puzzle :) And this is part of my code:
#_____
YELLOW = (204, 250, 35)
RED = (255, 0, 0)
#_____
WIDTH = 80
HEIGHT = 80
SG = True # While
# Create a 2 dimensional array. A two dimensional
# array is simply a list of lists.
grid = []
for row in range(10):
# Add an empty array that will hold each cell
# in this row
grid.append([])
for column in range(20):
grid[row].append(0) # Append a cell
# --------START-----------
while SG:
# ======
for i in pygame.event.get():
if i.type == pygame.QUIT:
SG = False
if i.type == pygame.MOUSEMOTION:
pos = pygame.mouse.get_pos()
# Change the x/y screen coordinates to grid coordinates
column = pos[0] // (WIDTH)
row = pos[1] // (HEIGHT)
# Set that location to one
grid[row][column] = 1
print("Click ", pos, "Grid coordinates: ", row, column)
# DRAWING THE BOARD
for row in range(8):
for column in range(15):
color = RED
if grid[row][column] == 1:
color = YELLOW
x = column *(WIDTH) + (column + 1)
y = row * (HEIGHT) + (row + 1)
pygame.draw.rect(screen, color, (x, y, WIDTH, HEIGHT), 1)
Upvotes: 1
Views: 49
Reputation: 210889
You don't need the MOUSEMOTION
event at all. pygame.mouse.get_pos()
returns a tuple that represents the currente x and y coordinates of the mouse cursor. Just test if the mouse hovers over the cell as you draw the cells:
while SG:
for i in pygame.event.get():
if i.type == pygame.QUIT:
SG = False
for row in range(8):
for column in range(15):
pos = pygame.mouse.get_pos()
mouse_column = pos[0] // (WIDTH + 1)
mouse_row = pos[1] // (HEIGHT + 1)
color = RED
if row == mouse_row and column == mouse_column:
color = YELLOW
x = column * WIDTH + (column + 1)
y = row * HEIGHT + (row + 1)
pygame.draw.rect(screen, color, (x, y, WIDTH, HEIGHT), 1)
pygame.display.flip()
Upvotes: 1