/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package brokensnake;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import static java.awt.SystemColor.text;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.image.BufferedImage;
import java.util.ArrayList;


/**
 *
 * @author Zemlaynin
 */
public class MainWindow extends javax.swing.JFrame implements Runnable
{
 long counter = 0;
 BufferedImage buff = new BufferedImage(800, 800, BufferedImage.TYPE_4BYTE_ABGR);
 boolean isRunning = true;
 boolean isGameStarted = false;
 boolean isGameEnded = false;
 int speed=3;
 int lvl = 1;
 long time = 0;
 long timeEnd = 0;
 

 
 UserWarrior userWarrior;
 
 ArrayList<Enemy> enemy = new ArrayList<Enemy>();
 /**
  * Creates new form MainWindow
  */
 public MainWindow()
 {
  initComponents();
  setTitle("Broken snake");
 }

 /**
  * This method is called from within the constructor to initialize the form.
  * WARNING: Do NOT modify this code. The content of this method is always
  * regenerated by the Form Editor.
  */
 @SuppressWarnings("unchecked")
 // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
 private void initComponents()
 {

  setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  setResizable(false);
  addKeyListener(new java.awt.event.KeyAdapter()
  {
   public void keyPressed(java.awt.event.KeyEvent evt)
   {
    formKeyPressed(evt);
   }
   public void keyTyped(java.awt.event.KeyEvent evt)
   {
    formKeyTyped(evt);
   }
  });

  javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  getContentPane().setLayout(layout);
  layout.setHorizontalGroup(
   layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
   .addGap(0, 400, Short.MAX_VALUE)
  );
  layout.setVerticalGroup(
   layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
   .addGap(0, 300, Short.MAX_VALUE)
  );

  pack();
 }// </editor-fold>//GEN-END:initComponents

 private void formKeyPressed(java.awt.event.KeyEvent evt)//GEN-FIRST:event_formKeyPressed
 {//GEN-HEADEREND:event_formKeyPressed
  isGameStarted = true;
  
  if(time== 0 ) time = System.currentTimeMillis();
  switch (evt.getKeyCode())
  {
   case KeyEvent.VK_ESCAPE:
    isRunning = false;
    System.exit(0);
    break;
   case KeyEvent.VK_UP:
    userWarrior.yShift = -speed;
    userWarrior.xShift = 0;
    break;
   case KeyEvent.VK_DOWN:
    userWarrior.yShift = speed;
    userWarrior.xShift = 0;
    break;
   case KeyEvent.VK_LEFT:
    userWarrior.yShift = 0;
    userWarrior.xShift = -speed;
    break;
   case KeyEvent.VK_RIGHT:
    userWarrior.yShift = 0;
    userWarrior.xShift = speed;
    break;

   case KeyEvent.VK_HOME:
    userWarrior.yShift = -speed;
    userWarrior.xShift = -speed;
   break;
   case KeyEvent.VK_PAGE_UP:
    userWarrior.yShift = -speed;
    userWarrior.xShift = speed;
   break;
   case KeyEvent.VK_PAGE_DOWN:
    userWarrior.yShift = speed;
    userWarrior.xShift = speed;
   break;
   case KeyEvent.VK_END:
    userWarrior.yShift = speed;
    userWarrior.xShift = -speed;
   break;
  
  }
  


  

  
 }//GEN-LAST:event_formKeyPressed

 private void formKeyTyped(java.awt.event.KeyEvent evt)//GEN-FIRST:event_formKeyTyped
 {//GEN-HEADEREND:event_formKeyTyped
  
 }//GEN-LAST:event_formKeyTyped

 @Override
 public void run()
 {
   Dimension sSize = Toolkit.getDefaultToolkit ().getScreenSize ();
   setPreferredSize(new Dimension(800, 800));
   setLocation((int)sSize.getWidth()/2 -400,(int)sSize.getHeight()/2 -400);
   userWarrior = new UserWarrior(new Point(400, 400));
   enemy.add(new Enemy(speed));
   
   
   initComponents();
   while (isRunning)
   {
    try
    {
     Thread.sleep(50);
    } catch (InterruptedException ex)
    {
   }
    
   if (isGameStarted) gameStep();    
    
   repaint();
   }
   
 
   

 }
 
 
 private void gameStep()
 {
  counter++;
  userWarrior.shift();
  try
  {
  
  
  for (int i = 0; i < enemy.size(); i++)
  {
   enemy.get(i).shift();
   if (enemy.get(i).lifeCycle >1000)enemy.remove(i);
   
   for (int j = 0; j < userWarrior.getRects().size(); j++)
   {
    if(userWarrior.getRects().get(j).intersects(enemy.get(i).getRect()))
    {
     switch (enemy.get(i).getType())
     {
      case 0:
       userWarrior.getRects().add(enemy.get(i).getRect());
       enemy.remove(i);
       break;
      case 1:
        userWarrior.getRects().remove(userWarrior.getRects().size()-1);
        break;
      case 2:
       userWarrior.getRects().add(enemy.get(i).getRect());
       enemy.remove(i);
       speed++;
       break;
      default:
       break;
     }
     
    }
   }
   
  }
  
  if(counter%50==1)
  {
   if(enemy.size()<30)enemy.add(new Enemy(lvl));
  }

  if(counter%1000==1)
  {
   lvl++;
   speed++;
  }  
  //setTitle("c = "+enemy.size());
  }
  catch(Exception e)
  {
  
  }
  
 }

 @Override
 public void paint(Graphics g)
 {
  
  Graphics2D g2 = (Graphics2D) buff.getGraphics();
  g2.setColor(new Color(200,200,200));
  g2.fillRect(0, 0, 800, 800);
  
  
 if(isGameStarted)
 {
  
  for (int i = 0; i < enemy.size(); i++)
  {
   
   if(enemy.get(i).getType() == Enemy.TYPE_GROW)g2.setColor(Color.GREEN);
   if(enemy.get(i).getType() == Enemy.TYPE_REDUCE)g2.setColor(Color.RED);
   if(enemy.get(i).getType() == Enemy.TYPE_SPEED)g2.setColor(Color.YELLOW);
   g2.fill(enemy.get(i).getRect());
   
  }
  
  
  g2.setColor(Color.BLUE);
  for (int i = 0; i < userWarrior.getRects().size(); i++)
  {
   g2.fill(userWarrior.getRects().get(i));
  }
  
  
  Font f = g2.getFont();
  f = new Font(f.getFontName(), Font.BOLD, 14);
  g2.setFont(f);
  g2.setColor(new Color(0,100,0));
  g2.drawString("Уровень: " + lvl, 20, 40);
  g2.drawString("Скорость: " + speed, 120, 40);
  g2.drawString("Вес: " + userWarrior.rects.size(), 220, 40);
  
  g2.drawString("Время (сек): " + (System.currentTimeMillis()-time)/1000 , 320, 40);
  
  if(userWarrior.getRects().isEmpty())
  {
   isGameEnded = true;
  // isRunning = false;
   isGameStarted = false;
   timeEnd = System.currentTimeMillis();
  }
 }
 else
 {
  if(isGameEnded)
  {
   g2.setColor(Color.BLACK);
   Font f = g2.getFont();
   f = new Font(f.getFontName(), Font.BOLD, 44);
   g2.setFont(f);
    g2.setColor(Color.RED);
   String s1 = "GAME OVER";
   TextLayout tl = new TextLayout(s1,f, new FontRenderContext(null, true, true));
   g2.drawString(s1, 400-(int)(tl.getBounds().getCenterX()), 300);
   s1 = "Ваше время: " + (timeEnd - time)/1000 + " сек";
    tl = new TextLayout(s1,f, new FontRenderContext(null, true, true));
   g2.drawString(s1, 400-(int)(tl.getBounds().getCenterX()), 350);
  
  }
  else
  {
  g2.setColor(Color.BLACK);
  Font f = g2.getFont();
  f = new Font(f.getFontName(), Font.BOLD, 12);
  g2.drawString("Ваша задача продержаться как можно дольше.", 20, 40);
  g2.drawString("- Синий квадрат это вы.", 20, 60);
  g2.drawString("- Зеленый квадрат - противник поедая которого вы растете.", 20, 80);
  g2.drawString("- Желтый квадрат - противник поедая которого вы растете и добавляете в скорости.", 20, 100);
  g2.drawString("- Красный квадрат - противник сталкиваясь с которым вы худеете.", 20, 120);
  
  g2.drawString("Управление стрелками на нумпаде, можно двигаться по диагонали!", 20, 160);
  
  g2.setColor(Color.red);
  g2.drawString("Вы погибаете исхудав!!!", 20, 140);
  
  
  
  f = new Font(f.getFontName(), Font.BOLD, 16);
  g2.setFont(f);
  g2.drawString("Для старта нажмите любую клавишу", 260, 700);
  g2.setColor(Color.BLUE);
  g2.fill(new Rectangle(5, 50, 10, 10));
  g2.setColor(Color.GREEN);
  g2.fill(new Rectangle(5, 70, 10, 10));
  g2.setColor(Color.YELLOW);
  g2.fill(new Rectangle(5, 90, 10, 10));
  g2.setColor(Color.RED);
  g2.fill(new Rectangle(5, 110, 10, 10));
  }
 }
 
 g.drawImage(buff, 0, 0, this);
 }

 
 

 // Variables declaration - do not modify//GEN-BEGIN:variables
 // End of variables declaration//GEN-END:variables




}
