I create a “Connect 4” game in C and I wanna know if have something I could improve in my code. Check it out:
#include <stdio.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdbool.h>
#define COLUMNS 6
#define ROWS 7
int board[ROWS][COLUMNS];
void inicializeBoard();
int uptadeBoard(int, int);
void drawBoard();
bool checkWinner(int, int, int);
int main() {
int player = 1, moveColumn, moveRow;
inicializeBoard();
drawBoard();
while(1) {
printf("nPlayer %d, make your choice: ", player);
scanf("%d", &moveColumn);
system("clear");
if (moveColumn > 0 && moveColumn <= COLUMNS && board[0][moveColumn - 1] == 0) {
moveColumn--;
moveRow = uptadeBoard(player, moveColumn);
drawBoard();
if (checkWinner(player, moveRow, moveColumn)) {
printf("nPlayer %d wins!", player);
break;
}
player = (player == 1) ? 2 : 1;
} else {
drawBoard();
printf("nInvalid choice. Try again.");
}
}
return 0;
}
void inicializeBoard(){
for (int r = 0; r < ROWS; r++) {
for (int c = 0; c < COLUMNS; c++) {
board[r][c] = 0;
}
}
}
int uptadeBoard(int player, int moveColumn) {
int r;
for (r = 0; r < ROWS - 1; r++) {
if (board[r + 1][moveColumn] != 0){
break;
}
}
board[r][moveColumn] = player;
return r;
}
void drawBoard() {
for(int r = 0; r < ROWS; r++) {
printf("[ ");
for(int c = 0; c < COLUMNS; c++){
printf("%d. ", board[r][c]);
}
printf("]n");
}
}
bool checkWinner(int player, int moveRow, int moveColumn) {
int sequence = 0, c, r;
for (c = 0; c < COLUMNS; c++) { //Horizontally check
if (board[moveRow][c] == player) {
sequence++;
} else {
sequence = 0;
}
if (sequence == 4) {
return true;
}
}
sequence = 0;
for (r = 0; r < ROWS; r++) { //Vertically check
if (board[r][moveColumn] == player) {
sequence++;
} else {
sequence = 0;
}
if (sequence == 4) {
return true;
}
}
sequence = 0;
r = moveRow;
c = moveColumn;
while (r < ROWS || c > 0) {
r++;
c--;
}
while(c < COLUMNS || r > 0) {
if(board[r][c] == player) {
sequence++;
} else {
sequence = 0;
}
if(sequence == 4){
return true;
}
r--;
c++;
}
sequence = 0;
r = moveRow;
c = moveColumn;
while (r > 0 || c > 0) {
r--;
c--;
}
while(c < COLUMNS || r < ROWS) { //Diagonally check
if(board[r][c] == player) {
sequence++;
} else {
sequence = 0;
}
if(sequence == 4) {
return true;
}
r++;
c++;
}
return false;
}
One thing I don’t know if it’s ok is for me to create a global variable for the board, some people use parameters to not do this. I also create variables inside the loop, I would like to know if this is good or not. Last thing is that I didn’t program tie, so don’t worry about that. Thanks!
New contributor
Matheus Santos da Silva is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1