如何确定我的鼠标是否在随机生成的对象上

How do I determine if my mouse is over randomly spawning objects

我正在尝试实现一款允许点击随机生成的圆圈的游戏,每次点击它都会给你积分。

import pygame
import time
import random

pygame.init()
window = pygame.display.set_mode((800,600))

class Circle():

    def __init__(self, color, x, y, radius, width):
        self.color = color
        self.x = x
        self.y = y
        self.radius = radius
        self.width = width

    def draw(self, win, outline=None):
        pygame.draw.circle(win, self.color, (self.x, self.y), self.radius, self.width)

    def isOver(self, mouse):

        mouse = pygame.mouse.get_pos()
        # Pos is the mouse position or a tuple of (x,y) coordinates
        if mouse[0] > self.x and mouse[0] < self.x + self.radius:
            if mouse[1] > self.y and mouse[1] < self.y + self.width:
                return True

        return False

circles = []

clock = pygame.time.Clock()
FPS = 60

current_time = 0
next_circle_time = 0

run=True
while run:
    delta_ms = clock.tick()

    current_time += delta_ms
    if  current_time > next_circle_time:
        next_circle_time = current_time + 1000 # 1000 milliseconds (1 second)
        r = 20
        new_circle = Circle((255, 255, 255), random.randint(r, 800-r), random.randint(r, 600-r), r, r)
        circles.append(new_circle)
        print()

    window.fill((0, 0, 0))
    for c in circles:
        c.draw(window)
    pygame.display.update()

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            run=False
            pygame.quit()
            quit()

        if event.type == pygame.MOUSEBUTTONDOWN:
            if Circle.isOver(mouse):
                print('Clicked the circle')

然而,当我尝试实现最后一个条件时,如果 Circle.isOver(mouse):... 我得到这个错误

TypeError: isOver() missing 1 required positional argument: 'mouse'

有人知道解决这个问题的方法吗?非常感谢任何帮助!

您必须遍历列表 circles 中包含的圆形对象。与绘制圆圈时的操作类似。您必须评估 class Circle 的每个实例的鼠标是否打开,而不是 Class 本身。注意,isOverMethod Object and has to be invoked by Instance Objects.
由于在 MOUSEBUTTONDOWN 事件发生时调用该方法,因此在 event.pos 属性中提供当前鼠标位置(参见 pygame.event):

run=True
while run:
    # [...]

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            run=False
            pygame.quit()
            quit()

        if event.type == pygame.MOUSEBUTTONDOWN:
            for c in circles:
                if c.isOver(event.pos):
                    print('Clicked the circle')

isOver 中通过 pygame.mouse.get_pos() 获取鼠标位置是多余的,因为当前鼠标位置是该方法的参数。
我建议通过评估Euclidean distance到圆心的平方是否小于或等于圆半径的平方来评估圆是否被点击:

class Circle():

    # [...]

    def isOver(self, mouse):
        dx, dy = mouse[0] - self.x, mouse[1] - self.y
        return (dx*dx + dy*dy) <= self.radius*self.radius 

mouse 传递给您的函数时未定义。还有其他问题,但这些是分开的。

if event.type == pygame.MOUSEBUTTONDOWN:
        mouse = pygame.mouse.get_pos()
        for circle in circles: 
            if circle.isOver(mouse):
                print('Clicked the circle')