import random

from pygame.locals import K_t, K_g, K_UP, K_DOWN, K_LEFT, K_RIGHT

from pygsear.Game import Game
from pygsear.Event import KEY_Event, TIMEOUT_Event, EventGroup
from pygsear.Widget import Dialog_OK, Score
from pygsear.locals import BLACK, WHITE, TRANSPARENT, BLUE, RED, YELLOW, GREEN

import Level
import Creature
import Target

class MathGame(Game):
    def initialize(self):
        self.score = Score(position=(100, 10), color=GREEN, bgcolor=BLACK)
        self.sprites.add(self.score)

        self.creature_controls = EventGroup()

        self.setLevel()

    def set_creature_controls(self):
        self.creature_controls.kill()

        cre = self.creature
        self.creature_controls.add(KEY_Event(key=K_LEFT, on_press=cre.start_left, on_release=cre.stop_left))
        self.creature_controls.add(KEY_Event(key=K_RIGHT, on_press=cre.start_right, on_release=cre.stop_right))
        self.creature_controls.add(KEY_Event(key=K_UP, on_press=cre.start_up, on_release=cre.stop_up))
        self.creature_controls.add(KEY_Event(key=K_DOWN, on_press=cre.start_down, on_release=cre.stop_down))

        self.events.add(self.creature_controls)

    def showInstructions(self):
        dlg = Dialog_OK(message=self.level.instructions)
        dlg.modal()

    def setLevel(self, level_number=1):
        self.level_number = level_number

        level_class = 'Level_%02d' % level_number
        level_type = getattr(Level, level_class)
        level = level_type()
        self.level = level

        self.set_background(tilename=level.bgimagetile)

        if hasattr(self, 'creature'):
            position = self.creature.get_position()
        else:
            position = None

        self.creature = level.creature_type()
        self.sprites.add(self.creature)
        self.set_creature_controls()

        if position is not None:
            self.creature.set_position(position)
        else:
            self.creature.center()

        for t in range(level.ntargets):
            level.make_target()

        #self.showInstructions()

    def checkCollisions(self):
        level = self.level
        target = self.creature.collidelist(level.targets.sprites())
        if target:
            if target.is_good_target():
                level.good_target_callback()
            else:
                level.bad_target_callback()
            self.score.updateScore()
            target.kill()

        if self.score.points >= level.next_level_score:
            self.creature.kill()
            level.targets.kill()
            level.events.kill()
            self.setLevel(self.level_number + 1)


