HTMLify

ttt.c
Views: 20 | Author: abh
#include "ttt.h"
#include <string.h>
#include <stdlib.h>
#include <time.h>


TTT *TTT_init(const char* player1, const char* player2, const char player1_symbol, const char player2_symbol, int turn) {
    static TTT game;
    strcpy(game.state, "         ");
    game.player1 = strdup(player1);
    game.player2 = strdup(player2);
    game.symbols[0] = player1_symbol;
    game.symbols[1] = player2_symbol;
    game.turn = turn;
    game.running = true;
    return &game;
}

bool TTT_mark(TTT *game, int pos) {
    if (!game->running)
        return false;

    if (pos < 1 || 9 < pos)
        return false;

    if (game->state[pos-1] != ' ')
        return false;

    game->state[pos-1] = game->symbols[game->turn-1];

    if (game->turn == 1)
        game->turn = 2;
    else
        game->turn = 1;

    int w = TTT_check_win(game);
    if (w >= 0)
        game->running = false;

    return true;
}

int TTT_check_win(TTT * game) {
    /*
     * 2 -> Player2 win
     * 1 -> Player1 win
     * 0 -> Draw
     * -1 -> Game is running
     */
    
    char p1 = game->symbols[0];
    char p2 = game->symbols[1];
    char *board = strdup(game->state);

    bool all_marked = true;
    for (int i=0; i<9; i++)
        if (game->state[i] == ' ')
            all_marked = false;

    // printf("board: %s\n", board);

    if (
        (board[0] == p1 && board[1] == p1 && board[2] == p1) ||
        (board[3] == p1 && board[4] == p1 && board[5] == p1) ||
        (board[6] == p1 && board[7] == p1 && board[8] == p1) ||

        (board[0] == p1 && board[3] == p1 && board[6] == p1) ||
        (board[1] == p1 && board[4] == p1 && board[7] == p1) ||
        (board[2] == p1 && board[5] == p1 && board[8] == p1) ||

        (board[0] == p1 && board[4] == p1 && board[8] == p1) ||
        (board[6] == p1 && board[4] == p1 && board[2] == p1)
    ) return 1;

    if (
        (board[0] == p2 && board[1] == p2 && board[2] == p2) ||
        (board[3] == p2 && board[4] == p2 && board[5] == p2) ||
        (board[6] == p2 && board[7] == p2 && board[8] == p2) ||

        (board[0] == p2 && board[3] == p2 && board[6] == p2) ||
        (board[1] == p2 && board[4] == p2 && board[7] == p2) ||
        (board[2] == p2 && board[5] == p2 && board[8] == p2) ||

        (board[0] == p2 && board[4] == p2 && board[8] == p2) ||
        (board[6] == p2 && board[4] == p2 && board[2] == p2)
    ) return 2;

    if (all_marked)
        return 0;

    return -1;

}

void TTT_bot_turn(TTT *game) {
    if (!game->running)
        return;

    bool marked_all = true;
    for (int i=0; i<9; i++)
        if (game->state[i] == ' ')
            marked_all = false;

    if (marked_all)
        return;

    srand(time(NULL));
    while (TTT_mark(game, rand()%9+1) != true);
}

Comments