网络编程
位置:首页>> 网络编程>> Python编程>> 利用Pygame绘制圆环的示例代码

利用Pygame绘制圆环的示例代码

作者:我的天才女友  发布时间:2022-04-02 12:55:05 

标签:Pygame,圆环

三角函数

利用Pygame绘制圆环的示例代码

如果我们以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)

利用Pygame绘制圆环的示例代码

全部代码

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)

来源:https://blog.csdn.net/qq_40801987/article/details/122584401

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com