piskvorky.c 1.66 KB
Newer Older
Gabriela Tričáková's avatar
Gabriela Tričáková committed
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
#include <stdio.h>
#include <stdlib.h>

int main() {
    printf("Enter the size of field: ");
    int size;
    scanf("%d", &size);

    char field[size];
    for (int i = 0; i < size; i++) {
        field[i] = ' ';
    }
    draw(field, size);

    char player = 'B';
    while (!isSolved(field, size)) {
        player = (player == 'A') ? 'B' : 'A';
        printf("Player %c: ", player);

        int position;
        scanf("%d", &position);

        int cross = addCross(field, size, position);

        if ( cross == -1 ) {
            printf("Wrong position!\n");
            continue;
        } else if ( cross == 0 ) {
            printf("X is already there!\n");
            continue;
        }

        draw(field, size);
    }

    printf("Player %c wins!\n", player);

    return EXIT_SUCCESS;
}

void draw(char field[], int size) {
    printf("\n");
    for (int i = 0; i < size; i++) {
        printf(" %d", i+1);
    }
    printf("\n");

    printf("+");
    for (int i = 0; i <size; i++) {
        printf("-+");
    }
    printf("\n");

    printf("|");
    for (int i = 0; i < size; i++) {
        printf("%c|", field[i]);
    }
    printf("\n");

    printf("+");
    for (int i = 0; i < size; i++) {
        printf("-+");
    }
    printf("\n");
}

int addCross(char field[], int size, int position) {
    if(position < 0 || position > size){
        return -1;
    }

    if(field[position-1] == 'X'){
        return 0;
    }

    field[position-1] = 'X';
    return 1;
}

int isSolved(char field[], int size) {
    for(int i = 0; i < size-2; i++){
        if(field[i] == 'X' && field[i+1] == 'X' && field[i+2] == 'X'){
            return 1;
        }
    }

    return 0;
}