לדלג לתוכן

3.5 - מודולריות - פתרון

מבנה הפרויקט:

tic_tac_toe/
├── main.c
├── game.c
├── game.h

game.h – קובץ Header

// game.h
#ifndef GAME_H
#define GAME_H

void init_board(char board[3][3]);
void print_board(char board[3][3]);
int play_turn(char board[3][3], char player);
int check_win(char board[3][3], char player);

#endif

game.c – קובץ הפונקציות

// game.c
#include <stdio.h>
#include "game.h"

void init_board(char board[3][3]) {
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            board[i][j] = '.';
}

void print_board(char board[3][3]) {
    printf("  0 1 2\n");
    for (int i = 0; i < 3; i++) {
        printf("%d ", i);
        for (int j = 0; j < 3; j++)
            printf("%c ", board[i][j]);
        printf("\n");
    }
}

int play_turn(char board[3][3], char player) {
    int row, col;
    printf("Turn: %c. Enter row and column (0-2): ", player);
    scanf("%d %d", &row, &col);

    if (row < 0 || row > 2 || col < 0 || col > 2) {
        printf("Invalid position. Try again.\n");
        return 0;
    }

    if (board[row][col] != '.') {
        printf("The spot is taken. Try again.\n");
        return 0;
    }

    board[row][col] = player;
    return 1;
}

int check_win(char board[3][3], char player) {
    for (int i = 0; i < 3; i++) {
        if ((board[i][0] == player &&
             board[i][1] == player &&
             board[i][2] == player) ||
            (board[0][i] == player &&
             board[1][i] == player &&
             board[2][i] == player)) {
            return 1;
        }
    }

    if ((board[0][0] == player &&
         board[1][1] == player &&
         board[2][2] == player) ||
        (board[0][2] == player &&
         board[1][1] == player &&
         board[2][0] == player)) {
        return 1;
    }

    return 0;
}

main.c – קובץ ההרצה

// main.c
#include <stdio.h>
#include "game.h"

int main() {
    char board[3][3];
    char player = 'X';
    int win = 0;
    int moves = 0;

    init_board(board);

    while (!win && moves < 9) {
        print_board(board);

        if (!play_turn(board, player)) {
            continue; // if the input is invalid, repeat the turn
        }

        moves++;

        if (check_win(board, player)) {
            print_board(board);
            printf("Well done! %c won!\n", player);
            win = 1;
            break;
        }

        // switch turn
        player = (player == 'X') ? 'O' : 'X';
    }

    if (!win) {
        print_board(board);
        printf("Tie! No one won.\n");
    }

    return 0;
}

קומפילציה:

gcc main.c game.c -o ttt
./ttt