日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

利用Pygame繪制圓環(huán)的示例代碼_python

作者:我的天才女友 ? 更新時(shí)間: 2022-04-02 編程語言

三角函數(shù)

如果我們以O(shè)P作為圓的半徑r,以o點(diǎn)作為圓的圓心,圓上的點(diǎn)的x坐標(biāo)就是r * cos a ,y坐標(biāo)就是 r * sin a。

python中提供math.cos() 和 math.sin(),要求參數(shù)為弧度。

弧度和角度的關(guān)系

PI代表180度,PI就是圓周率:3.1415926 535 897392 23846,python提供了角度和弧度的轉(zhuǎn)化

math.degress() 弧度轉(zhuǎn)角度

math.radiens() 角度轉(zhuǎn)弧度

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

90度的橫坐標(biāo)為0,但因?yàn)镻I不是浮點(diǎn)小數(shù),導(dǎo)致運(yùn)算不準(zhǔn)確,是接近0的一個(gè)值。

基本包和事件捕捉

初始化窗口,配置圓心和半徑,添加了定時(shí)器便于控制繪制的速度

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

# 定時(shí)器
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開始,隨機(jī)一個(gè)顏色,計(jì)算出這個(gè)角度上的大圓上的點(diǎn),以這個(gè)點(diǎn)畫一個(gè)半徑為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

# 定時(shí)器
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

欄目分類
最近更新