海龟画图移动方式的箭头类

"""海龟画图移动方式的箭头类,这个程序设计了一个箭头类,实例化它会不断地朝向鼠标指针的方向,并且按前进或后退方向箭头会移动。
这是制作游戏的一个基本例程。"""

import pygame
from pygame.locals import *
import math


class Arrow():
    """箭头类,移动方式为朝向自己的方向移动"""

    def __init__(self, position,heading ):        
         
        self.raw_image=pygame.Surface((36,24))  # 新建原始图形       
        self.raw_image.set_colorkey((0,0,0))    # 设置不渲染颜色
        pointlist=[(0,7),(20,7),(20,0),(36,12),(20,24),(20,17),(0,17)]
        pygame.draw.polygon(self.raw_image,(255,255,255),pointlist)        
        self.image = self.raw_image        # 这个属性的初值和raw_image一样
        self.rect = self.raw_image.get_rect()       
        self.rect.center= position         # 初始坐标
        self.heading = heading             # 朝向

    def forward(self,distance):
        angle = math.radians(self.heading) # 把角度变为弧度 ,直接用2D向量,旋转的时候就要算角度       
        dx,dy =  distance*math.cos(angle),- distance*math.sin(angle)   
        self.rect.move_ip(dx,dy)      
        
    def turn(self,angle):
        self.heading = self.heading - angle
        self.heading = self.heading % 360
        self.setheading(self.heading)

    def setheading(self,heading):
        old_position = self.rect.center    # 记录老的坐标        
        self.image = pygame.transform.rotate(self.raw_image,self.heading)# 对图像进行旋转变形
        self.rect = self.image.get_rect()
        self.rect.center = old_position        
    
    def draw(self):
        """在screen上绘制箭头"""                
        screen.blit(self.image,self.rect)        
        
    def headingpoint(self,x,y):
        """朝向某点,算出新方向"""
        heading = math.atan2((x-self.rect.x),(y - self.rect.y))
        heading= math.degrees(heading) - 90
        self.heading = heading             # 算出了新的朝向
        self.setheading(heading)           # 那么图像就要变形

def main(screensize):
    clock = pygame.time.Clock()
    arrow = Arrow((screensize.centerx,screensize.centery),0)
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == QUIT:running= False                 
            if event.type == KEYDOWN   :
                if event.key == K_UP or event.key == K_w:
                    arrow.forward(10)
                if event.key == K_DOWN or event.key == K_s:
                    arrow.forward(-10)
                    
        mx,my = pygame.mouse.get_pos() 
        arrow.headingpoint(mx,my)
        
        screen.fill((112,0,23))        
        arrow.draw()
        pygame.display.update()
        clock.tick(30)
        
    pygame.quit()

    
if __name__=="__main__":
    
    pygame.init()
    screen = pygame.display.set_mode((480,360))
     
    screenrect = screen.get_rect()
    pygame.display.set_caption("pygame箭头类_朝向鼠标指针_作者:李兴球")

    main(screenrect)