Trying to blit an image at the cursor position when you left click in pygame , but the image disappears after less than a second

Viewed 249

Im trying to make some Minecraft 2d clone in pygame, and I want it to blit an image at the position of the cursor when I left click, but when I test the game and left click, the image appears and disappears shortly.

Here is the code:

import pygame

# Setup
pygame.init()
screen = pygame.display.set_mode((1080,720))
pygame.display.set_caption('2d minecraft')
clock = pygame.time.Clock()
logo = pygame.image.load("logo.png")
pygame.display.set_icon(logo)

# Variables
running = True
dirt = pygame.image.load("logo.png")

# Program
while running:
    # Customization
    screen.fill((110,150,200))

    # Update display
    pygame.display.update()

    # Events
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONUP:
            screen.blit(dirt, (pygame.mouse.get_pos()))
        if event.type == pygame.QUIT:
            running = False
        pygame.display.flip()
        clock.tick(30)
2 Answers

You have to draw the image in the application loop. Add the position to a list when you click the mouse. Draw images at all positions in the list in the application loop:

import pygame
pygame.init()
screen = pygame.display.set_mode((1080,720))
pygame.display.set_caption('2d minecraft')
clock = pygame.time.Clock()
logo = pygame.image.load("logo.png")
pygame.display.set_icon(logo)

#Variables
running = True
dirt = pygame.image.load("logo.png")

# list of positions
positions = []

#Program
while running:
    #Events
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONUP:

            # add position to list
            positions.append(event.pos)
            
        if event.type == pygame.QUIT:
            running = False
    
    screen.fill((110,150,200))
    # draw images at positions
    for pos in positions:
        screen.blit(dirt, pos)    
    pygame.display.flip()

    clock.tick(30)

The event pygame.MOUSEBUTTONUP occurs only the frame when you press the mouse button.

This can be used for example to handle clicks on buttons, but if you want to blit the image when the mouse is pressed, then prefer using pygame.mouse.get_pressed().

This function returns a list of values corresponding to the mouse buttons. Each value of the list is set to True if the corresponding button is pressed, otherwise it is set to False.

Use this code which displays a red rectangle at the mouse position:

import pygame
from pygame.locals import *

pygame.init()

screen = pygame.display.set_mode((640, 480))

red_rect = pygame.Surface((50, 50))
red_rect.fill((255, 0, 0))

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()

    if pygame.mouse.get_pressed()[0]: # first value of the list is the left click (check if left click pressed
        screen.blit(red_rect, pygame.mouse.get_pos())
Related