shougi_main.c

an anonymous user · October 12, 2025
#include <pdcurses.h>
#include <locale.h>
#include <string.h>
#include <windows.h> // SetConsoleOutputCP
#include "shougi_data.h"

extern void set_board_from_dataretu();
extern void draw_board();
extern void csv_read();

void draw_board();

extern int cursor_x; // 初期カーソル位置(ファイル)
extern int cursor_y; // 初期カーソル位置(段)

const char *selected_piece = NULL; // 動かす対象の駒の種類

// 盤面を管理する2次元配列
// NULLなら空マス、文字列なら駒
const char *board[BOARD_SIZE][BOARD_SIZE];

int is_selected = 0;  // 駒を選択中かどうか
int from_x = -1;  // 選択した位置x
int from_y = -1;  // 選択した位置y

int main(void) {
    setlocale(LC_ALL, "");
    SetConsoleOutputCP(CP_UTF8);

    initscr();

    start_color();                           // 色機能を有効化
    init_pair(1, COLOR_WHITE, COLOR_BLACK);  // 通常
    init_pair(2, COLOR_BLACK, COLOR_YELLOW); // カーソル位置(背景を黄色に)
    init_pair(3, COLOR_WHITE, COLOR_BLUE);   // 選択中の駒(追従表示)
    init_pair(4, COLOR_BLACK, COLOR_GREEN);   // 移動可能範囲

    noecho();
    cbreak();
    keypad(stdscr, TRUE);
    curs_set(0);

    csv_read();

    // 盤面初期化
    memset(board, 0, sizeof(board));

    set_board_from_dataretu();

    while (1) {

        draw_board();

        int ch = getch();
        if (ch == 'q') break;

        switch (ch) {
            case KEY_UP:    if (cursor_y > 1) cursor_y--; break;
            case KEY_DOWN:  if (cursor_y < BOARD_SIZE) cursor_y++; break;
            case KEY_LEFT:  if (cursor_x > 1) cursor_x--; break;
            case KEY_RIGHT: if (cursor_x < BOARD_SIZE) cursor_x++; break;
            case '\n':   // UNIX系
            case '\r':   // Windows系
            case KEY_ENTER: // PDCurses用
            {
                if (!is_selected) {
                    // まだ選択していない -> カーソル位置の駒を選ぶ(あれば)
                    if (board[cursor_y - 1][cursor_x - 1] != NULL) {
                        is_selected = 1;
                        from_x = cursor_x;
                        from_y = cursor_y;
                        selected_piece = board[from_y - 1][from_x - 1]; // ポインタだけ保持
                        board[from_y - 1][from_x - 1] = NULL; // 見た目上は持ち上げる
                    }
                } else {
                    // 既に選択中 -> 現在カーソル位置に置く(同じマスならキャンセル扱い)
                    if (cursor_x == from_x && cursor_y == from_y) {
                        // 同じマスに戻す(キャンセル)
                        board[from_y - 1][from_x - 1] = selected_piece;
                    } else {
                        // 上書きして置く(取る処理はここで入れられます)
                        board[cursor_y - 1][cursor_x - 1] = selected_piece;
                    }
                    // リセット
                    selected_piece = NULL;
                    is_selected = 0;
                    from_x = from_y = -1;
                }
                break;
            }
        }
    }

    endwin();
    return 0;
}
Output

Comments

Please sign up or log in to contribute to the discussion.