Pygame画一个彩色圆盘(颜色渐变与仿海龟画图)

"""用Pygame画一个彩色圆盘,这是本人曾经学习Pygame的一个练习程序。
   本程序定义一个笔类,它有forward方法,能朝自己的方向前进,但是有误差! 减小这个误差需要全部用浮点数表示数据.
本程序实例化这支笔画了一个彩色的圆盘.笔的x,y坐标是数学坐标系(scratch类的舞台坐标系),非计算机屏幕的左上角为原点的坐标素(x朝右为正,y朝下为正这个坐标系)。
"""
import math
import pygame
import colorsys
from pygame.locals import *

class Pen():
    def __init__(self,color,thickness):
        self.image = pygame.Surface((12,12))
        pygame.draw.circle(self.image,color,(6,6),6)
        pygame.display.update()
        self.rect = self.image.get_rect()
        self.color = color         # 笔颜色
        self.thickness = thickness # 笔迹宽度        
        self.rect.centerx = screenCenterx 
        self.rect.centery = screenCentery 
        self.heading = 0          # 朝向,是与新y轴的夹角
        self.status = 0           # 0表示抬笔,1表示落笔
        self.visible = 1          # 0表示隐藏笔,1表示显示笔(就是那个小点)
    def down(self):
        self.status = 1
    def up(self):
        self.status = 0
    def show(self):
        self.visible = 1
    def hide(self):
        self.visible = 0
    def drawaxis(self):
        """画x轴和y轴"""
        pygame.draw.line(screen,(255,255,255),(0,screenCentery),(screenWidth,screenCentery))
        pygame.draw.line(screen,(255,255,255),(screenCenterx,0),(screenCenterx,screenHeight))
    def setxy(self,x,y):
        self.rect.centerx = screenCenterx + x
        self.rect.centery = screenCentery - y
    def setHeading(self,heading):
        self.heading = heading % 360


    def turn(self,angle):
        self.heading = (self.heading + angle) % 360
    
    def forward(self,step):
        
        oldx = self.rect.centerx
        oldy = self.rect.centery
        # 乘以1000是用来消除误差,但好像没有效果,误差可能来源于角度旋转带来。
        newx   = 1000* self.rect.centerx + 1000* step * math.sin(math.radians(self.heading))
        newy  = 1000* self.rect.centery - 1000* step * math.cos(math.radians(self.heading))
        self.rect.centerx = newx //1000
        self.rect.centery = newy //1000
        if self.status==1:           # 如果落笔,那么就画线
            pygame.draw.line(screen,self.color,(oldx,oldy),(self.rect.centerx,self.rect.centery),self.thickness)        
    
    def coloradd(self):
        h,l,s, = colorsys.rgb_to_hls(self.color[0]/255,self.color[1]/255,self.color[2]/255)
        h =  h + 0.01
        r,g,b = colorsys.hls_to_rgb(h,l,s)
        self.color = (int(r*255),int(g*255),int(b*255))
    def draw(self):
        if self.visible==1:
            screen.blit(self.image,self.rect)

You must log in to read the rest of this article. Please log in or register as a user.