利用Pygame繪制圓環(huán)的示例代碼
三角函數
如果我們以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繪制圓環(huán)的示例代碼的文章就介紹到這了,更多相關Pygame繪制圓環(huán)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解Python中__new__和__init__的區(qū)別與聯(lián)系
在Python中,每個對象都有兩個特殊的方法:__new__和__init__,本文將詳細介紹這兩個方法的不同之處以及它們之間的聯(lián)系,具有一定的參考價值,感興趣的可以了解一下2023-12-12解決python3.6用cx_Oracle庫連接Oracle的問題
這篇文章主要介紹了解決python3.6用cx_Oracle庫連接Oracle的問題,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12pycharm遠程連接服務器并配置python interpreter的方法
這篇文章主要介紹了pycharm遠程連接服務器并配置python interpreter的方法,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12Python實現(xiàn)HTTP協(xié)議下的文件下載方法總結
這篇文章主要介紹了Python實現(xiàn)HTTP協(xié)議下的文件下載方法總結,包括端點續(xù)傳下載等功能,需要的朋友可以參考下2016-04-04python GUI庫圖形界面開發(fā)之PyQt5 UI主線程與耗時線程分離詳細方法實例
這篇文章主要介紹了python GUI庫圖形界面開發(fā)之PyQt5 UI主線程與耗時線程分離詳細方法實例,需要的朋友可以參考下2020-02-02