# Pygame
import pygame
from pygame.locals import *

# PGU
from pgu import engine

# Mòduls propis
import conf
from cotxes import Cotxe


# Classe joc
class Joc(engine.Game):

    # Initialize screen, pygame modules, clock... and states.
    def __init__(self):
        super().__init__()
        self.screen = pygame.display.set_mode(conf.mides_pantalla, SWSURFACE)
        self.crono = pygame.time.Clock()
        self._init_state_machine()

    # Creates and stores all states as attributes
    def _init_state_machine(self):
        self.jugant = Jugant(self)

    # Calls the main loop with the initial state.
    def run(self): 
        super().run(self.jugant, self.screen)

    # Tick is called once per frame. It shoud control de timing.
    def tick(self):
        self.crono.tick(conf.fps)   # Limits the maximum FPS


# A state may subclass engine.State.
class Jugant(engine.State):

    # The init method should load data, etc.  The __init__ method
    # should do nothing but record the parameters.  If the init method
    # returns a value, it becomes the new state.
    def init(self):
        grup = pygame.sprite.RenderPlain() # grup de Sprites
        imc = pygame.image.load('cotxe.png')
        c1 = Cotxe(imc, 50, 1)
        c2 = Cotxe(imc, 100, 3)
        c3 = Cotxe(imc, 150, 2)
        c4 = Cotxe(imc, 200, 5)
        grup.add(c1)
        grup.add(c2)
        grup.add(c3)
        grup.add(c4)
        self.all_sprites = grup
 
    # The paint method is called once.  If you call repaint(), it
    # will be called again.
    def paint(self,screen):
        screen.fill(conf.color_fons)

    # Loop is called once a frame.  It should contain all the logic.
    # If the loop method returns a value it will become the new state.
    def loop(self):
        self.all_sprites.update()

    # Update is called once a frame.  It should update the display.
    def update(self, screen):
        screen.fill(conf.color_fons)
        self.all_sprites.draw(screen)
        pygame.display.flip()


# Programa principal
def main():
    game = Joc()
    game.run()


# Crida el programa principal només si s'executa el mòdul:
#
#   python3 main_cotxes.py
#
# o bé
#
#   python3 -m main_cotxes
#
# Importa les funcions i les classes, però no executa el programa
# principal si s'importa el mòdul:
#
#   import joc
if __name__ == "__main__":
    main()
