圆形面上的间隔指示器

Interval indicators on a Circular face

我正在尝试将间隔指示器放在一个圆圈上,就像您在计时器或时钟上找到的一样。

import pygame
from pygame.locals import *
import math

SCREENWIDTH = 400
SCREENHEIGHT = 400
BACKGROUND = (0, 0, 0)
FPS = 60
clock = pygame.time.Clock()
screen = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT))

lineStart = (200, 200)
lineLen = 100
color = (255, 255, 255)

pygame.init()

def drawLines(width, delta, amt):
    for i in range(amt):
        deltaAmt = 0
        deltaRadian = delta*2*math.pi #converts degree amt to radians

        x = lineStart[0] + math.cos(deltaAmt) * lineLen 
        y = lineStart[1] + math.sin(deltaAmt) * lineLen
        pygame.draw.line(screen, color, lineStart, (x, y), width)
        deltaAmt += deltaRadian


    pygame.display.flip()

drawLines(4, 0, 80)
clock.tick(FPS)

我遇到的麻烦是代码实际上只画了一条线。我需要它以一致的度差绘制多条线。例如,我需要绘制 4 条相互成 90 度的线,或者 5 条相互成 72 度的线。我以为我通过将 deltaAmt 增加 deltaRadian 的当前值来为此做好准备,但再次查看代码我认为这实际上并没有实现。

此外,您会看到,对于 delta 参数,我目前已将 0 作为参数传递。理想情况下,这意味着该线绘制在 12 点钟位置,但它被绘制在 3 点钟位置。当我输入 90 作为参数时,该线位于 6 点钟位置或 180 度,而应在 3 点钟或 90 度位置绘制。

如有任何帮助,我们将不胜感激。

您的问题是 deltaAmt = 0for 内 - 您在绘制每条线之前重置了角度。 deltaAmt = 0 必须在 for

之前

如果您需要 12 点钟的 0 度,则在所有计算中使用 angle-90

radiants = math.radians(angle-90)

我必须使用 round()x,y 转换为整数,因为 pygame 使用 int() 以不正确的方式舍入值并且在 360 度线之后不完全是 vertical/horizontal.

带动画的版本 - 它使用 start_angle 旋转线条。

import pygame
import math

# --- constants --- (UPPER_CASE names)

SCREEN_WIDTH = 400
SCREEN_HEIGHT = 400

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

FPS = 60

# --- functions --- (lower_case names)

def draw_lines(screen, number, delta_angle, start_angle, width=1):

    angle = start_angle

    for i in range(number):

        radiants = math.radians(angle-90)

        x = round(line_start[0] + math.cos(radians) * line_len)
        y = round(line_start[1] + math.sin(radians) * line_len)

        pygame.draw.line(screen, line_color, line_start, (x, y), width)

        angle += delta_angle


# --- main --- (lower_case names)

# - init -

pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
screen_rect = screen.get_rect()

# - objects-

line_start = screen_rect.center
line_len = 200
line_color = WHITE

start_angle = 0

# - mainloop -

clock = pygame.time.Clock()

running = True

while running:

    # - events -

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False

    # - updates (without draws) -

    start_angle += 0.5

    # - draws (without updates) -

    screen.fill(BLACK)

    draw_lines(screen, 4, 90, start_angle)

    pygame.display.flip()

    # - constant speed - FPS -

    clock.tick(FPS)

# - end -

pygame.quit()

顺便说一句: 我改名是因为:PEP 8 -- Style Guide for Python Code


顺便说一句: 参见时钟示例 Clock in Python