import pygame

pygame.init()




def main():

    screen = pygame.display.set_mode((640, 480))
    pygame.display.set_caption('game')

    background = pygame.Surface(screen.get_size())
    background = background.convert()
    background.fill(pygame.color.Color('yellow'))


    box = pygame.Surface((100,100))
    box = box.convert()
    box.fill(pygame.color.Color('red'))
    
    t = True
    clock = pygame.time.Clock()

    while t:
        

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                t = False

            elif event.type == pygame.MOUSEBUTTONDOWN:
                posi = pygame.mouse.get_pos()
                print 'mous down', posi
                screen.blit(box,posi)
                

                

            elif event.type == pygame.MOUSEBUTTONUP:
                print 'mouse up', pygame.mouse.get_pos()

        screen.blit(background, (0,0))
        
        pygame.display.flip()

            
                


main()

I just start to learn pygame. I want to make a box when I click mouse in the background, but I don't see a box from this code. also in this statement : for event in pygame.event.get(): how many event will actually be taken every time in this for loop? This is where I got confused the most. Thank you in advance.

The culprit is
screen.blit(background, (0,0))
I moved it out of the event loop, and rewrote your program just a little to reflect Python coding convention better ...

import pygame as pg

def main():
    # initialize pygame
    pg.init()
    screen = pg.display.set_mode((640, 480))
    pg.display.set_caption('game')

    background = pg.Surface(screen.get_size())
    background = background.convert()
    background.fill(pg.color.Color('yellow'))
    # this will color the whole screen, clear it
    screen.blit(background, (0,0))

    box = pg.Surface((100,100))
    box = box.convert()
    box.fill(pg.color.Color('red'))

    # initialize clock
    clock = pg.time.Clock()

    running = True
    while running:
        # optionally limit the framerate
        clock.tick(30)        
        for event in pg.event.get():
            if event.type == pg.QUIT:
                running = False
            elif event.type == pg.MOUSEBUTTONDOWN:
                posi = pg.mouse.get_pos()
                screen.blit(box, posi)
                s = 'mouse down (x=%d, y=%d)' % posi
                pg.display.set_caption(s)
            elif event.type == pg.MOUSEBUTTONUP:
                s = 'mouse up (x=%d, y=%d)' % pg.mouse.get_pos()
                pg.display.set_caption(s)

        #screen.blit(background, (0,0))  # clears the whole screen
        pg.display.flip()

main()

Thanks a lot vegaseat, your revised code is very helpful!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.