In this article, I will create a pygame program that will change the color of a circle every time a user has clicked on the display screen. The entire game plan here is to create a circle that will fill with random colors on top of another empty circle.
# Import and initialize the pygame library
import random
import pygame
import pygame.gfxdraw
pygame.display.init()
# set the caption on the panel
pygame.display.set_caption("Draw Some Drawing")
# windows height and width
windowwidth = 600
windowheight = 600
# Print this line on output panel if the initialize process is successful
if(pygame.display.get_init() == True):
print("Success initialize the game!")
# Initialize a window or screen for display
screen = pygame.display.set_mode([windowwidth, windowheight])
# Print the x, y size of the game display window
print("The windows size is " + str(pygame.display.get_window_size()))
# coordinate for circle
center_x = 300
center_y = 300
radius = 100
# create a list of colors
colorlist = [pygame.Color(0, 0, 0), pygame.Color(255, 255, 255), pygame.Color(160, 150, 150)]
# Run the game until the user asks to quit
running = True
while running:
# If the user clicks on the 'x' button on pygame display window then set running to false
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Fill the screen with blue color
screen.fill((0,0,255))
pygame.gfxdraw.circle(screen, center_x, center_y, radius, pygame.Color(0, 0, 0)) # Draw circle
# check the left mouse button press state
left_mouse_button_press_state = pygame.mouse.get_pressed(num_buttons=3)[0]
if(left_mouse_button_press_state == True): # if the user has clicked the left mouse button...
# draw and fill circle with selected color
pygame.gfxdraw.filled_circle(screen, center_x, center_y, radius, colorlist[random.randint(0, 2)])
pygame.display.flip() # refresh the screen
# Quit the game
pygame.display.quit()
A very simple program indeed, you can further modify it to make the circle changes color only if the user has clicked within that circle!