Professional Documents
Culture Documents
Canino BSCS – 3
#7 Minimax of Modified Tic Tac Toe
Code:
//Tic-tac-toe playing AI. Exhaustive tree-search. WTFPL
//Matthew Steel 2009, www.www.repsilat.com
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char gridChar(int i) {
switch(i) {
case -1:
return 'X';
case 0:
return ' ';
case 1:
return '0';
}
}
int * flipCoin()
{
int lower = 1, upper = 2, count = 9;
static int r[9];
srand((unsigned) time(NULL));
return r;
}
int main() {
int board[9] = {0,0,0,0,0,0,0,0,0};
int coin;
int player = 0;
unsigned turn;
int *p;
p = flipCoin();
if(coin != player) {
printf("Computer's turn:\n");
computerMove(board);
draw(board);
else {
printf("Your turn:\n");
draw(board);
playerMove(board);
}
}
switch(win(board)) {
case 0:
printf("A draw. How droll.\n");
break;
case 1:
printf("You lose.\n");
break;
case -1:
draw(board);
printf("You win. Inconceivable!\n");
break;
}
}
Explanation:
The modified tic-tac-toe I created is based on one of the Tic-tac-toe variants, which is the
Random turn tic-tac-toe.
In the C code I added a flipCoin() function that returns an int pointer. This function creates an
array (line 96) that can hold up to *9 values of random 1 or 2. The srand() function is used
together with the time() function (line 98) that uses the current time as a seed for random
generator. 1 represents heads and 2 represents tails that are generated in Line 101. It will
determine if it’s the computer or the player’s turn. Line 104 returns the address of the array in
the location in which the function is called.
Line 115 will ask the player if he will play Heads or Tails. Line 118 will call the flipCoin() function
(example if the coin is tossed in real life) and assign to the int pointer p to access the pre-
defined values in the array to determine the turn sequence. Line 123 will access the value
(either 1 or 2) present in the address pointed by the pointer. Based on the value, for example, if
the player chooses to play as head (1), if the result is 1 (Head), the player will first to play. If the
result is 2 (Tails), it’s the computer’s turn. The game will continue (the turns are now based on
the pre-define values in the array) until there’s a winner or draw.
Online Compiler: https://onlinegdb.com/gFAMa4uzj