from os import mkdir, rename
from os.path import join, exists, dirname, basename
from time import strftime
from math import floor
from random import choice, random
from glob import glob

from pygame import Color, Rect, Surface
from pygame.font import Font
from pygame.image import load
from pygame.mixer import Sound
from pygame.event import clear
from pygame.locals import *

from _send.pgfw.GameChild import GameChild
from _send.pgfw.Animation import Animation
from _send.field.Field import Field
from _send.field.sideline.Sideline import Sideline
from _send.field.Charge import Charge
from _send.Send import SoundEffect

class Fields(Animation):

    def __init__(self, parent):
        Animation.__init__(self, parent)
        self.compare = self.get_delegate().compare
        self.load_configuration()
        self.subscribe(self.respond)
        self.set_sidelines()
        self.charge = Charge(self)
        self.life_meter = LifeMeter(self)
        self.score = Score(self)
        self.result = Result(self)
        music = self.music = []
        for path in sorted(glob(join(self.get_resource("fields", "music-path"),
                                     "[0-9]*"))):
            music.append(Sound(path))
        self.register(self.unsuppress_input)
        self.reset()
        self.read()

    def load_configuration(self):
        config = self.get_configuration("fields")
        self.palette_base = config["palette-base"]
        self.delimiter = config["delimiter"]
        self.fields_path = self.get_resource("fields", "path")
        self.backup_directory_name = self.\
                                     get_configuration("fields",
                                                       "backup-directory-name")

    def respond(self, event):
        if self.compare(event, "reset-game"):
            self.reset()
        elif self.compare(event, "raise-volume") or \
             self.compare(event, "lower-volume"):
            step = .1 * (-1 if event.command == "lower-volume" else 1)
            print step
            for sound in self.music:
                volume = sound.get_volume() + step
                print volume
                if volume < 0:
                    volume = 0
                elif volume > 1:
                    volume = 1
                sound.set_volume(volume)

    def reset(self):
        self.current_index = None
        for sound in self.music:
            sound.stop()
            sound.set_volume(self.get_configuration("fields",
                                                    "music-initial-volume"))
        self.music_index = None
        self.charge.reset()
        self.life_meter.reset()
        self.score.reset()
        self.result.reset()
        self.halt()
        self.suppressing_input = False
        self.loading = False

    def read(self, custom=False):
        path = self.custom_fields_path if custom else self.fields_path
        fields = self.fields = []
        index = {}
        for ii, line in enumerate(open(path)):
            name, parameters, background, foreground = \
                  map(str.strip, line.split(self.delimiter))
            ball, cup, speed, tartan_scale = parameters.split()
            background_color = self.parse_color(background)
            foreground_color = self.parse_color(foreground)
            fields.append(Field(self, name, float(ball), float(cup),
                                float(speed), float(tartan_scale),
                                background_color, foreground_color))
            index[name] = ii
        self.index = index

    def parse_color(self, color):
        return Color(*map(int, color.split(",")))

    def set_sidelines(self):
        self.sidelines = Sideline(self), Sideline(self, True)

    def get(self, name):
        return self.fields[self.get_index(name)]

    def get_index(self, name):
        return self.index[name]

    def get_current_field(self):
        if self.current_index is None:
            return
        return self.fields[self.current_index]

    def load(self, index=None, previous=False, suppress_title=False):
        if index is None:
            if not previous:
                index = self.get_next_index()
            else:
                index = self.get_previous_index()
        if not self.music[1].get_num_channels():
            self.music[1].play(-1)
        # if index / len(self.music) != self.music_index:
        #     if self.music_index is not None:
        #         self.music[self.music_index].fadeout(8000)
        #     self.music_index = index / len(self.music)
        #     self.music[self.music_index].play(-1, 0, 8000)
        current = self.get_current_field()
        if current:
            current.unload()
        self.fields[index].load(suppress_title)
        self.current_index = index
        for sideline in self.sidelines:
            sideline.refresh()
        self.charge.reset()
        self.loading = True

    def get_next_index(self):
        current = self.current_index
        if current is None:
            return 0
        if current == len(self.fields) - 1:
            return current
        return current + 1

    def get_previous_index(self):
        current = self.current_index
        if current is None or current == 0:
            return 0
        return current - 1

    def unsuppress_input(self):
        self.suppressing_input = False

    def write(self):
        fields_path = self.fields_path
        backup_directory_path = join(dirname(fields_path),
                                     self.backup_directory_name)
        if not exists(backup_directory_path):
            mkdir(backup_directory_path)
        rename(fields_path, join(backup_directory_path,
                                 "%s.%s" % (basename(fields_path),
                                            strftime("%Y%m%d%H%M%S"))))
        output = open(fields_path, "w")
        for field in self.fields:
            output.write("%s\n" % field)

    def update(self):
        current = self.get_current_field()
        if current:
            if self.suppressing_input and not self.is_playing(check_all=True):
                self.play(self.unsuppress_input, delay=500, play_once=True)
            current.update()
            for sideline in self.sidelines:
                sideline.update()
            self.charge.update()
            self.life_meter.update()
            self.score.update()
            self.result.update()
            if self.loading:
                self.loading = False
                self.suppressing_input = True
                clear()
        Animation.update(self)


class LifeMeter(GameChild, Rect):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.display_surface = self.get_display_surface()
        self.heart = load(self.get_resource("life-meter", "heart-path")).\
                     convert()
        self.miss = load(self.get_resource("life-meter", "miss-path")).\
                    convert()
        self.initial_lives = self.get_configuration("life-meter",
                                                    "initial-lives")
        self.max_lives = self.get_configuration("life-meter", "max-lives")
        Rect.__init__(self, 0, 0, self.heart.get_width() * self.max_lives,
                      self.heart.get_height())
        self.center = parent.sidelines[1].center
        self.reset()

    def reset(self):
        self.lives = self.initial_lives

    def remove_life(self):
        self.lives -= 1

    def add_life(self):
        if self.lives < self.max_lives:
            self.lives += 1

    def update(self):
        for ii, x in enumerate(xrange(0, self.w, self.w / self.max_lives)):
            image = self.heart if ii < self.lives else self.miss
            self.display_surface.blit(image, self.move(x, 0))


class Score(GameChild):

    def __init__(self, parent):
        GameChild.__init__(self, parent)
        self.display_surface = self.get_display_surface()
        font = self.font = Font(self.get_resource("display", "font-path"), 24)
        self.high_score = 0
        path = self.get_resource("score", "path")
        if path is not None:
            for line in open(path):
                if int(line) > self.high_score:
                    self.high_score = int(line)
        self.set_high_score_surface()
        self.reset()

    def set_high_score_surface(self):
        font = Font(self.get_resource("display", "font-path"), 10)
        top = font.render("best", True, (221, 172, 227), (255, 255, 255))
        bottom = font.render(str(self.high_score), True, (170, 132, 208),
                             (255, 255, 255))
        tr, br = top.get_rect(), bottom.get_rect()
        surface = self.high_score_surface = Surface((max(tr.w, br.w) + 4,
                                                     tr.h + br.h))
        surface.fill((255, 255, 255))
        rect = self.high_score_rect = surface.get_rect()
        tr.midtop = rect.midtop
        surface.blit(top, tr)
        br.midbottom = rect.midbottom
        surface.blit(bottom, br)
        rect.bottomright = self.display_surface.get_rect().bottomright

    def reset(self):
        self.score = 0
        self.set_surface()

    def increase(self, amount):
        self.score += amount
        self.set_surface()
        if self.score > self.high_score:
            self.high_score = self.score
            self.set_high_score_surface()

    def set_surface(self):
        text = str(self.score)
        font = self.font
        width, height = font.size(text)
        text_surface = Surface((width + 4, height), SRCALPHA)
        text_surface.blit(font.render(text, True, (255, 255, 0)), (0, 0))
        text_surface.blit(font.render(text, True, (0, 255, 0)), (4, 0))
        background = (255, 255, 255)
        text_surface.blit(font.render(text, True, (0, 0, 255)), (2, 0))
        text_rect = text_surface.get_rect()
        surface = self.surface = Surface(text_rect.inflate(12, 2).size,
                                         SRCALPHA)
        surface.fill(background)
        rect = self.rect = surface.get_rect()
        text_rect.center = rect.center
        rect.center = self.parent.sidelines[0].center
        surface.blit(text_surface, text_rect)

    def update(self):
        self.display_surface.blit(self.surface, self.rect)
        self.display_surface.blit(self.high_score_surface, self.high_score_rect)


class Result(Animation):

    def __init__(self, parent):
        Animation.__init__(self, parent, self.render)
        self.register(self.render,
                      self.get_configuration("result", "framerate"))
        self.delegate = self.get_game().delegate
        self.display_surface = self.get_display_surface()
        self.subscribe(self.respond)
        config = self.get_configuration("result")
        regions = self.regions = config["text"]
        portholes = self.portholes = {}
        for path in glob(join(self.get_resource("result", "porthole-path"),
                              "*")):
            portholes[basename(path).split(".")[0].upper()] = load(path).\
                                                              convert_alpha()
        self.font = Font(self.get_resource("display", "font-path"),
                         config["font-size"])
        self.main_color_probability = config["main-color-probability"]
        text_colors = self.text_colors = {}
        for ii, color in enumerate(config["colors"]):
            text_colors[regions[ii]] = Color(color + "FF")
        self.success_audio = SoundEffect(self.get_resource("result",
                                                           "success-audio"), .2)
        self.miss_audio = SoundEffect(self.get_resource("result", "miss-audio"),
                                      1.0)
        self.next_level_audio = SoundEffect(self.\
                                            get_resource("result",
                                                         "next-level-audio"),
                                            .1)
        self.reset()

    def respond(self, event):
        if self.is_playing() and self.delegate.compare(event, "any"):
            if self.success:
                self.parent.load()
                self.next_level_audio.play()
            else:
                if self.parent.life_meter.lives > 0:
                    self.parent.load(self.parent.current_index,
                                     suppress_title=True)
                else:
                    path = self.get_resource("score", "path")
                    if path is None:
                        path = join(\
                            self.get_configuration("setup",
                                                   "resource-search-path")[0],
                            self.get_configuration("score", "path"))
                    open(path, "a").write(str(self.parent.score.score) + "\n")
                    self.parent.score.reset()
                    self.parent.life_meter.reset()
                    self.parent.load(0)
            self.reset()

    def reset(self):
        self.halt()

    def render(self):
        font = self.font
        region = self.regions[self.region_index]
        color = self.text_colors[region]
        if self.region_index > 0 and random() > self.main_color_probability:
            colors = self.text_colors.copy()
            colors.pop(self.regions[0])
            colors.pop(region)
            color = choice(colors.values())
        text = font.render(region, True, color, (255, 255, 255))
        tr = text.get_rect()
        surface = self.text_surface = Surface((tr.w + 50, tr.h + 10), SRCALPHA)
        surface.fill((255, 255, 255))
        rect = self.text_rect = surface.get_rect()
        tr.center = rect.center
        surface.blit(text, tr)
        rect.center = self.display_surface.get_rect().center

    def evaluate(self):
        field = self.parent.get_current_field()
        ball, cup = field.ball, field.cup
        if not ball.rect.colliderect(cup.location):
            self.parent.life_meter.remove_life()
            self.set_region(0)
            self.success = False
            if self.parent.life_meter.lives > 0:
                self.miss_audio.play()
            else:
                self.miss_audio.play(-1)
                self.miss_audio.fadeout(2600)
        else:
            distance = max(abs(ball.location.centerx - cup.location.centerx),
                           abs(ball.location.centery - cup.location.centery))
            ratio = 1 - float(distance) / (cup.location.w / 2 + \
                                           ball.location.w / 2 + 1)
            index = int(floor(len(self.regions[1:]) * ratio))
            self.parent.score.increase((self.parent.current_index + 1) * \
                                       (index + 1))
            self.set_region(index + 1)
            self.success = True
            self.success_audio.play()
            fields = self.parent
            level_index = fields.current_index
            if level_index != len(fields.index) - 1 and level_index % 5 == 4:
                fields.life_meter.add_life()
        self.play()

    def set_region(self, index):
        self.region_index = index
        surface = self.porthole_surface = self.portholes[self.regions[\
            self.region_index]]
        rect = self.porthole_rect = surface.get_rect()
        rect.center = self.display_surface.get_rect().center

    def update(self):
        if self.is_playing():
            Animation.update(self)
            self.display_surface.blit(self.porthole_surface, self.porthole_rect)
            self.display_surface.blit(self.text_surface, self.text_rect)
3.15.143.181
3.15.143.181
3.15.143.181
 
June 7, 2018