Reputation: 434
I am attempting to create a paint program in pygame. It requires the user to be able to draw a rectangle on the screen by clicking and dragging.
pygame.draw.rect(screeny, (255,255,255), [posi[0], posi[1], e.pos[0]-posi[0], e.pos[1]-posi[1]], 1)
square = pygame.draw.rect(screeny, color, [posi[0], posi[1], e.pos[0]-posi[0], e.pos[1]-posi[1]], 1)
pygame.display.flip()
However, the rectangle is not displayed properly. How would I only draw one rectangle starting from the mouse button down point going to the mouse button up point?
Upvotes: 1
Views: 495
Reputation: 31
I don't have enough code to work with from your example. But I was able to make a little bit of code that creates boxes and leaves it on the screen.
import pygame, sys
from pygame.locals import * //Allows MOUSEMOTION in stead of pygame.MOUSEMOTION
window_size = (800, 600)
clock = pygame.time.Clock()
FPS = 60
mousepos = None
boxes = []
screen = pygame.display.set_mode(window_size)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
while 1:
screen.fill(WHITE)
events = pygame.event.get()
for event in events:
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
mousepos = [event.pos[0], event.pos[1], 0, 0]
if event.type == MOUSEBUTTONUP:
boxes.append(mousepos)
mousepos = None
if event.type == MOUSEMOTION and mousepos != None:
mousepos = [mousepos[0], mousepos[1], event.pos[0] - mousepos[0], event.pos[1] - mousepos[1]]
for box in boxes:
pygame.draw.rect(screen, BLACK, box, 1)
if mousepos != None:
pygame.draw.rect(screen, BLACK, mousepos, 1)
pygame.display.update()
clock.tick(FPS)
I hope this helps.
NOTE: Be careful with the event queue, it's dangerous. NEVER use it for checking key presses. Use "pygame.key.get_pressed()[K_(Key here)]". If you need to prevent this from triggering twice, create a list that holds the previous values like so:
prev = pygame.key.get_pressed()
if prev[K_(key here)] != pygame.key.get_pressed()[K_(Key here)]
do your stuff...
Upvotes: 3