Question

I have been trying to make a rectangle that moves to my mouse location, but it doesn't seem to be working. Here is my code:

import random, pygame, sys, pickle, pygame.mouse, pygame.draw
from pygame.locals import *
pygame.mixer.init()
#             R    G    B
WHITE     = (255, 255, 255)
BLACK     = (  0,   0,   0)
RED       = (255,   0,   0)
GREEN     = (  0, 255,   0)
DARKGREEN = (  0, 155,   0)
DARKGRAY  = ( 40,  40,  40)
BGCOLOR = BLACK

pygame.init()

DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
DISPLAYSURF.fill(BLACK)
rectangle = pygame.draw.rect (DISPLAYSURF, DARKGREEN, Rect((100,100), (130,170)))
pygame.display.update()

while True:
    DISPLAYSURF.fill(BLACK)
    #print pygame.mouse.get_pos()
    rectangle.move(pygame.mouse.get_pos())
    pygame.display.update()
    for event in pygame.event.get():
            if event.type == QUIT:
                    pygame.mixer.music.stop()
                    pygame.quit()
                    sys.exit()

I try running the code, but I only see a green rectangle for a millisecond, and then it disappears.

Was it helpful?

Solution

You didn't assign any value to the variables WINDOWWIDTH and WINDOWHEIGHT. I have done some modifications to your code and it works well for me:

import random, pygame, sys, pickle, pygame.mouse, pygame.draw
from pygame.locals import *
pygame.mixer.init()
#             R    G    B
WHITE     = (255, 255, 255)
BLACK     = (  0,   0,   0)
RED       = (255,   0,   0)
GREEN     = (  0, 255,   0)
DARKGREEN = (  0, 155,   0)
DARKGRAY  = ( 40,  40,  40)
BGCOLOR = BLACK

pygame.init()

WINDOWWIDTH = 500
WINDOWHEIGHT = 400
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
rectangle = Rect(0, 0, 130, 170)

while True:
    for event in pygame.event.get():
            if event.type == QUIT:
                    pygame.mixer.music.stop()
                    pygame.quit()
                    sys.exit()
    DISPLAYSURF.fill(BLACK)
    rectangle.center = pygame.mouse.get_pos()
    pygame.draw.rect(DISPLAYSURF, DARKGREEN, rectangle)
    pygame.display.update()

I made a variable called rectangle where my Rect object is. Then in the while loop, I changed the center of the Rect object according to the position of the mouse. You have to redraw the rectangle each loop because the background color (black) fills the whole window and hides your rectangle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top