from xdf import *


class SpriteSheet:
    def __init__(self, arr, config):
        self.isPlaying = True
        self.isFlag = False
        self.currentFrame = 0
        self.totalFrames = len(arr)
        self.stamps = []
        self.config = config
        for i in range(len(arr)):
            sp = stamp(arr[i])
            self.stamps.append(sp)
            sp.hide()
    
    def play(self):
        self.isPlaying = True
    
    def stop(self):
        self.isPlaying = False
    
    def gotoAndStop(self, n):
        self.currentFrame = n;
        self.stop()
    
    def gotoAndPlay(self, n):
        self.currentFrame = n;
        self.play()
    
    def nextFrame(self):
        self.currentFrame = self.currentFrame + 1
        if self.isFlag:
            if self.currentFrame > self.flagEnd:
                self.currentFrame = self.flagStart
        elif self.currentFrame >= self.totalFrames:
            self.currentFrame = 0
    
    def playFlag(self, flag):
        if flag in self.config:
            a = self.config[flag]
            self.flagStart = a[0]
            self.flagEnd = a[1]
            self.isFlag = True
            self.gotoAndPlay(self.flagStart);
    
    def clearPlayFlag(self):
        self.isFlag = False
    
    def update(self):
        if self.isPlaying:
            self.nextFrame()    
        for i in range(len(self.stamps)):
            self.stamps[i].hide()
        if self.totalFrames > 0:
            self.stamps[self.currentFrame].show()

hero = SpriteSheet(
    ['hero1.png', 'hero2.png', 'hero3.png', 'hero4.png', 'hero5.png', 'hero6.png', 'hero7.png', 'hero8.png', 'hero9.png', 'hero10.png', 'hero11.png', 'hero12.png', 'hero13.png', 'hero14.png', 'hero15.png', 'hero16.png', 'hero17.png', 'hero18.png', 'hero19.png', 'hero20.png'],
    {
        'stand': [0, 4],
        'run': [5, 10],
        'jump': [11, 13],
        'jump2': [14, 19]
    }
)

def updateN(n):
    global hero, actions, tf2
    hero.playFlag(actions[n])
    tf2.change(actions[n])

def tap():
    global n
    n = n + 1
    if n == len(actions):
        n = 0
    updateN(n)

def loop():
    hero.update()

text("点击切换动画", 100, 100, 50, 'red', 'lisu')
tf2 = text("", 100, 200, 50, 'red')
n = 0
actions = ['stand', 'run', 'jump', 'jump2']
updateN(0)

import xdf
xdf.loop = loop
xdf.tap = tap

go()

