import pygame
import time
from pygame.locals import *

from locals import *

import os


class Animation:
# New constructor with filename as an argument - load_animation function omitted
    def __init__(self):
        #Assigns default values for a stationary object
        self.surface = None
        self.frames = 1
        self.center = (0,0)
        self.size = (0,0)
        self.dir = (0,0)
        self.name = ""
        self.walkover = False
        self.walkoverlevel = 0

        self.framesize = (0,0)

        self.frame = 0

    def load_surface(self, object_name, animation_name = None):
        self.name = animation_name

        filename = os.path.join("images", object_name)
        if animation_name:
            filename = filename + "_" + animation_name
        filename += ".png"
        self.surface = pygame.image.load(filename).convert_alpha()
        self.framesize = (self.surface.get_width() / self.frames,
                          self.surface.get_height())


    def set_frames(self, frames):
        self.frames = frames
        if self.surface:
            self.framesize = (self.surface.get_width() / self.frames, self.surface.get_height())

    def update(self):
        self.frame += 1
        while self.frame >= self.frames:
            self.frame -= self.frames

    def draw(self, screen, pos):
        rect = (self.framesize[0] * self.frame, 0,
                self.framesize[0], self.framesize[1])
        pos = (pos[0] - self.center[0],
               pos[1] - self.center[1])
        screen.blit(self.surface, pos, rect)

def main():
    pygame.init()

    screen = pygame.display.set_mode((640,480))

    anim = Animation()
    anim.load_surface("zombie", "hitting_west")
    anim.set_frames(9)

    done = False
    lastupdate = pygame.time.get_ticks()

    while not done:
        for e in pygame.event.get():
            if e.type == QUIT:
                done = True
            if e.type == KEYDOWN and e.key == K_ESCAPE:
                done = True

        screen.fill((0,0,0))

        anim.draw(screen, (300,200))
        sleeptime = (1000 / FPS - (pygame.time.get_ticks() - lastupdate)) * 0.001
        if sleeptime > 0:
           time.sleep(sleeptime)
        lastupdate = pygame.time.get_ticks()
        anim.update()

        pygame.display.flip()

if __name__ == "__main__":
    main()
