Advertisement
John_Conner

Hangs about once every 12 runs

Mar 11th, 2014
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.15 KB | None | 0 0
  1. // Chapter 8 Programming Project #9
  2.  
  3. #include <stdio.h>
  4. #include <stdbool.h>
  5. #include <stdlib.h>
  6. #include <time.h>
  7.  
  8. #define SIZE 10
  9. #define PATH_SIZE 25
  10. #define ROW_SIZE ((int) (sizeof(board) / sizeof(board[0])))
  11.  
  12. int main(void)
  13. {
  14.     char board[SIZE][SIZE] = {};
  15.     // 0 = Up, 1 = Down, 2 = Left, 3 = Right
  16.     unsigned short i = 0, x, y;
  17.     // Generate a random number
  18.     srand((unsigned) time(NULL));
  19.     int dir = rand() % 4;
  20.     // Set all positions of board to '.'
  21.     for (x = 0; x < ROW_SIZE; x++) {
  22.         for (y = 0; y < ROW_SIZE; y++)
  23.             board[x][y] = '.';
  24.     }
  25.     x = 0;
  26.     y = 0;
  27.     board[0][0] = 'A';
  28.     // Generate the path
  29.     for (i = 0; i < PATH_SIZE;) {
  30.             // Check that the last character has not been cornered
  31.         if ((board[x][y - 1] != '.' || y - 1 < 0) &&
  32.             (board[x][y + 1] != '.' || y + 1 > ROW_SIZE) &&
  33.             (board[x - 1][y] != '.' || x - 1 < 0) &&
  34.             (board[x + 1][y] != '.' || x + 1 > ROW_SIZE))
  35.             break;
  36.         // Check the direction and replace that char
  37.         switch (dir) {
  38.             case 0: if ((y - 1) >= 0
  39.                         && board[x][y - 1] == '.') {
  40.                         board[x][--y] = i + 'B';
  41.                         ++i;
  42.                     } break;
  43.             case 1: if ((y + 1) < ROW_SIZE
  44.                         && board[x][y + 1] == '.') {
  45.                         board[x][++y] = i + 'B';
  46.                         ++i;
  47.                     } break;
  48.             case 2: if ((x - 1) >= 0
  49.                         && board[x - 1][y] == '.') {
  50.                         board[--x][y] = i + 'B';
  51.                         ++i;
  52.                     } break;
  53.             case 3: if ((x + 1) < ROW_SIZE
  54.                         && board[x + 1][y] == '.') {
  55.                         board[++x][y] = i + 'B';
  56.                         ++i;
  57.                     } break;
  58.         }
  59.     // Reset the random directions
  60.     dir = rand() % 4;
  61.     }
  62.     // Print the board
  63.     for (x = 0; x < ROW_SIZE; x++) {
  64.         for (y = 0; y < ROW_SIZE; y++)
  65.             printf("%4c ", board[x][y]);
  66.         printf("\n");
  67.     }
  68.  
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement