Select Git revision
connect4.cpp
connect4.cpp 2.77 KiB
#include "connect4.hpp"
void initBoard(int board[][HEIGHT])
{
for (int i = 0; i < HEIGHT; i++)
{
for (int j = 0; j < WIDTH; j++)
{
board[i][j] = EMPTY;
}
}
}
int placePiece(int board[][HEIGHT], int col, Tile player)
{
if (col < 0 || col >= WIDTH)
{
return -1;
}
// Check if the column is full
if (board[0][col] != EMPTY)
{
return -1;
}
// Find the first empty spot in the specified column and place the player's piece there
for (int i = HEIGHT - 1; i >= 0 ; i--)
{
if (board[i][col] == EMPTY)
{
board[i][col] = player;
break;
}
}
return 0;
}
Tile checkWin(int board[][HEIGHT])
{
// Check if the player has won by checking for a horizontal, vertical, or diagonal line of their pieces
for (int i = 0; i < HEIGHT; i++)
{
for (int k = 0; k < WIDTH; k++)
{
Tile currentPlayer = (Tile)board[i][k];
if (currentPlayer != EMPTY)
{
if (checkNumberOfNearbyToken(board, i, k, currentPlayer) >= 4)
{
return currentPlayer;
}
}
}
}
return EMPTY;
}
int checkNumberOfNearbyToken(int board[][HEIGHT], int row, int col, Tile player)
{
// Check the number of pieces of the specified player in all directions around the specified row and column
// Return the number of pieces found
// Check nearby flags
int nearbyOwnToken = 0;
// Check horizontal
for (int i = 0; i < WIDTH; i++)
{
if (board[row][i] == player)
{
nearbyOwnToken++;
}
else
break;
}
if (nearbyOwnToken >= 4)
{
return nearbyOwnToken;
}
else
{
nearbyOwnToken = 0;
}
// Check vertical
for (int i = 0; i < HEIGHT; i++)
{
if (board[i][col] == player)
{
nearbyOwnToken++;
}
else
break;
}
if (nearbyOwnToken >= 4)
{
return nearbyOwnToken;
}
else
{
nearbyOwnToken = 0;
}
// Check diagonal top-left to bottom-right
for (int i = row, j = col; i >= 0 && i < HEIGHT && j >= 0 && j < WIDTH; i++, j++)
{
if (board[i][j] == player)
{
nearbyOwnToken++;
}
else
break;
}
if (nearbyOwnToken >= 4)
{
return nearbyOwnToken;
}
else
{
nearbyOwnToken = 0;
}
// Check diagonal top-right to bottom-left
for (int i = row, j = col; i >= 0 && i < HEIGHT && j >= 0 && j < WIDTH; i++, j--)
{
if (board[i][j] == player)
{
nearbyOwnToken++;
}
else
break;
}
return nearbyOwnToken;
}