+/EE306

intro to computing

git clone https://git.julia.blue/+/EE306

P1n3appl3Finish connect 430b1299

master
2.4 KiB108 linesraw
1#include <stdio.h>
2#include <stdlib.h>
3
4int turn = -1; /* -1 = player 1, 1 = player 2*/
5int board[6][6];
6
7void display(){
8    for (int i = 0; i < 6; i++) {
9        for (int j = 0; j < 6; j++) {
10            if (board[i][j] < 0) {
11                putc('O', stdout);
12            }else if (board[i][j] > 0) {
13                putc('X', stdout);
14            }else {
15                putc('-', stdout);
16            }
17            if (j < 5) {
18                putc(' ', stdout);
19            }
20        }
21        putc('\n', stdout);
22    }
23}
24
25int can_move(int col){
26    return board[0][col] == 0;
27}
28
29void execute_move(int col){
30    int n = 5;
31    while (n >= 0) {
32        if (board[n][col] == 0) {
33            board[n][col] = turn;
34            return;
35        }
36        n--;
37    }
38}
39
40int check_win(){
41    for (int i = 0; i < 3; i++) {
42        for (int j = 0; j < 3; j++) {
43            int diagup = 0;
44            int diagdown = 0;
45            for (int k = 0; k < 4; k++) {
46                diagup += board[5 - i - k][j + k];
47                diagdown += board[i + k][j + k];
48            }
49            if (abs(diagup) == 4 || abs(diagdown) == 4) {
50                return 1;
51            }
52        }
53    }
54    for (int i = 0; i < 3; i++) {
55        for (int j = 0; j < 6; j++) {
56            int vert = 0;
57            int hor = 0;
58            for (int k = 0; k < 4; k++) {
59                vert += board[j][i + k];
60                hor += board[i + k][j];
61            }
62            if (abs(vert) == 4 || abs(hor) == 4) {
63                return 1;
64            }
65        }
66    }
67    return 0;
68}
69
70int check_full(){
71    for (int i = 0; i < 6; i++) {
72        if (can_move(i)) {
73            return 0;
74        }
75    }
76    return 1;
77}
78
79int main(){
80    char input;
81    while (1) {
82        display();
83        while (1) {
84            printf("Player %d, choose a column: ", (turn + 3) / 2);
85            input = getc(stdin);
86            getc(stdin);
87            if (input > 48 && input < 55) {
88                input -= 49;
89                if (can_move(input)) {
90                    execute_move(input);
91                    break;
92                }
93            }
94            printf("Invalid move. Try again.\n");
95        }
96        if (check_win()) {
97            display();
98            printf("Player %d Wins.\n", (turn + 3) / 2);
99            break;
100        }else if (check_full()) {
101            display();
102            printf("Tie Game\n");
103            break;
104        }
105        turn = -turn;
106    }
107    return 0;
108}