-1

I'm trying to create a game. I have a list of circles that moves continuously. I want to print "yes" if the user clicked on one of the circle. I tried to use the "if in" condition but it doesn't work. Please help me

import pygame

import random

pygame.init()

blanc = (255, 255, 255)
vert = (0, 255, 0)

Taille =[500, 500]
fenetre = pygame.display.set_mode(Taille)

pygame.display.set_caption("bienvenue!")

termine = False

horloge = pygame.time.Clock()

liste_objets= []
for i in range(100):
    x = random.randrange(0,450)
    y = random.randrange(0,495)
    liste_objets.append([x,y])

while termine == False:
    
    fenetre.fill(blanc)

    for i in liste_objets:
        i[0] += 1
        pygame.draw.circle(fenetre, vert, i, 5)
        if i[0] > 500:
            i[0] = 0
        
    pygame.display.flip()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            termine = True
        if event.type == pygame.MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()
            if pos in liste_objets:
                print("yes")

    pygame.display.flip()

    horloge.tick(200)
pygame.quit()
Blu Btw
  • 3
  • 2

1 Answers1

1

When you use the in condition, you have to make sure that you've got the correct types. Your list contains other list objects, whereas pygame.mouse.get_pos() returns a tuple object, list != tuple even if the elements are the same.

A more critical problem is that you have to check that your mouse is in a circle, not at a certain point.
To check that a point is in a circle, you have to find the distance from the point to the centre of the circle and check if that distance is less than the radius of the circle.
For example:

for obj in liste_objets:
    if ((obj[0] - pos[0])**2 + (obj[1] - pos[1])**2)**0.5 <= 5:
        print("yes")

((obj[0] - pos[0])**2 + (obj[1] - pos[1])**2)**0.5 calculates the distance from obj to pos (Pythagoras' theorem).

pySam1459
  • 224
  • 1
  • 6