/**
  gbcoundrel.c: a Game Boy port of the Scoundrel roguelike card game
  using the official ruleset only
  Created by Luxferre in 2026, released into public domain
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ezgb.h"

/* Sound section */

void beep_start() {
  play_jingle(220, 440, 440, 660, 660, 880);
}
void beep_interact() {
  play_jingle(440, 660, 220, 880, 440, 660);
}
void beep_enemy() {
  play_jingle(440, 220, 220, 110, 110, 110);
}
void beep_weapon() {
  play_jingle(660, 880, 440, 880, 660, 880);
}
void beep_potion() {
  play_jingle(440, 660, 660, 990, 660, 880);
}
void beep_run() {
  play_jingle(660, 880, 440, 660, 220, 440);
}
void beep_win() {
  play_jingle(55, 110, 110, 220, 220, 440);
  delay_cycles(6000);
  play_jingle(440, 660, 660, 880, 880, 1760);
  delay_cycles(6000);
  play_jingle(880, 660, 660, 880, 880, 1760);
}
void beep_lose() {
  play_jingle(110, 55, 220, 110, 110, 110);
  delay_cycles(6000);
  play_jingle(110, 110, 110, 110, 110, 110);
}
void beep_err() {
  play_jingle(330, 220, 330, 220, 330, 220);
}

/* print helper utils */

static char numbuf[6];
void printnum(s16 num) {
  memset(numbuf, 0, sizeof(numbuf));
  snprintf(numbuf, sizeof(numbuf), "%02d", num);
  convdigits(numbuf, sizeof(numbuf));
  cprintf("%s", numbuf);
}

/* Main game logic */

void game_startup() {
  u8 i, j, x = 0;
  termreset();
  DISPLAY_OFF;
  cputs( " " NL
"  \x0e\x0e\x0e\x1d  \x0e\x0e\x0e\x1d  \x0e\x0e\x0e" NL
" \x0f     \x0f     \x0f   \x0f" NL
"  \x0e+\x0e  \x0f +   \x0f + \x0f" NL
"     \x0f \x0f     \x0f   \x0f" NL
" \x1e\x0e\x0e\x0e   \x0e\x0e\x0e\x1f  \x0e\x0e\x0e " NL

" \x1d   \x1c \x1c   \x1c \x1c\x0e\x0e\x0e" NL
" \x0f   \x0f \x0f+  \x0f  \x0f  \x0f" NL
" \x0f + \x0f \x0f + \x0f  +  \x0f" NL
" \x0f   \x0f \x0f  +\x0f  \x0f  \x0f" NL
"  \x0e\x0e\x0e  \x1f   \x1f \x1e\x0e\x0e\x0e" NL

" \x1c\x0e\x0e\x0e  \x1c\x0e\x0e\x0e\x1d \x1c\x1d" NL
" \x0f   \x0f \x0f     \x0f\x1f" NL
" \x0f\x0e+\x0e  \x0f\x0e+\x0e  \x0f +" NL
" \x0f  +  \x0f     \x0f  \x1c\x1d" NL
" \x0f   + \x1e\x0e\x0e\x0e\x1f \x1e\x0e\x0e\x0e\x1f");
  cputsxy(1, SCREEN_HEIGHT - 1, "Luxferre");
  cputsxy(SCREEN_WIDTH-5, SCREEN_HEIGHT - 1, "2026");
  DISPLAY_ON;
  wait_vbl_done();
  wait_for_start_rand();
  beep_start();
  termreset();
}

/* Win screen display */
static char* ranks[] = {"Survivor", "Master", "Epic", "Legend", "God"};
void win_screen(s16 score) {
  u8 i, j, r;
  if(score > 29) r = 4;
  else if(score > 24) r = 3;
  else if(score > 19) r = 2;
  else if(score > 9) r = 1;
  else r = 0;
  termreset();
  cputs( \
" \x1d   \x1c  \x0e\x0e\x0e  \x1c   \x1c" NL
" \x0f   \x0f   \x0f   \x0f+  \x0f" NL
" \x0f + \x0f   +   \x0f + \x0f" NL
" \x0f+ +\x0f   \x0f   \x0f  +\x0f" NL
" \x1e\x1f \x1e\x1f  \x0e\x0e\x0e  \x1f   \x1f");
  cputsxy(2, 6,  "Congratulations!");
  cputsxy(0, 7,  " You made it across");
  cputsxy(0, 8, "   the dangerous");
  cputsxy(0, 9, "  dungeon  alive!");
  gotoxy(1, 11);
  cprintf("Score: %d", score);
  gotoxy(SCREEN_WIDTH-3-strlen(ranks[r]), 11);
  cprintf("|%s|", ranks[r]);
  chlinexy(0, 12, SCREEN_WIDTH);
  cputs(" By: Luxferre, 2026");
  cputs(NL NL "  Orig: Zach Gage," NL "  Kurt Bieg, 2011");
  wait_vbl_done();
  beep_win();
  wait_for_start();
}

/* UI choices */
#define CH1 0
#define CH2 1
#define CH3 2
#define CH4 3
#define CH_R 4
#define CH_Q 5
#define CH_INVAL 6

/**
Deck/room representation:
0 is empty (this value cannot be in the deck, only in the room),
1 to 13 is a monster,
14 to 22 is a weapon,
23 to 31 is a potion

Monster level: x + 1
Weapon level: x - 12
Potion level: x - 21
*/

/* Game stats */

/* main deck and room */
static s8 deck[44], room[] = {0, 0, 0, 0};

/* status message */
static char status_msg[(SCREEN_WIDTH)];
static char bufmsg[(SCREEN_WIDTH)];

/* tracking variables */
static s16 hp = 20;
static u8 deck_idx = 0, rooms_cleared = 0,
  weapon = 0, durability = 0, can_run = 1,
  engaged = 0, potion_drank = 0, last_potion_val = 0;

/* Input method */
/* up 1, left 2, right 3, down 4, a run, start quit */
u8 get_choice() {
  switch(joy_input_wait()) {
    case EZJOY_UP: return CH1;
    case EZJOY_LT: return CH2;
    case EZJOY_RT: return CH3;
    case EZJOY_DN: return CH4;
    case EZJOY_ST: return CH_Q;
    default: return CH_R;
  }
}

/* Draw a room character according to the index and value */
void render_room_item(u8 i, u8 v) {
  u8 topleft_x, topleft_y, cheight=4, cwidth=6;
  if(i == 0) {
    topleft_x = 7;
    topleft_y = 1;
  } else if(i == 1) {
    topleft_x = 0;
    topleft_y = 6;
  } else if(i == 2) {
    topleft_x = 14;
    topleft_y = 6;
  } else if(i == 3) {
    topleft_x = 7;
    topleft_y = 11;
  }
  if(v == 0) {} /* don't render anything */
  else {
    /* draw the rectangle */
    rect(topleft_x, topleft_y, cwidth, cheight);
    gotoxy(topleft_x + 1, topleft_y + 1);
    /* draw text */
    if(v < 14) cputs("ENMY");
    else if(v < 23) cputs("WEAP");
    else cputs("POTI");
    gotoxy(topleft_x + 2, topleft_y + 2);
    if(v < 14) printnum(v + 1);
    else if(v < 23) printnum(v - 12);
    else printnum(v - 21); 
  }
}

/* Render main game screen */
void render_main_scene() {
  u8 i, deck_count = 0;
  for(i=0;i<sizeof(deck);i++)
    if(deck[i]) deck_count++;
  termreset();
  /* render the room */
  for(i=0;i<4;i++) render_room_item(i, room[i]);
  /* render deck count */
  rect(7, 6, 6, 4);
  cputsxy(8, 7, "DECK");
  gotoxy(9, 8);
  printnum(deck_count);
  /* render stats */
  gotoxy(1, 2);
  cprintf("HP "); printnum(hp);
  gotoxy(1, 3);
  cprintf("RC "); printnum(rooms_cleared);
  gotoxy(14, 2);
  cprintf("WP "); printnum(weapon);
  gotoxy(14, 3);
  cprintf("DR "); printnum(durability);
  /* render controls */
  cputsxy(1, 12, "Item:");
  cputsxy(1, 13, "D-Pad");
  if(can_run) {
    cputsxy(14, 12, "Run:");
    cputsxy(14, 13, "A/B/SL");
  } else {
    cputsxy(14, 12, "Cannot");
    cputsxy(15, 13, "run!");
  }
  /* render status message */
  chlinexy(0,SCREEN_HEIGHT-2,SCREEN_WIDTH);
  gotoxy(0, SCREEN_HEIGHT-1);
  cprintf("%s", status_msg);
  wait_vbl_done();
}

/* Confirmation method */
u8 confirm(char *prompt) {
  u8 res = 2, statbase = SCREEN_WIDTH - 5;
  memset(status_msg, 0, sizeof(status_msg));
  snprintf(status_msg, sizeof(status_msg), "%s", prompt);
  render_main_scene();
  gotoxy(statbase, SCREEN_HEIGHT-3);
  cprintf("A=YES");
  gotoxy(statbase, SCREEN_HEIGHT-2);
  cprintf("B=NO");
  while(res > 1) {
    switch(joy_input_wait()) {
      case EZJOY_A: res = 1; break;
      case EZJOY_B: res = 0; break;
      default: res = 2;
    }
  }
  beep_interact();
  return res;
}

/* Output method */
void print_msg(char *s) {
  memset(status_msg, 0, sizeof(status_msg));
  strncpy(status_msg, s, sizeof(status_msg));
  render_main_scene();
}

/* Room item handling methods */

s16 handle_monster(s16 val) {
  s16 healthlost = val;
  char monster_msg[(SCREEN_WIDTH-1)];
  beep_enemy();
  if(weapon > 0 && val <= durability) {
    s16 weapondiff = val - weapon;
    if(weapondiff < 0) weapondiff = 0;
    snprintf(monster_msg, sizeof(status_msg), "(%d) Use weapon?", val);
    if(confirm(monster_msg)) {
      healthlost = weapondiff;
      durability = val - 1;
      if(durability < 2) {
        durability = weapon = 0;
      }
    }
  }
  hp -= healthlost;
  if(hp < 0) hp = 0;
  snprintf(status_msg, sizeof(status_msg), "Lost %d HP", healthlost);
  return val;
}

void handle_weapon(u8 val) {
  weapon = val;
  snprintf(status_msg, sizeof(status_msg), "Equipped %d-lvl wpn", weapon);
  durability = 14; /* reset durability to max limit */
  beep_weapon();
}

void handle_potion(u8 val) {
  if(potion_drank) {
    print_msg("Potion broken!");
    beep_err();
  } else {
    potion_drank = 1;
    hp += val;
    if(hp > 20) hp = 20;
    snprintf(status_msg, sizeof(status_msg), "Drank %d-lvl potion", val);
    if(deck_idx >= sizeof(deck) || deck[deck_idx] == 0)
      last_potion_val = val;
    beep_potion();
  }
}

/* Main gameplay */
s16 game() {
  u16 i;
  s16 score = -208; /* score storage */
  s16 item, room_sum; /* true item value */
  s16 last_room = 0, last_room_clr = 0; /* last room markers */
  u8 ch;
  deck_idx = 0; /* reset the deck index */
  /* Prefill the deck */
  for(i=0;i<13;i++) deck[i] = deck[i+13] = i+1;
  for(i=26;i<44;i++) deck[i] = i - 12;
  /* Shuffle the deck */
  shuffle(deck, sizeof(deck));
  /* prepare all other parameters */
  hp = 20;
  can_run = 1;
  weapon = durability = engaged = rooms_cleared = 0;
  potion_drank = last_potion_val = 0;
  for(i=0;i<sizeof(room);i++) room[i] = 0; /* reset the room */
  print_msg("Good luck!"); /* reset the status message */

  while(hp > 0 && !last_room_clr) {
    /* fill in the new room unless engaged */
    if(!engaged) {
      for(i=0;i<sizeof(room);i++) {
        /* fill only if empty */
        if(!room[i]) {
          /* Check if deck is empty or exhausted */
          if(deck_idx >= sizeof(deck) || deck[deck_idx] == 0) {
            last_room = 1;
            can_run = 0;
          } else {
            room[i] = deck[deck_idx];
            deck[deck_idx] = 0; /* remove from deck */
            deck_idx++;
            /* Check immediately if that was the last card */
            if(deck_idx >= sizeof(deck) || deck[deck_idx] == 0) {
               last_room = 1;
               can_run = 0;
            }
          }
        }
      }
    }

    /* display the stats and room */
    render_main_scene();
    ch = get_choice();

    /* Logic validation */
    if(ch == CH_R) {
        if(!can_run || engaged) ch = CH_INVAL; /* Cannot run if disabled or engaged */
    } else if(ch < CH_R && !room[(int)ch]) {
        ch = CH_INVAL; /* empty item */
    }

    if(ch == CH_Q) {
      if(confirm("End game?")) {
        hp = 0;
        break;
      } else print_msg("Go on!");
    } else if(ch == CH_INVAL) {
      print_msg("Invalid input!");
      beep_err();
      continue;
    } else if(ch == CH_R) { /* run mechanics */
      /* Compact and rearrange the deck */
      char temp_deck[sizeof(deck)];
      s16 t_idx = 0;

      /* 1. Collect all valid remaining cards from deck */
      for(i=0; i<sizeof(deck); i++) {
        if(deck[i] != 0) temp_deck[t_idx++] = deck[i];
      }

      /* 2. Shuffle room cards and append to the end */
      shuffle(room, sizeof(room));
      for(i=0; i<sizeof(room); i++) {
        if(room[i] != 0) {
          temp_deck[t_idx++] = room[i];
          room[i] = 0; /* Clear room */
        }
      }

      /* 3. Rebuild deck */
      memset(deck, 0, sizeof(deck));
      for(i=0; i<t_idx; i++) deck[i] = temp_deck[i];

      /* 4. Reset state */
      deck_idx = 0; /* Reset index to start of compacted deck */
      can_run = 0; /* can't run twice in a row */
      engaged = 0;
      last_room = 0; /* Since we added cards, it's not the last room anymore */
      print_msg("Ran from the room!");
      beep_run();
    } else { /* engagement mechanics */
      engaged++; /* increase the amount of engaged cards */
      can_run = 0; /* Cannot run once engaged */

      item = room[ch]; /* get the item from the room */
      room[ch] = 0; /* mark the room slot as empty */
      /* Note: We do NOT put the item back in deck. It is consumed. */

      if(item < 14) { /* monster */
        score += handle_monster(item + 1);
      } else if(item < 23) { /* weapon */
        handle_weapon(item - 12);
      } else { /* potion */
        handle_potion(item - 21);
      }

      /* condition to move to the next room */
      room_sum = 0;
      for(i=0;i<sizeof(room);i++) room_sum += room[i];

      if(hp > 0) {
        if(room_sum == 0) {
          if(last_room) last_room_clr = 1;
          else {
            engaged = 0;
            potion_drank = 0;
            can_run = 1;
            rooms_cleared++;
          }
        } else if(!last_room && engaged == 3) {
          engaged = 0;
          potion_drank = 0;
          can_run = 1;
          rooms_cleared++;
        }
      }
    }
  }
  /* Score the result */
  if(hp > 0) { /* win */
    score = hp;
    if(hp == 20) score += last_potion_val;
  }
  return score;
}

/* Entry point */
s16 main() {
  s16 score;
  init_sound();
  while(1) {
    termreset();
    game_startup();
    while(1) {
      score = game();
      if(score > 0) {
        win_screen(score);
        break;
      } else {
        beep_lose();
        snprintf(bufmsg, sizeof(bufmsg), "(%d) Restart?", score);
        if(!confirm(bufmsg)) break;
      }
    }
    wait_vbl_done();
  }
  return 0;
}
