检测pygam中是否单击了圆弧

2024-06-10 18:01:00 发布

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

我目前正在尝试数字化我发明的一款棋盘游戏(repo:https://github.com/zutn/King_of_the_Hill)。为了让它工作,我需要检查是否这个board上的一个平铺(弧)被点击了。到目前为止,我还没能想出一个不放弃这个计划的办法pygame.arc公司绘图功能。如果我使用点击位置的x,y位置,我无法找到一种方法来确定要比较的弧的确切轮廓。我想过使用颜色检查,但这只会告诉我,如果任何瓷砖已点击。那么,有没有一种方便的方法来测试pygame中是否点击了一个弧,或者我是否必须使用精灵或者完全不同的东西?此外,在后面的步骤中,将包括位于瓷砖上的单元。这将使以下角度计算柱的求解更加困难。你知道吗


Tags: ofthe方法httpsgithubcom游戏棋盘
1条回答
网友
1楼 · 发布于 2024-06-10 18:01:00

这是一个简单的圆弧类,它将检测圆弧中是否包含一个点,但它仅适用于圆弧。你知道吗

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

class CircularArc:

    def __init__(self, color, center, radius, start_angle, stop_angle, width=1):
        self.color = color
        self.x = center[0]  # center x position
        self.y = center[1]  # center y position
        self.rect = [self.x - radius, self.y - radius, radius*2,  radius*2]
        self.radius = radius
        self.start_angle = start_angle
        self.stop_angle = stop_angle
        self.width = width




    def draw(self, canvas):
        pygame.draw.arc(canvas, self.color, self.rect, self.start_angle, self.stop_angle, self.width)



    def contains(self, x, y):

        dx = x - self.x   # x distance
        dy = y - self.y   # y distance

        greater_than_outside_radius = dx*dx + dy*dy >= self.radius*self.radius

        less_than_inside_radius = dx*dx + dy*dy <= (self.radius- self.width)*(self.radius- self.width)

        # Quickly check if the distance is within the right range
        if greater_than_outside_radius or less_than_inside_radius:
            return False



        rads = atan2(-dy, dx)  # Grab the angle

        # convert the angle to match up with pygame format. Negative angles don't work with pygame.draw.arc
        if rads < 0:
            rads = 2 * pi + rads


        # Check if the angle is within the arc start and stop angles
        return self.start_angle <= rads <= self.stop_angle

下面是该类的一些示例用法。使用它需要一个中心点和半径,而不是矩形来创建圆弧。你知道吗

pygame.init()


black = ( 0, 0, 0)
width = 800
height = 800
screen = pygame.display.set_mode((width, height))


distance = 100
tile_num = 4
ring_width = 20

arc = CircularArc((255, 255, 255), [width/2, height/2], 100, tile_num*(2*pi/7), (tile_num*(2*pi/7))+2*pi/7, int(ring_width*0.5))

while True:

    fill_color = black

    for event in pygame.event.get():
        # quit if the quit button was pressed
        if event.type == pygame.QUIT:
            pygame.quit(); sys.exit()

    x, y = pygame.mouse.get_pos()


    # Change color when the mouse touches
    if arc.contains(x, y):
        fill_color = (200, 0, 0)


    screen.fill(fill_color)
    arc.draw(screen)
    # screen.blit(debug, (0, 0))
    pygame.display.update()

相关问题 更多 >