Skip to content

Instantly share code, notes, and snippets.

@nbervar21
Last active November 10, 2020 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nbervar21/f377806d642f43c7137669aaed3cc78d to your computer and use it in GitHub Desktop.
Save nbervar21/f377806d642f43c7137669aaed3cc78d to your computer and use it in GitHub Desktop.
Compact tic tac toe (C)
#include <stdio.h>
#define EMPTY -1
// translate human-readable coordinates to char indexes on board
int translateRow[4] = {EMPTY, 22, 42, 62};
int translateCol[4] = {EMPTY, 0, 2, 4};
char currentPiece[2] = "OX";
// ---- translateWinConditions explanation ----
// 9 is for the squares on the board, as follows
// 0 1 2
// 3 4 5
// 6 7 8
// 4 is for the total amount of win conditions that
// could possibly be modified by a tile's status
// there are 8 win conditions:
// 0, 1, 2 - top, middle, bottom - completed row
// 3, 4, 5 - left, middle, right - completed column
// 6, 7 - down, up (towards right) - completed diagonal
// EMPTY slots aren't used (see lines 52-55)
int translateWinConditions[9][4] = {{0, 3, 6, EMPTY}, {0, 4, EMPTY, EMPTY}, {0, 5, 7, EMPTY}, {1, 3, EMPTY, EMPTY}, {1, 4, 6, 7}, {1, 5, EMPTY, EMPTY}, {2, 3, 7, EMPTY}, {2, 4, EMPTY, EMPTY}, {2, 5, 6, EMPTY}};
int main()
{
char board[79] = " 1 2 3\n +-+-+-+\n1 | | | |\n +-+-+-+\n2 | | | |\n +-+-+-+\n3 | | | |\n +-+-+-+";
int moves = 0, inputRow, inputCol;
for (;;)
{
inputRow = 0, inputCol = 0;
do
{
printf("Enter input (row, col): ");
scanf("%i, %i", &inputRow, &inputCol);
}
while ((inputRow < 1 || inputRow > 3) || (inputCol < 1 || inputCol > 3));
int boardIndex = translateRow[inputRow] + translateCol[inputCol];
if (board[boardIndex] == ' ')
{
board[boardIndex] = currentPiece[moves % 2];
moves++;
puts(board);
if (moves > 4)
{
for (int knotOrCross = 0; knotOrCross < 2; knotOrCross++)
{
int winConditions[8] = {0, 0, 0, 0, 0, 0, 0, 0};
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 4; j++)
{
if (translateWinConditions[i][j] == EMPTY)
{
continue;
}
short piecesInLine = winConditions[translateWinConditions[i][j]] += (board[translateRow[(i / 3) + 1] + translateCol[(i % 3) + 1]] == currentPiece[knotOrCross]);
if (piecesInLine > 2)
{
printf("%c Wins!!!\n", currentPiece[knotOrCross]);
return 0;
}
}
}
}
}
}
else
{
printf("That space is occupied.\n");
}
}
}
@dkiang
Copy link

dkiang commented Nov 10, 2020

This is very impressive and plays well in a Terminal window. Amazing that it is so compact!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment