/*****************************************
  xjump version 3

  hero.c

*****************************************/

#include<stdio.h>
#include<X11/Xlib.h>

#include"xjump.h"


void HERO_delete( hero_t *hp )
{
  XClearArea(Disp,Scr_d,hp->erase_x,hp->erase_y,32,64,False);
}

/* 主人公を表示 */

void HERO_draw( hero_t *hp )
{
  int pic;
  int sx,sy;

  pic = hp->pic * 2 + hp->dir;
  sx = ( pic & 3 ) * 32;
  sy = ( pic >> 2 ) * 64;

  XSetClipOrigin(Disp,Gc_mask,hp->x-sx,hp->y-sy);
  XCopyArea(Disp,Char_p,Scr_d,Gc_mask,sx,sy,32,64,hp->x,hp->y);
}


/* 主人公の移動 */

int HERO_move( hero_t *hp, int scroll )
{
  int acc,st,floor;
  int fv,mu,rv;
  floor_t *fp;

  hp->erase_x = hp->x;
  hp->erase_y = hp->y;

  hp->x += hp->vx/2;
  hp->y += hp->vy;

  if( scroll )
    hp->y += 16;

  if( hp->x < 16 ){
    hp->x = 16;
    hp->vx = -hp->vx/2;
  }else if( hp->x > WIDTH*16-48 ){
    hp->x = WIDTH*16-48;
    hp->vx = -hp->vx/2;
  }

  if( hp->vy >= 0 && (fp = FLOOR_check(hp->x,hp->y)) ){
    floor = fp->floor;
    st = 1;
    hp->pic &= 1;
    if( ++hp->g_count == 10 ){
      hp->g_count = 0;
      hp->pic ^= 1;
    }
    hp->y = ((hp->y + 64 ) & ~15) - 64;
    hp->vy = 0;

    fv = (fp->move_vector + fp->force_vector)*2;
    mu = fp->mu;


  }else{
    floor = 0;
    st = 0;
    fv = 0;
    mu = 0;
  }

  rv = hp->vx - fv;

#if 0
  if( mu ){
    if( hp->key[KEY_LEFT] ){
      rv -= (19 + rv) / 4;
      hp->dir = 0;
    }else if( hp->key[KEY_RIGHT] ){
      rv += (19 - rv) / 4;
      hp->dir = 1;
    }else{
      if( abs(rv) < 4 )
        rv = 0;
      else
        rv += (rv > 0) ? -4 : 4;
    }
  }else{
    if( hp->key[KEY_LEFT] && rv > -16 ){
      rv--;
      hp->dir = 0;
    }else if( hp->key[KEY_RIGHT] && rv < 16 ){
      rv++;
      hp->dir = 1;
    }
  }
#else
  if( mu ){
    if( hp->key[KEY_LEFT] ){
      rv -= (32+7 + rv) / 8;
      hp->dir = 0;
    }else if( hp->key[KEY_RIGHT] ){
      rv += (32+7 - rv) / 8;
      hp->dir = 1;
    }else{
      if( abs(rv) < 4 )
        rv = 0;
      else
        rv += (rv > 0) ? -4 : 4;
    }
  }else{
    if( hp->key[KEY_LEFT] && rv > -32 ){
      rv -= rv < 0 ? (32+15 + rv) / 16 : 2;
      hp->dir = 0;
    }else if( hp->key[KEY_RIGHT] && rv < 32 ){
      rv += rv > 0 ? (32+15 - rv) / 16 : 2;
      hp->dir = 1;
    }
  }
#endif
  hp->vx = rv + fv;

  if( !st ){
    if( hp->jump ){
      hp->vy = -hp->jump/2-12;
      if( hp->key[ KEY_UP ] )
	hp->jump--;
      else
	hp->jump = 0;
    }else{
      hp->vy+=2;
      if( hp->vy > 0 )
	hp->pic = 3;

      if( hp->vy > 16 )
	hp->vy = 16;
    }
  }else if( hp->key[KEY_UP] ){
    hp->jump = abs(rv)/4+7;
    hp->vy = -hp->jump/2-12;
    hp->pic = 2;
  }

  return floor;
}


/* 初期化 */

void HERO_init( hero_t *hp )
{
  hp->x = WIDTH * 8 - 16;
#if 1
  hp->y = (HEIGHT - 4)*16-64;
#else
  hp->y = 0;
#endif
  hp->vx = hp->vy = 0;
  hp->pic = 0;
  hp->dir = 0;
  hp->g_count = 0;

  HERO_draw(hp);
}

