/********************************
  netpuyo(server)
  kill.c --- delete & score
  (C) Sep 24, 1997 ROYALPANDA
*******************************/

#include<stdio.h>
#include"server.h"

static int Color_target;    /* 消去判定用 */
static int Killed_x[3];
static int Killed_y[3];
static int Killed;


player_t *Tp;  /* 現在注目しているプレイヤーへのポインタ */

/* 計算開始 (各連鎖ごとに呼ぶ) */

static void start_calc( void )
{
  int i;

  Tp->kill = 0;
  Tp->kill_max = 0;
  Tp->kill_colors = 0;
  for( i = 1 ; i < 6 ; i++ )
    Tp->color[i] = 0;
}


/* 消したぷよの加算 (消した塊ごとに呼ぶ) */

static void add_score( int puyo )
{
  Tp->kill += puyo;
  if( puyo > 10 )
    Tp->kill_max += 10;
  else if( puyo > 4 )
    Tp->kill_max += puyo - 3;

  if( !Tp->color[ Color_target] ){
    Tp->kill_colors++;
    Tp->color[Color_target] = 1;
  }
}


/* 計算 (連鎖ごとに呼ぶ) */

static int calc_score( void )
{
  int mul;

  Tp->sc_multi++;

  mul = 0;

  if( Tp->sc_multi < 4 )
    mul = (Tp->sc_multi-1)*8;
  else
    mul = (Tp->sc_multi-3)*32;

  if( Tp->kill_colors > 1 )
    mul += 3 << (Tp->kill_colors-2);

  mul += Tp->kill_max;

  if( mul == 0 )
    mul = 1;
  else if( mul > 999 )
    mul = 999;

  return Tp->kill * mul * 10;
}


/* ぷよ消去用サブルーチン */

static void chain_puyo( int x, int y )
{
  if( y < 1 )
    return;

  if( Tp->map[x][y] != Color_target )
    return;

  Tp->map[x][y] = PY_KILLED;

  if( Killed < 3 ){
    Killed_x[Killed] = x;
    Killed_y[Killed] = y;
  }
  Killed++;

  chain_puyo( x+Dir_x[0],y+Dir_y[0] );
  chain_puyo( x+Dir_x[1],y+Dir_y[1] );
  chain_puyo( x+Dir_x[2],y+Dir_y[2] );
  chain_puyo( x+Dir_x[3],y+Dir_y[3] );
}



/* つながったぷよの消去および得点処理。得点 を返す。消えなかったら 0*/

int kill_puyo( int p )
{
  int x,y,x2,y2,dir;

  Tp = P+p;

  start_calc();

  for( y = 1 ; y < 13 ; y++ )
    for( x = 1 ; x < 7 ; x++ ){
      Color_target = Tp->map[x][y];
      if( Color_target > 0 && Color_target < 6 ){
	Killed = 0;
	chain_puyo(x,y);
	if( Killed > 3 )
	  add_score( Killed );
	else
	  while( --Killed >= 0 )
	    Tp->map[Killed_x[Killed]][Killed_y[Killed]] = Color_target;
      }
    }
   
  return calc_score();
}
