0
votes

I'm pretty new to Python and programming in general.

I'm trying to draw a square (200px by 200px) on the screen when the user clicks on the screen.

I tried to create a surface and a rect around the surface ( when the user clicks on the screen) and then using the rect, placed the surface on the screen using the blit method.
for the x and y of the rect I used mouse position.

So, this in my head should have changed the position of the square whenever a user clicks somewhere else on the screen but it rather creates a new square every time.

so I have a couple of questions:

  • If the way I'm implementing this is wrong, then how can I implement this feature?
  • Shouldn't the square change place as Pygame draws it every frame?

Thank you :)

pygame.init()
# --- Column --------------- #
col_num = 8
col_size = 120
# --- Screen --------------- #
screen = pygame.display.set_mode((col_num * col_size, col_num * col_size))
screen.fill((255, 255, 255))
draw_board()
# --- Clock ---------------- #
clock = pygame.time.Clock()

white_player = Player()

# --- test surface --------- #
surface = pygame.Surface((200, 200))
surface.fill((255, 255, 255))

# --- Main Loop ------------ #
check = False
while True:
    white_player.draw_piece()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit(), sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            check = True
            a_rect = surface.get_rect(center=pygame.mouse.get_pos())
            print('here!')


    if check:
        screen.blit(surface, a_rect)
            

    pygame.display.update()
    clock.tick(60)

Output:


Even trying with a simple surface and a screen it doesn't work. It adds another surface to the screen with the new x.

import pygame as pg
import sys

pg.init()
screen = pg.display.set_mode((400, 400))
clock = pg.time.Clock()
surface = pg.Surface((200, 200))
surface.fill((255, 255, 255))
xpos = 50

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

    xpos += 1
    screen.blit(surface, (xpos, 100))


    pg.display.flip()
    clock.tick(60)
1
Please consider creating a minimal reproducible example so it's easier to assist you. E.g. we don't know how draw_board() works. You should move all of your drawing functions so they are called with every loop. A typical game loop is `event handling → update game state → draw screen → display update. - import random
oh sorry about draw board as I already tested them thought they wouldn't be important. - arshiagholami
I added another example. This should draw a new surface with the new x in each frame, as far as I know. It does that; however, the previous surface is still there. - arshiagholami

1 Answers

1
votes

Oh, I just realized I forgot to fill the screen before each frame. fixed