import pygame from math import sin,cos,radians class Durtle(): """Durtle取名自Draw与turtle的组合,它是用来生成图像的""" def __init__(self,image,heading = 0,width=1,color=(0,0,0)): self.__pensize__ = width # 笔迹宽度,对应的是draw.circle的半径 self.__color__ = color # rgb255颜色 self.__image__ = image # 在哪个图像上画 self.__heading__ = heading self.__imagerect__ = self.__image__.get_rect() # 获取图像的rect,描述坐标与长高的 self.__width__ = self.__imagerect__.width # 图像的宽 self.__height__ = self.__imagerect__.height # 图像的高 self.x = self.__width__//2 # 起始x坐标 self.y = self.__height__//2 # 起始y坐标 def setheading(self,heading): """设定方向,以0度为向右,90度为向上,180度为向左,270度为向下""" self.__heading__ = heading def right(self,angle): """右转""" self.__heading__ = (self.__heading__ - angle) % 360 def left(self,angle): """左转""" self.__heading__ = (self.__heading__ + angle) % 360 def forward(self,step): """朝当前方向移动step像素""" if step == 0 :return length = abs(step) k = length / step for i in range(length): pygame.draw.circle(self.__image__,self.__color__,(int(self.x),int(self.y)),self.__pensize__) self.x = self.x + k * cos(radians(self.__heading__)) self.y = self.y - k * sin(radians(self.__heading__)) def save(self,filename = "test_demo2.png"): pygame.image.save(self.__image__,filename) if __name__ == "__main__": image = pygame.Surface((1024,1024),pygame.SRCALPHA,32) #创建透明图像 p =Durtle(image,30,2,(15,250,55)) for i in range(36): p.forward(100) p.forward(-100) p.right(10) p.save()
李兴球
李兴球的博客是Python创意编程原创博客