在pygame中,如何检查鼠标单击是否在圆内?

2024-09-30 04:30:06 发布

您现在位置:Python中文网/ 问答频道 /正文

import pygame

pygame.init()

white = 255,255,255
cyan = 0,255,255

gameDisplay = pygame.display.set_mode((800,600))
pygame.display.set_caption('Circle Click Test')

stop = False

while not stop:
    gameDisplay.fill(white)

    pygame.draw.circle(gameDisplay,cyan,(400,300),(100))

    for event in pygame.event.get():

        if event.type == pygame.MOUSEBUTTONDOWN:
            ####################################################  

        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()

我在屏幕上有一个圆圈,我想看看用户是否 在圆圈内单击。我知道如何用一个矩形来做,我会假设它是相似的。谢谢你的帮助,我对pygame还是个新手。在

这是我对矩形的看法:

^{pr2}$

Tags: importeventifinitmodetypedisplaypygame
2条回答

使用距离公式:

################################################################################
# Imports ######################################################################
################################################################################

from pygame.locals import *
import pygame, sys, math

################################################################################
# Screen Setup #################################################################
################################################################################

pygame.init()
scr = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Box Test')

################################################################################
# Game Loop ####################################################################
################################################################################

while True:
    pygame.display.update(); scr.fill((200, 200, 255))
    pygame.draw.circle(scr, (0, 0, 0), (400, 300), 100)

    x = pygame.mouse.get_pos()[0]
    y = pygame.mouse.get_pos()[1]

    sqx = (x - 400)**2
    sqy = (y - 300)**2

    if math.sqrt(sqx + sqy) < 100:
        print 'inside'

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

################################################################################
################################################################################
################################################################################

你可以像这样采样像素 detect click on shape pygame 否则就用毕达哥拉斯来计算离中心的距离。在

正如马利克所说,毕达哥拉斯很适合圆形,但对于一般的纯色形状,你可以做到:

if event.type == pygame.MOUSEBUTTONDOWN:
  click = gameDisplay.get_at(pygame.mouse.get_pos()) == cyan

  if click == 1:
      print 'CLICKED!'

相关问题 更多 >

    热门问题