summaryrefslogtreecommitdiff
path: root/lib/print.c
blob: d584fcc7de03b878ae70079b9c4cb667c0deff40 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <stdio.h>
#include <stdlib.h>

#include "print.h"
#include "board.h"
#include "coordinate.h"
#include "piece.h"

static void _print_row_separator() {
    int j;

    printf("  ");
    for (j = 0; j < SIZE; j++)
        printf("+---");

    printf("+\n");
}

static Coord _next_coord(Coord c, Color side)  {
        if (side == WHITE)
            return coord_next(c);
        else
            return coord_prev(c);
}

static int _first_column(char col, Color side) {
    if (side == WHITE && col == 'a')
        return 1;

    if (side == BLACK && col == 'h')
        return 1;

    return 0;
}

static void _print_columns(Color side) {
    char c;

    putchar(' ');
    if (side == WHITE)
        for (c = 'a'; c <= 'h'; c++)
            printf("   %c", c);
    else
        for (c = 'h'; c >= 'a'; c--)
            printf("   %c", c);

    putchar('\n');
}

/* Printing related functions */
void print_piece(Piece p) {
    putchar(piece_character(p));
}

void print_square(Square s) {
    printf("| ");
    if (s.piece == NULL)
        if (s.color == WHITE)
            putchar(' ');
        else
            putchar('/');
    else
        print_piece(*s.piece);

    putchar(' ');
}

/*
 * Pretty print the board. The "side" parameter lets you choose the
 * orientation. Use WHITE for a white player perspective, BLACK otherwise.
 */
void print_board(Board b, Color side) {
    Coord c = _next_coord(coord_null(), side);
    char current_row = coord_get_row(c);

    _print_row_separator();
    while (!coord_is_null(c)) {
        // Print row if it's the first column
        if (_first_column(coord_get_col(c), side))
            printf("%c ", current_row);

        // Print the square
        print_square(board_get_square(b, c));

        // Shall we move forward or backwards?
        c = _next_coord(c, side);

        // If the row changed then we must start a new line
        if (coord_get_row(c) != current_row) {
            printf("|\n");
            _print_row_separator();

            current_row = coord_get_row(c);
        }
    }

    _print_columns(side);
}
nihil fit ex nihilo