Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h> // Tic-Tac-Toe (Random Moves)
- #include <stdlib.h> // Code by: The Elite Noob
- #include <time.h>
- int clean();
- void display(int* ar);
- void getinput(int(*validity)(int* ar, int l), int* ar); // (int l is location)
- int checkwin(int* ar);
- int validmove(int* ar, int place);
- void aimove(int(*validity)(int* ar, int l), int* ar);
- int main (int argc, char *argv[]){
- int board[] = {32, 32, 32, 32, 32, 32, 32, 32, 32}; // The board (ascii values), 32 is blank, 111 is o, and 120 is x(player);
- display(board);
- while(checkwin(board) == -1){
- getinput(validmove, board);
- display(board);
- if(checkwin(board) != -1)
- break;
- aimove(validmove, board);
- display(board);
- if(checkwin(board) != -1)
- break;
- }
- printf("%c wins!\n", checkwin(board));
- return 0;
- }
- void aimove(int(*validity)(int* ar, int l), int* ar){
- int r;
- srand(time(NULL));
- do{
- r = (rand() % 10) + 1; // Random num from 1 to 9
- }while((*validity)(ar, r) == -1); // Check if move is valid (Yay function pointers)
- ar[r-1] = 111; // AI move..
- }
- void getinput(int(*validity)(int* ar, int l), int* ar){ // Get and sanatize input
- char c; // First get the input, then make sure it's a valid move... c is used for garbage stuff
- int input;
- do{
- printf("\nEnter move: ");
- }while(!(((scanf("%d%c", &input, &c)!=2 || c!='\n') && clean()) ||input<1 || input>9) && ((*validity)(ar, input) == -1)); // Magic.
- ar[input-1] = 120; // Place/actually set the board piece
- }
- int validmove(int* ar, int place){ // If move is not valid, return -1
- if((ar[place-1] == 111)||(ar[place-1] == 120)){
- printf("\nInvalid move.");
- return -1;
- }
- return 1;
- }
- void display(int* ar){ // Display the board
- int i; // Iterator
- printf("\n");
- for (i = 0; i < 7; i+=3){
- printf("%c | %c | %c\n", ar[i], ar[i+1], ar[i+2]);
- if(i < 4)
- printf("----------\n");
- }
- }
- int checkwin(int* ar){ // Check if we have any winner yet..
- int i; // Iterator
- for(i = 0; i < 7; i+=3) // Check rows
- if((ar[i] == ar[i+1]) && (ar[i] == ar[i+2]) && (ar[i] != 32))
- return ar[i];
- for(i = 0; i < 3; i++) // Check cols
- if((ar[i] == ar[i+3]) && (ar[i] == ar[i+6]) && (ar[i] != 32))
- return ar[i];
- if((ar[0] == ar[4]) && (ar[0] == ar[8]) && (ar[0] != 32)) // Check diags
- return ar[0];
- if((ar[2] == ar[4]) && (ar[2] == ar[6]) && (ar[2] != 32)) // Check diags
- return ar[2];
- return -1; // No winner yet.
- }
- int clean(){ // Flushes input
- while (getchar()!='\n');
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement