Part 6: Events – Change colour on key press and draw circles on mouse movement

drawcircleonmousemovementandchangecolor
When the mouse is moved, circles are drawn following the mouse, it will looking like a thick line as in the above image and on space key press the colour of the circles drawn is changed.


Comment or delete the following lines from the previous code since we are not going to draw a circle in a single position this time.

#YPOS = 40
#XPOS = 40
#POS = (XPOS, YPOS)
#circlerect = pygame.draw.circle(SCREEN, COLOR, POS, RADIUS)
#pygame.display.update(circlerect)

Add the line to get the mouse position in the while loop
pos = pygame.mouse.get_pos()

Change the colour on key press and in the for loop add the code for circle draw and update.

circlerect = pygame.draw.circle(SCREEN, COLOR, pos, RADIUS)
pygame.display.update(circlerect)

Now for the entire code.

#Import statements are to enable the code to use the functions from the library
import pygame
import sys
import os
import random

#instructions to windows to center the game window in the center of
#the screen, which it might ignore
os.environ["SDL_VIDEO_CENTERED"] = "1"

#initialize pygame
pygame.init()

#Right way
SCREENWIDTH = 500
SCREENHEIGHT = 500
SCREENSIZE = [SCREENWIDTH, SCREENHEIGHT]
SCREEN = pygame.display.set_mode(SCREENSIZE)

#caption for the game
pygame.display.set_caption("My first game in pygame")

RADIUS = 20
ZEROINTENSITY = 0
MAXINTENSITY = 255

COLOR = (random.randint(ZEROINTENSITY, MAXINTENSITY), random.randint(ZEROINTENSITY, MAXINTENSITY), random.randint(ZEROINTENSITY, MAXINTENSITY))

while True:
    pos = pygame.mouse.get_pos()
    for events in pygame.event.get():
        if events.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        #Here for any commands inside the for loop  
        if (events.type == pygame.KEYDOWN) and (events.key == pygame.K_SPACE):
            COLOR = (random.randint(ZEROINTENSITY, MAXINTENSITY), random.randint(ZEROINTENSITY, MAXINTENSITY), random.randint(ZEROINTENSITY, MAXINTENSITY))
        #note- we have skipped the last parameter and by default, 0 is taken
        circlerect = pygame.draw.circle(SCREEN, COLOR, pos, RADIUS)
        pygame.display.update(circlerect)
    #beware of the positioning of this line. It should be inside the while
    #for all the commands that need to be executed inside the while

Now the next step, draw different coloured circles at random positions on the screen using a small neat trick. Let’s go!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s