#include <genesis.h>

// 迷路のサイズ
#define MAZE_W 10
#define MAZE_H 8

// プレイヤー位置
int playerX = 1;
int playerY = 1;

// 迷路マップ（0=通路, 1=壁, 2=ゴール）
u8 maze[MAZE_H][MAZE_W] = {
  {1,1,1,1,1,1,1,1,1,1},
  {1,0,0,0,0,0,1,0,2,1},
  {1,0,1,1,1,0,1,0,1,1},
  {1,0,0,0,1,0,0,0,0,1},
  {1,1,1,0,1,1,1,1,0,1},
  {1,0,0,0,0,0,0,1,0,1},
  {1,0,1,1,1,1,0,1,0,1},
  {1,1,1,1,1,1,1,1,1,1},
};

// マップを表示
void drawMaze()
{
  for (int y=0; y<MAZE_H; y++)
  {
    for (int x=0; x<MAZE_W; x++)
    {
      if (maze[y][x] == 1)
        VDP_drawText("#", x, y);   // 壁
      else if (maze[y][x] == 2)
        VDP_drawText("G", x, y);   // ゴール
      else
        VDP_drawText(".", x, y);   // 通路
    }
  }
}

// プレイヤーを描画
void drawPlayer()
{
  VDP_drawText("@", playerX, playerY);
}

// プレイヤーを移動
void movePlayer(int dx, int dy)
{
  int newX = playerX + dx;
  int newY = playerY + dy;

  if (maze[newY][newX] != 1) // 壁でなければ移動
  {
    // 古い位置を再描画（通路に戻す）
    if (maze[playerY][playerX] == 0)
      VDP_drawText(".", playerX, playerY);
    else if (maze[playerY][playerX] == 2)
      VDP_drawText("G", playerX, playerY);

    // 新しい位置へ
    playerX = newX;
    playerY = newY;

    drawPlayer();

    // ゴール判定
    if (maze[playerY][playerX] == 2)
    {
      VDP_drawText("YOU WIN!", 2, MAZE_H + 1);
    }
  }
}

// コントローラー入力
void handleInput(u16 joy, u16 changed, u16 state)
{
  if (joy == JOY_1)
  {
    if (state & BUTTON_UP)  movePlayer(0, -1);
    if (state & BUTTON_DOWN)  movePlayer(0, 1);
    if (state & BUTTON_LEFT)  movePlayer(-1, 0);
    if (state & BUTTON_RIGHT) movePlayer(1, 0);
  }
}

// メイン関数
int main()
{
  VDP_setScreenWidth320();
  VDP_setScreenHeight224();
  VDP_clearTextArea(0, 0, 40, 28);

  VDP_drawText("Maze Game (SGDK)", 2, 0);

  drawMaze();
  drawPlayer();

  JOY_init();
  JOY_setEventHandler(handleInput);

  while(1)
  {
    SYS_doVBlankProcess();
  }

  return 0;
}
