/********************************
  netpuyo(client)
  screen.c --- screen operation
  (C) Sep 17, 1997 ROYALPANDA
*******************************/

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


/* 向きに対応する相対座標 */

static int Dir_x[4] = { 0,1,0,-1 };
static int Dir_y[4] = { -1,0,1,0 };


/* 画面全体の更新 */

void flush_scr( int p )
{
  int x,y,style,dir,b;

  for( y = 1 ; y < 13 ; y++ )
    for( x = 1 ; x < 7 ; x++ ){
      style = 0;
      if( P[p].map_c[x][y] != NOTHING )
	for( b=1, dir = 0 ; dir < 4 ; b <<= 1, dir++ )
	  if( P[p].map_c[x][y] == P[p].map_c[x+Dir_x[dir]][y+Dir_y[dir]] )
	    style |= b;
      P[p].map_s[x][y] = style;
      draw_pic( p,x,y,P[p].map_c[x][y],P[p].map_s[x][y] );
    }
}


/* 組ぷよ消去 */

void del_puyo( int p )
{
  int i;

  for( i = 0 ; i < 2 ; i++ )
    draw_pic( p,P[p].x[i],P[p].y[i],NOTHING,0 );
}


/* 組ぷよ描画 */

void move_puyo( int p )
{
  int i;

  for( i = 0 ; i < 2 ; i++ )
    draw_pic( p,P[p].x[i],P[p].y[i],P[p].puyo[i],i*16 );
}


/* ぷよ落下( 1つでも落ちたら 1 を返す ) */

int fall_puyo( int p )
{
  int x,y,flag;

  flag = 0;

  for( y = 12 ; y > 0 ; y-- )
    for( x = 1 ; x < 7 ; x++ )
      if( P[p].map_c[x][y] == NOTHING && P[p].map_c[x][y-1] != NOTHING ){
	P[p].map_c[x][y] = P[p].map_c[x][y-1];
	P[p].map_c[x][y-1] = NOTHING;
	flag = 1;
      }

  flush_scr( p );

  return flag;
}


/* 消えるぷよの点滅( おわったら、実際に消して0を返す) */
int blink_puyo( int p )
{
  int x,y,b;

  P[p].blink--;

  if( P[p].blink == 0 ){
    for( y = 1 ; y < 13 ; y++ )
      for( x = 1, b = 1 ; x < 7 ; x++, b <<= 1 )
	if( P[p].kill[y] & b )
	  P[p].map_c[x][y] = NOTHING;
    flush_scr( p );

    return 0;
  }

  if( P[p].blink & 2 ){
    for( y = 1 ; y < 13 ; y++ )
      for( x = 1, b = 1 ; x < 7 ; x++, b <<= 1 )
	if( P[p].kill[y] & b )
	  draw_pic( p,x,y,NOTHING,0 );
  }else{
    for( y = 1 ; y < 13 ; y++ )
      for( x = 1, b = 1 ; x < 7 ; x++, b <<= 1 )
	if( P[p].kill[y] & b )
	  draw_pic( p,x,y,P[p].map_c[x][y],P[p].map_s[x][y] );
  }
  return 1;

}

/* おじゃまぷよを降らせる (残っていれば1を返す) */
int jama_puyo( int p )
{
  int x,b;

  if( P[p].jama_line ){
    for( x = 1 ; x < 7 ; x++ )
      if( P[p].map_c[x][0] == NOTHING )
	P[p].map_c[x][0] = JAMA;
  }else{
    for( x = 1,b = 1 ; x < 7 ; x++, b <<= 1 )
      if( (P[p].jama_top & b) && P[p].map_c[x][0] == NOTHING )
	P[p].map_c[x][0] = JAMA;
  }
  fall_puyo( p );

  if( P[p].jama_line == 0 )
    return 0;

  P[p].jama_line--;
  return 1;
}

