1

I have a task, where I have a square 3X3 and for every click in the small square, this square will paint in red. Here is my code yet. I think I did something wrong in my first while loop, but I'm not sure. Please help me.

import pygame pygame.init() #create a screen screen = pygame.display.set_mode((400, 400)) #colors white = [255, 255, 255] red = [255, 0, 0] x = 0 y = 0 #create my square for j in range(3): for i in range(3): pygame.draw.rect(screen, white, (x, y, 30, 30), 1) x += 30 if x == 90: x = 0 y += 30 pygame.display.flip() running = 1 while running: event = pygame.event.poll() #found in what position my mouse is if event.type == pygame.QUIT: running = 0 elif event.type == pygame.MOUSEMOTION: print("mouse at (%d, %d)" % event.pos) mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() #mouse click if click[0] == 1 and x in range(30) and y in range (30): pygame.draw.rect(screen, red, (30, 30 , 29 ,29)) while pygame.event.wait().type != pygame.QUIT: pygame.display.change() 

1 Answer 1

1

You have to update your screen each time when you draw or do something in screen. So, put this line under your first while loop.

pygame.display.flip() 

In your condition you was checking x and y and which are not mouse position.

if click[0] == 1 and x in range(30) and y in range (30): 

Check your mouse position in range(90) because of you have three rectangular and the are 30x30.

if click[0] == 1 and mouse[0] in range(90) and mouse[1] in range (90): 

Then, set your rectangular start position to fill the mouse point.

rect_x = 30*(mouse[0]//30) # set start x position of rectangular rect_y = 30*(mouse[1]//30) # set start y position of rectangular 

You can edit your code with this.

while running: pygame.display.flip() event = pygame.event.poll() #found in what position my mouse is if event.type == pygame.QUIT: running = 0 elif event.type == pygame.MOUSEMOTION: print("mouse at (%d, %d)" % event.pos) mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() #mouse click if click[0] == 1 and mouse[0] in range(90) and mouse[1] in range (90): ''' rect_x = 30*(0//30) = 0 rect_y = 30*(70//30) = 60 ''' rect_x = 30*(mouse[0]//30) # set start x position of rectangular rect_y = 30*(mouse[1]//30) # set start y position of rectangular pygame.draw.rect(screen, red, (rect_x, rect_y , 30 , 30)) # rectangular (height, width), (30, 30) 

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.