In previous
post, I explained how to work with keyboard keys. In this post I am going to
explain how to work with mouse.
Following
program draws a person image when user clicks on the window. To draw a picture
on window, we need to get the position, where mouse is clicked.
# import pygame import pygame # initialize game engine pygame.init() window_width=500 window_height=500 animation_increment=10 clock_tick_rate=20 # Open a window size = (window_width, window_height) screen = pygame.display.set_mode(size) # Set title to the window pygame.display.set_caption("Hello World") dead=False # Constants related to soldiers soldier_head_width=10 soldier_head_height=10 soldier_start_x_position_incr=5 def draw_soldier(soldier_start_x_position, soldier_start_y_position): # Soldier head pygame.draw.ellipse(screen, BLACK, [soldier_start_x_position+soldier_start_x_position_incr,soldier_start_y_position,soldier_head_width,soldier_head_height], 0) # Soldier Body pygame.draw.line(screen, RED, [10+soldier_start_x_position, 9+soldier_start_y_position], [10+soldier_start_x_position, 20+soldier_start_y_position], 3) # Soldier hands pygame.draw.line(screen, RED, [10+soldier_start_x_position, 9+soldier_start_y_position], [5+soldier_start_x_position, 15+soldier_start_y_position], 3) pygame.draw.line(screen, RED, [10+soldier_start_x_position, 9+soldier_start_y_position], [15+soldier_start_x_position, 15+soldier_start_y_position], 3) #Soldier legs pygame.draw.line(screen, BLACK, [10+soldier_start_x_position, 20+soldier_start_y_position], [5+soldier_start_x_position, 26+soldier_start_y_position], 3) pygame.draw.line(screen, BLACK, [10+soldier_start_x_position, 20+soldier_start_y_position], [15+soldier_start_x_position, 26+soldier_start_y_position], 3) #Initialize values for color (RGB format) WHITE=(255,255,255) RED=(255,0,0) GREEN=(0,255,0) BLUE=(0,0,255) BLACK=(0,0,0) clock = pygame.time.Clock() # Hide the mouse cursor pygame.mouse.set_visible(False) while(dead==False): for event in pygame.event.get(): if event.type == pygame.QUIT: dead = True screen.fill(WHITE) pos = pygame.mouse.get_pos() x = pos[0] y = pos[1] draw_soldier(x, y) pygame.display.flip() clock.tick(clock_tick_rate)
Above program
draws a person image, wherever you take the mouse.
Reference
No comments:
Post a Comment