目录
  • 三角函数
  • 弧度和角度的关系
  • 基本包和事件捕捉
  • 主程序
  • 全部代码

三角函数

如果我们以op作为圆的半径r,以o点作为圆的圆心,圆上的点的x坐标就是r * cos a ,y坐标就是 r * sin a。

python中提供math.cos() 和 math.sin(),要求参数为弧度。

弧度和角度的关系

pi代表180度,pi就是圆周率:3.1415926 535 897392 23846,python提供了角度和弧度的转化

math.degress() 弧度转角度

math.radiens() 角度转弧度

a = math.cos(math.radians(90))

90度的横坐标为0,但因为pi不是浮点小数,导致运算不准确,是接近0的一个值。

基本包和事件捕捉

初始化窗口,配置圆心和半径,添加了定时器便于控制绘制的速度

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

pygame.init()
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("梦幻圆")
screen.fill((0, 0, 100))

pos_x = 300
pos_y = 250
radius = 200
angle = 360

# 定时器
mainclock = pygame.time.clock()
while true:
    for event in pygame.event.get():
        if event.type == quit:
            pygame.quit()
            sys.exit()

    keys = pygame.key.get_pressed()
    if keys[k_escape]:
        pygame.quit()
        sys.exit()

主程序

角度不断的加,如果超过360度则重新重1开始,随机一个颜色,计算出这个角度上的大圆上的点,以这个点画一个半径为10的圆。   

angle += 1
    if angle >= 360:
        angle = 0

    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)
    color = r, g, b

    x = math.cos(math.radians(angle)) * radius
    y = math.sin(math.radians(angle)) * radius

    pos = (int(pos_x + x), int(pos_y + y))
    pygame.draw.circle(screen, color, pos, 10, 0)

    pygame.display.update()
    mainclock.tick(20)

全部代码

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

pygame.init()
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("梦幻圆")
screen.fill((0, 0, 100))

pos_x = 300
pos_y = 250
radius = 200
angle = 360

# 定时器
mainclock = pygame.time.clock()

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

    keys = pygame.key.get_pressed()
    if keys[k_escape]:
        pygame.quit()
        sys.exit()

    angle += 1
    if angle >= 360:
        angle = 0

    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)
    color = r, g, b

    x = math.cos(math.radians(angle)) * radius
    y = math.sin(math.radians(angle)) * radius

    pos = (int(pos_x + x), int(pos_y + y))
    pygame.draw.circle(screen, color, pos, 10, 0)

    pygame.display.update()
    mainclock.tick(10)

到此这篇关于利用pygame绘制圆环的示例代码的文章就介绍到这了,更多相关pygame绘制圆环内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!