Dabeen Park/C /Fourconnectgame
#include <iostream>
- include <cmath>
- include <iomanip>
using namespace std;
- define ROW_NUM 6
- define COL_NUM 7
int q, w, e, r;
char row_name, who_turn;
string board[ROW_NUM][COL_NUM];
void four_contect_board(int e)
{
for(int q = 0; q < ROW_NUM; q++)
{
for(int w = 0; w < COL_NUM; w++)
{
board[q][w] = " ";
}
}
}
void four_contect(int e)
{
for(int q = 0; q < ROW_NUM; q++)
{
for(int w = 0; w < COL_NUM; w++)
{
cout << " | " << board[q][w];
if(w == COL_NUM - 1)
{
cout << " | " << endl;
}
}
}
cout << " ";
for(int w = 0; w < COL_NUM; w++)
{
cout << " ___ ";
}
cout << endl << " ";
for(int w = 0; w < COL_NUM; w++)
{
row_name = 65 + w;
cout << " " << row_name << " ";
}
if(w == COL_NUM - 1)
{
cout << endl;
}
}
void turn(int e)
{
if(e % 2 == 1)
{
who_turn = '0';
}
else if(e % 2 == 0)
{
who_turn = 'X';
}
while(e>0)
{
cout << "Please choose a column for the player " << who_turn << ":";
cin >> row_name;
w = row_name - 65;
while(w >= COL_NUM)
{
cout << "Invalid column." << endl << "Please choose a column for the player " << who_turn << " again:";
cin >> row_name;
w = row_name - 65;
}
if(board[0][w]!=" ")
{
cout << "The column is full." << endl;
}
else
{
for(int q = ROW_NUM - 1; q >= 0; q--)
{
if(board[q][w]==" ")
{
board[q][w] = who_turn;
e = 0;
break;
}
}
}
}
}
int If_the_board_full(int e)
{
e = 0;
for(int q = 0; q < ROW_NUM; q++)
{
for(int w = 0; w < COL_NUM; w++)
{
if(board[q][w]!=" ")
{
e++;
}
}
}
return e;
}
int Who_is_winner(int e)
{
for(int q = 0; q < ROW_NUM; q++)
{
for(int w = 0; w < COL_NUM; w++)
{
if(board[q][w]==board[q+1][w] & board[q][w]==board[q+2][w] & board[q][w]==board[q+3][w] & board[q][w]!=" ")
{
four_contect(e);
cout << endl << "Player " << board[q][w] << " has won." << endl;
return 1;
}
else if(board[q][w]==board[q][w+1] & board[q][w]==board[q][w+2] & board[q][w]==board[q][w+3] & board[q][w]!=" ")
{
four_contect(e);
cout << endl << "Player " << board[q][w] << " has won." << endl;
return 1;
}
else if(board[q][w]==board[q+1][w+1] & board[q][w]==board[q+2][w+2] & board[q][w]==board[q+3][w+3] & board[q][w]!=" ")
{
four_contect(e);
cout << endl << "Player " << board[q][w] << " has won." << endl;
return 1;
}
else if(board[q][w]==board[q+1][w-1] & board[q][w]==board[q+2][w-2] & board[q][w]==board[q+3][w-3] & board[q][w]!=" ")
{
four_contect(e);
cout << endl << "Player " << board[q][w] << " has won." << endl;
return 1;
}
else if(If_the_board_full(e)==COL_NUM * ROW_NUM)
{
four_contect(e);
cout << "The game ended in a draw.";
return 1;
}
}
}
return 0;
}
int main()
{
four_contect_board(e);
cout << "Let's play Connect-4!" << endl << endl;
for(int r = 1; r < ROW_NUM * COL_NUM + 1; r++)
{
four_contect(e);
cout << endl;
turn(r);
if(Who_is_winner(e))
{
r = ROW_NUM * COL_NUM + 1;
}
}
return 0;
}