diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8510665 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +four diff --git a/README.md b/README.md index e69de29..4eabb4e 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,10 @@ +# Connect Four in C + +## Usage +```bash +./build +``` +and then: +```bash +./four +``` diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..64e8a9e --- /dev/null +++ b/build.sh @@ -0,0 +1,6 @@ + #!/bin/bash + +set -xe +CFLAGS="-Wall -Werror -ggdb" + +gcc $CFLAGS -o four main.c diff --git a/main.c b/main.c new file mode 100644 index 0000000..fd027cb --- /dev/null +++ b/main.c @@ -0,0 +1,125 @@ +#include +#include +#include +#include +#include +// connect four + +#define ROWS 7 +#define COLUMNS 6 +#define TIME 0.6 + +#define BOLDYELLOW "\033[1m\033[33m" /* Bold Yellow */ +#define BOLDRED "\033[1m\033[31m" /* Bold Yellow */ +#define BOLDWHITE "\033[1m\033[37m" /* Bold White */ +#define RESET "\033[0m" + +char board[ROWS][COLUMNS]; + +void print_board(); +void clear_board(); +void player_choice(char player); +int check_free_space(); + +int main(int argc, char *argv[]){ + clear_board(); + + print_board(); + player_choice('0'); + print_board(); + player_choice('O'); + print_board(); + player_choice('0'); + print_board(); + player_choice('O'); + print_board(); + + return 0; +} + + +void print_board(){ + system("clear"); + printf("\nFree Spaces: %d\n", check_free_space()); + int r, c; + c = 0; + printf(BOLDWHITE " 1 2 3 4 5 6 \n" RESET); + for(r = 0; r < ROWS; ++r){ + //printf(BOLDWHITE "%d\t" RESET, r+1); + for(c = 0; c < COLUMNS; ++c){ + if(board[r][c] == 'O'){ + printf("[ "); + printf(BOLDRED "%c" RESET ,board[r][c]); + printf(" ]"); + } + else if(board[r][c] == '0'){ + printf("[ "); + printf(BOLDYELLOW "%c" RESET ,board[r][c]); + printf(" ]"); + } + else{ + printf("[ %c ]", board[r][c]); + } + } + printf("\n"); + } +} + + +void clear_board(){ + int r, c; + for(r = 0; r < ROWS; ++r){ + for(c = 0; c < COLUMNS; ++c){ + board[r][c] = ' '; + } + } +} + +void player_choice(char player){ + unsigned int time = 30000; + int pc; + + printf(BOLDWHITE "\n[%c]Enter column (1-6)\n> ", player); + scanf("%d", &pc); + pc--; //arrays start with 0 + + + //TODO: replace these + assert(pc < 6); + assert(pc < 6); + + + for(int r = 0; board[r][pc] == ' '; ++r){ + + // Check if the next tile is not empty (occupied) + if(board[r+1][pc] != ' '){ + board[r][pc] = player; + break; + } + //check if we've hit the last row + if(r >= COLUMNS){ + board[r][pc] = player; + break; + } + + // Animation + board[r][pc] = player; + print_board(); + usleep(time); + board[r][pc] = ' '; + print_board(); + usleep(time); + } +} + +int check_free_space(){ + int r, c; + int sp = 0; + for(r = 0; r < ROWS; ++r){ + for(c = 0; c < COLUMNS; ++c){ + if(board[r][c] == ' ') ++sp; + } + } + + return sp; +}