#*-* encoding: utf-8 *-*
import pygame, random, sys
from pygame.locals import *

WINDOWWIDTH = 1024
WINDOWHEIGHT = 768
TEXTCOLOR = (255, 198, 0)
BACKGROUNDCOLOR = (0, 30, 0)
FPS = 40
BADDIEMINSIZE = 10
BADDIEMAXSIZE = 40
BADDIEMINSPEED = 1
BADDIEMAXSPEED = 8
ADDNEWBADDIERATE = 8
PLAYERMOVERATE = 8
PUKKAUS = 50

def terminate():
    pygame.quit()
    sys.exit()

def waitForPlayerToPressKey(oldPlayerNumber):
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()
            if event.type == MOUSEBUTTONDOWN:
                return oldPlayerNumber
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE or event.key == ord('q'): # pressing escape quits
                    terminate()
                if event.key == K_SPACE or event.key == K_RETURN:
                    return oldPlayerNumber
                if event.key == ord('1'):
                    return 1
                if event.key == ord('2'):
                    return 2

def playerHasHitBaddie(playerRect, baddies):
    for b in baddies:
        if playerRect.colliderect(b['rect']):
            return True
    return False

def playerHasHitPlayer(playerRect, playerRect2):
    if playerRect.colliderect(playerRect2):
        return True
    return False
            
def drawText(text, font, surface, x, y):
    textobj = font.render(text, 1, TEXTCOLOR)
    textrect = textobj.get_rect()
    textrect.topleft = (x, y)
    surface.blit(textobj, textrect)

# set up pygame, the window, and the mouse cursor
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
#pygame.display.set_caption(u'Möröt hyökkää!'.encode('utf-8'))
pygame.display.set_caption(u'Möröt hyökkää!')
pygame.mouse.set_visible(False)

# set up fonts
font = pygame.font.SysFont(None, 48)

# set up sounds
gameOverSound = pygame.mixer.Sound('peliloppu.wav')
pygame.mixer.music.load('taustamusa.mid')

# set up images
playerImage = pygame.image.load('superhahmo.png')
playerImage2 = pygame.image.load('superkakkonen.png')
playerRect = playerImage.get_rect()
playerRect2 = playerImage2.get_rect()
baddieImage = pygame.image.load('hirvio.png')

# show the "Start" screen
drawText(u'Varo pahoja mörköjä!', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText(u'Valitse supersipulien määrä', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50)
drawText(u'PAINA 1 tai 2', font, windowSurface, (WINDOWWIDTH / 3) + 70, (WINDOWHEIGHT / 3) + 100)
pygame.display.update()
playerNumber = waitForPlayerToPressKey(1)

# Loads top score
try:
  scorefile = open('topscore', 'r')
  topScore = int(scorefile.readline())
  scorefile.close()
except IOError:
  topScore = 0

while True:
    # set up the start of the game
    baddies = []
    score = 0
    if playerNumber == 1:
        playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 150)
    else:
        playerRect.topleft = ((WINDOWWIDTH / 4) * 3, WINDOWHEIGHT - 150)
        playerRect2.topleft = (WINDOWWIDTH / 4, WINDOWHEIGHT - 150)
    moveLeft = moveRight = moveUp = moveDown = False
    moveLeft2 = moveRight2 = moveUp2 = moveDown2 = False
    baddieAddCounter = 0
    pygame.mixer.music.play(-1, 0.0)

    while True: # the game loop runs while the game part is playing
        score += 1 # increase score

        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()

            if event.type == KEYDOWN:
            
                # player 1
                if event.key == K_LEFT:
                    moveRight = False
                    moveLeft = True
                if event.key == K_RIGHT:
                    moveLeft = False
                    moveRight = True
                if event.key == K_UP:
                    moveDown = False
                    moveUp = True
                if event.key == K_DOWN:
                    moveUp = False
                    moveDown = True
                    
                # player 2
                if playerNumber == 2:
                    if event.key == ord('a'):
                        moveRight2 = False
                        moveLeft2 = True
                    if event.key == ord('d'):
                        moveLeft2 = False
                        moveRight2 = True
                    if event.key == ord('w'):
                        moveDown2 = False
                        moveUp2 = True
                    if event.key == ord('s'):
                        moveUp2 = False
                        moveDown2 = True

            if event.type == KEYUP:

                if event.key == K_ESCAPE:
                        terminate()

                # player 1
                if event.key == K_LEFT:
                    moveLeft = False
                if event.key == K_RIGHT:
                    moveRight = False
                if event.key == K_UP:
                    moveUp = False
                if event.key == K_DOWN:
                    moveDown = False

                # player 2
                if playerNumber == 2:
                  if event.key == ord('a'):
                      moveLeft2 = False
                  if event.key == ord('d'):
                      moveRight2 = False
                  if event.key == ord('w'):
                      moveUp2 = False
                  if event.key == ord('s'):
                      moveDown2 = False
                    
                    
            if event.type == MOUSEMOTION:
                # If the mouse moves, move the player where the cursor is.
                playerRect.move_ip(event.pos[0] - playerRect.centerx, event.pos[1] - playerRect.centery)

        # Add new baddies at the top of the screen, if needed.
        baddieAddCounter += 1
        if baddieAddCounter == ADDNEWBADDIERATE:
            baddieAddCounter = 0
            baddieSize = random.randint(BADDIEMINSIZE, BADDIEMAXSIZE)
            newBaddie = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-baddieSize), 0 - baddieSize, baddieSize, baddieSize),
                        'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
                        'surface':pygame.transform.scale(baddieImage, (baddieSize, baddieSize)),
                        }

            baddies.append(newBaddie)


        # Move the player around.
        if moveLeft and playerRect.left > 0:
            playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
        if moveRight and playerRect.right < WINDOWWIDTH:
            playerRect.move_ip(PLAYERMOVERATE, 0)
        if moveUp and playerRect.top > 0:
            playerRect.move_ip(0, -1 * PLAYERMOVERATE)
        if moveDown and playerRect.bottom < WINDOWHEIGHT:
            playerRect.move_ip(0, PLAYERMOVERATE)

        # Move the player2 around.
        if playerNumber == 2:
            if moveLeft2 and playerRect2.left > 0:
                playerRect2.move_ip(-1 * PLAYERMOVERATE, 0)
            if moveRight2 and playerRect2.right < WINDOWWIDTH:
                playerRect2.move_ip(PLAYERMOVERATE, 0)
            if moveUp2 and playerRect2.top > 0:
                playerRect2.move_ip(0, -1 * PLAYERMOVERATE)
            if moveDown2 and playerRect2.bottom < WINDOWHEIGHT:
                playerRect2.move_ip(0, PLAYERMOVERATE)
            
        # Move the baddies down.
        for b in baddies:
            b['rect'].move_ip(0, b['speed'])


         # Delete baddies that have fallen past the bottom.
        for b in baddies[:]:
            if b['rect'].top > WINDOWHEIGHT:
                baddies.remove(b)

        # Draw the game world on the window.
        windowSurface.fill(BACKGROUNDCOLOR)

        # Draw the score and top score.
        drawText(u'Pisteet: %s' % (score), font, windowSurface, 10, 0)
        drawText(u'Ennätys: %s' % (topScore), font, windowSurface, 10, 40)
        drawText(u'Supersipuleita: %d' % (playerNumber), font, windowSurface, 10, 80)

        # Draw the player's rectangle
        windowSurface.blit(playerImage, playerRect)
        if playerNumber == 2:
            windowSurface.blit(playerImage2, playerRect2)

        # Draw each baddie
        for b in baddies:
            windowSurface.blit(b['surface'], b['rect'])

        pygame.display.update()

        # Check if any of the baddies have hit the player.
        if playerHasHitBaddie(playerRect, baddies):
            loser = 1
            if score > topScore:
                topScore = score # set new top score
                scorefile = open('topscore', 'w')
                scorefile.write(str(topScore))
                scorefile.close()
            break

        if playerNumber == 2 and playerHasHitBaddie(playerRect2, baddies):
            loser = 2
            if score > topScore:
                topScore = score # set new top score
                scorefile = open('topscore', 'w')
                scorefile.write(str(topScore))
                scorefile.close()
            break
            
        # sipulien törmäys. Sipulit sinkoavat eroon toisistaan.
        if playerNumber == 2 and playerHasHitPlayer(playerRect, playerRect2):
        
            # Inits variables
            playerUp = False
            playerDown = False
            playerLeft = False
            playerRight = False
            player2Up = False
            player2Down = False
            player2Left = False
            player2Right = False

            # Pukkaus suunnat        
            if playerRect.centerx < playerRect2.centerx:
                playerLeft = True
                player2Right = True
            if playerRect.centerx > playerRect2.centerx:
                playerRight = True
                player2Left = True
            if playerRect.centery > playerRect2.centery:
                playerUp = True
                player2Down = True
            if playerRect.centery < playerRect2.centery:
                playerDown = True
                player2Up = True
           
            # Pelaaja 1 pukkaus
            if playerUp:
                playerRect.move_ip(0, PUKKAUS)
                if playerRect.centery > WINDOWHEIGHT:
                  playerRect.centery = WINDOWHEIGHT
            if playerDown:
                playerRect.move_ip(0, -PUKKAUS)
                if playerRect.centery < 0:
                  playerRect.centery = 0
            if playerRight:
                playerRect.move_ip(PUKKAUS,0)
                if playerRect.centerx > WINDOWWIDTH:
                  playerRect.centerx = WINDOWWIDTH
            if playerLeft:
                playerRect.move_ip(-PUKKAUS,0)
                if playerRect.centerx < 0:
                  playerRect.centerx = 0

            # Pelaaja 2 pukkaus
            if player2Up:
                playerRect2.move_ip(0, PUKKAUS)
                if playerRect2.centery > WINDOWHEIGHT:
                  playerRect2.centery = WINDOWHEIGHT
            if player2Down:
                playerRect2.move_ip(0, -PUKKAUS)
                if playerRect2.centery < 0:
                  playerRect2.centery = 0
            if player2Right:
                playerRect2.move_ip(PUKKAUS,0)
                if playerRect2.centerx > WINDOWWIDTH:
                  playerRect2.centerx = WINDOWWIDTH
            if player2Left:
                playerRect2.move_ip(-PUKKAUS,0)
                if playerRect2.centerx < 0:
                  playerRect2.centerx = 0

        # Move the mouse cursor to match the player.
        pygame.mouse.set_pos(playerRect.centerx, playerRect.centery)
        
        mainClock.tick(FPS)

    # Stop the game and show the "Game Over" screen.
    pygame.mixer.music.stop()
    gameOverSound.play()

    drawText(u'PELI LOPPU!', font, windowSurface, (WINDOWWIDTH / 3) - 40, (WINDOWHEIGHT / 3))
    if loser == 1:
          drawText(u'VIHERSIPULI päätyi mörköjen pataan!', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
    else:
          drawText(u'PUNASIPULI päätyi mörköjen pataan!', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
    drawText(u'Valitse supersipulien määrä', font, windowSurface, (WINDOWWIDTH / 3) - 10, (WINDOWHEIGHT / 3) + 150)
    drawText(u'PAINA 1 tai 2', font, windowSurface, (WINDOWWIDTH / 3) + 90, (WINDOWHEIGHT / 3) + 200)

    pygame.display.update()
    playerNumber = waitForPlayerToPressKey(playerNumber)

    gameOverSound.stop()
