利用Pygame繪制圓環(huán)的示例代碼
三角函數(shù)

如果我們以OP作為圓的半徑r,以o點作為圓的圓心,圓上的點的x坐標就是r * cos a ,y坐標就是 r * sin a。
python中提供math.cos() 和 math.sin(),要求參數(shù)為弧度。
弧度和角度的關系
PI代表180度,PI就是圓周率:3.1415926 535 897392 23846,python提供了角度和弧度的轉化
math.degress() 弧度轉角度
math.radiens() 角度轉弧度
a = math.cos(math.radians(90))
90度的橫坐標為0,但因為PI不是浮點小數(shù),導致運算不準確,是接近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繪制圓環(huán)的示例代碼的文章就介紹到這了,更多相關Pygame繪制圓環(huán)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python opencv實現(xiàn)切變換 不裁減圖片
這篇文章主要為大家詳細介紹了python opencv實現(xiàn)切變換,不裁減圖片,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-07-07
Python3讀取和寫入excel表格數(shù)據(jù)的示例代碼
這篇文章主要介紹了Python3讀取和寫入excel表格數(shù)據(jù)的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-06-06

