Pygame游戏(2) 转圈圈的圆
第一步,我们得先知道如何在屏幕上绘制一个圆
这里,我们调用pygame的一个函数
pygame.draw.circle(Surface,color,pos,radius,width)
说明:
Surface: 圆的绘制对象(要把圆绘制到哪个窗口上)
Color: 圆的填充颜色
pos: 圆心的x,y坐标
radius: 圆的半径
width: 圆的边缘宽度,默认为0,即完全填充
第二步:我们先在屏幕上绘制一个圆(注释在代码行的后面):
import pygame,sys
from pygame.locals import *
pygame.init() #初始化游戏
screen = pygame.display.set_mode((600,500)) #创建窗口
pygame.display.set_caption("圆") #设置标题
screen.fill((255,255,255)) #窗口的背景颜色
pos_x = 300 #圆心的x坐标
pos_y = 250 #圆心的y坐标
radius = 20 #圆的半径
while True: #设置游戏循环
for event in pygame.event.get(): #获取事件
if event.type == pygame.QUIT: #如果事件是鼠标点击窗口右上角的关闭按钮
sys.exit() #退出游戏
keys = pygame.key.get_pressed() #获取键盘事件
if keys[K_ESCAPE]: #如果按下ESC键
sys.exit() #退出游戏
pygame.draw.circle(screen,color,(pos_x,pos_y),radius,0) #绘制圆
pygame.display.update() #刷新屏幕
好了,是不是很简单呢,接下去让我们继续修改吧
第三步,使用数学函数和随机函数(注释在代码行的后面)
import sys,random,math,pygame
from pygame.locals import *
pygame.init() #初始化游戏
screen = pygame.display.set_mode((600,500)) #创建窗口
pygame.display.set_caption("转圈圈的圆") #设置标题
screen.fill((255,255,255)) #窗口的背景颜色
pos_x = 300 #圆心的x坐标
pos_y = 250 #圆心的y坐标
radius = 200 #圆的半径
angle = 360 #初始角度
while True: #设置游戏循环
for event in pygame.event.get(): #获取事件
if event.type == pygame.QUIT: #如果事件是鼠标点击窗口右上角的关闭按钮
sys.exit() #退出游戏
keys = pygame.key.get_pressed() #获取键盘事件
if keys[K_ESCAPE]: #如果按下ESC键
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 #调用cos,sin函数(以弧度作为参数)让圆心在圆周上移动
y = math.sin(math.radians(angle)) * radius #将角度转化为弧度,需导入math库
pos = (int(pos_x + x),int(pos_y + y)) #让圆心发生变化
pygame.draw.circle(screen,color,pos,30,0) #绘制圆
pygame.display.update() #刷新屏幕
这里有几个需要注意的地方:
1、要计算绕着一个圆的圆周的任何点的x坐标,使用余弦函数,math.cos(),需要以弧度作为参数,而不是角度,如果你想使用角度和话,通过math.radians()将角度转化为弧度就可以了。
2、同理,计算绕着一个圆的圆周的任何点的y坐标也是这样计算。
3、将上述两步的结果和半径相乘 x=math.cos(math.radians(angle))*radius
简单画个图便可知道
这样会导致这个点从圆心移动到圆周上,让angle不断变化,达到遍历圆周的每个点的用途。
好了,是不是觉得小有意思呢