python pygame: Draw loaded image at current mouse click position
I'm trying to get a loaded image displayed at the current mouse click position in pygame... Please help me... What I'm doing wrong?
import pygame
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 25 # for more than 220 it has no time to update screen
BLACK = (0, 0, 0)
RED = (255, 0, 0)
pygame.init()
def main():
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
screen_rect = screen.get_rect()
image = pygame.image.load('images/explo_trans.png').convert()
image_rect = image.get_rect()
all_items = []
clock = pygame.time.Clock()
running = True
while running:
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYUP:
if event.key == pygame.K_ESCAPE:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
x, y = event.pos
image_rect.x = x
image_rect.y = y
item = {
'rect': image_rect,
'remove_at': current_time + 500, # 500ms = 0.5s
}
all_items.append(item)
print("add at:", x, y)
keep_items = []
for item in all_items:
if item['remove_at'] > current_time:
keep_items.append(item)
else:
print('removed:', item)
all_items = keep_items
screen.fill(BLACK)
for item in all_items:
#pygame.draw.rect(screen, item['rect'])
screen.blit(item['rect'], (x, y))
pygame.display.flip()
ms = clock.tick(FPS)
# pygame.display.set_caption('{}ms'.format(ms)) # 40ms for 25FPS, 16ms for 60FPS
fps = clock.get_fps()
pygame.display.set_caption('FPS: {}'.format(fps))
pygame.quit()
if __name__ == "__main__":
main()
Solution 1:
The 1st argument of pygame.Surface.blit
is the image (pygame.Surface
) and the 2nd argument is the position:
screen.blit(item['rect'], (x, y))
screen.blit(image, item['rect'])
See also What is a good way to draw images using pygame?