Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #define MAX(a,b) ((a) > (b) ? (a) : (b))
- #define NAUGHT -1
- #define CROSS 1
- int x, y, maxdist, board[3][3];
- /* Prototypes */
- void getmove (int);
- void printboard (void);
- void updatemax (void);
- int inbounds (int, int);
- int distancegoing (int, int, int, int, int);
- int horizontaldistance (int, int);
- int verticaldistance (int, int);
- int ascdiagdistance (int, int);
- int dscdiagdistance (int, int);
- /* Functions */
- int main (void) {
- int lastplayer = NAUGHT;
- int moves = 0;
- do {
- fprintf(stdout, "Turn for: %c\n", (lastplayer == NAUGHT ? 'O' : 'X'));
- getmove(lastplayer);
- printboard();
- updatemax();
- lastplayer *= -1;
- } while (maxdist < 2 && ++moves < 9);
- if (moves < 9) {
- fprintf(stdout, "%c wins!\n", (-lastplayer == NAUGHT ? 'O' : 'X'));
- } else {
- fprintf(stdout, "Tie!\n");
- }
- return 0;
- }
- void getmove (int player) {
- do {
- fprintf(stdout, "(x,y) = ");
- scanf("%d %d", &x, &y);
- } while (!inbounds(x,y) || board[x][y]);
- board[x][y] = player;
- }
- void printboard (void) {
- putc('\n', stdout);
- for (int i = 0; i < 3; i++) {
- for (int j = 0; j < 3; j++) {
- fprintf(stdout, " %c ", (board[i][j] ? (board[i][j] > 0 ? 'X' : 'O') : '_'));
- }
- putc('\n', stdout);
- }
- putc('\n', stdout);
- }
- void updatemax (void) {
- int h = horizontaldistance(x, y);
- int v = verticaldistance(x, y);
- int ad = ascdiagdistance(x, y);
- int dd = dscdiagdistance(x, y);
- maxdist = MAX(h, MAX(v, MAX(ad, dd)));
- }
- /* Supporting functions */
- int inbounds (int x, int y) {
- return (x >= 0 && x < 3 && y >= 0 && y < 3);
- }
- int distancegoing (int player, int x, int y, int dx, int dy) {
- int d = 0;
- while (inbounds((x += dx), (y += dy)) && (player * board[x][y] > 0)) {
- d++;
- }
- return d;
- }
- int horizontaldistance (int x, int y) {
- return distancegoing(board[x][y], x, y, -1, 0) + distancegoing(board[x][y], x, y, 1, 0);
- }
- int verticaldistance (int x, int y) {
- return distancegoing(board[x][y], x, y, 0, -1) + distancegoing(board[x][y], x, y, 0, 1);
- }
- int ascdiagdistance (int x, int y) {
- return distancegoing(board[x][y], x, y, 1, -1) + distancegoing(board[x][y], x, y, -1, 1);
- }
- int dscdiagdistance (int x, int y) {
- return distancegoing(board[x][y], x, y, -1, -1) + distancegoing(board[x][y], x, y, 1, 1);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement