In this pygame example, I will create a triangle and fill it up with the color of my choice. Next, I am going to create a small program that will detect that object using its own color as a hint.
Below is the entire python program which will use the pygame.mouse.get_pos() method to return the color of a pixel at a particular location on the display screen which will then serve as a hint whether I have clicked on that triangle or not!
# Import and initialize the pygame library 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]) # the triangle color tricolor = pygame.Color(0,0,0) # Print the x, y size of the game display window print("The windows size is " + str(pygame.display.get_window_size())) # 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.filled_polygon(screen, ((200,300), (300, 300), (250, 60)), tricolor) # draw triangle filled with black color # 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... # get the pixel color at that position of the mouse click x, y = pygame.mouse.get_pos() if(screen.get_at((x, y)) == tricolor): print('In the triangle region!') else: print('Not in the triangle region!') pygame.display.flip() # refresh the screen # Quit the game pygame.display.quit()
If I have clicked on the above triangle the console will print out the below text…
In the next article I will start to create my next game project so stay tuned and if you have not yet subscribed to my blog please do so through either the RSS news feed at the top left panel of this blog or just click on the web notification button above!