import os, sys
from grid import Grid
import pygame
from pygame.locals import *
from shape import Shape
import copy

def main():
	pygame.init()
	screen = pygame.display.set_mode([300, 720])
	white = 255, 255, 255
	black = 0, 0, 0
	purple = 155, 0, 155
	cleared = []
	current_shape = Shape()
	grid = Grid()
	lost = False
	
	while 1:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				sys.exit()
			
			elif event.type == KEYDOWN:
				if event.key == K_RIGHT:
					current_shape.status = 'moveright'
				if event.key == K_LEFT:
					current_shape.status = 'moveleft'
				if event.key == K_SPACE:
						lost = False
			elif event.type == KEYUP:
				if event.key == K_RIGHT and current_shape.status == 'moveright':
					current_shape.status = None
				if event.key == K_LEFT and current_shape.status == 'moveleft':
					current_shape.status = None
	
		if not grid.is_valid(current_shape.status, current_shape): #check if proposed move is legal
			current_shape.status = None		

		grid.move_down(cleared) #move down blocks if a row has been cleared
		
		cleared = grid.row_check()  #check for cleared rows
		
		grid.clear_rows(cleared) #delete blocks from cleared rows
		
		at_bottom = grid.collided_vert(current_shape) #check if the current shape can move down further
		
		current_shape.at_bottom = at_bottom
		
		current_shape.update() #move the current shape


		if at_bottom: #shape can't go down further so add its blocks to the list of blocks
			grid.add_blocks(current_shape.blocks)
			current_shape = Shape()
			if grid.collided_vert(current_shape):
				lost = True
		
		screen.fill(white)

		for b in current_shape.blocks: #draw the current shape's blocks on the screen
			pygame.draw.rect(screen, b.color, b, 0) #once for fill
			pygame.draw.rect(screen, black, b, 1)	#once for outline
		
		for bk in grid.blocks: #draw all other blocks on the screen
			pygame.draw.rect(screen, bk.color, bk, 0)
			pygame.draw.rect(screen, black, bk, 1)
		
		if lost:
			font = pygame.font.Font(None, 50)
			text = font.render("You lost!", 1, purple)
			text_rect = text.get_rect(centerx=screen.get_width()/2, centery=screen.get_height()/2)
			screen.fill(white)
			screen.blit(text, text_rect)
			grid = Grid()
			current_shape = Shape()

			
		pygame.display.update()
		pygame.time.delay(200)
		
	

if __name__ == '__main__': main()
