Advertisement
Guest User

Untitled

a guest
Jun 29th, 2016
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. void init(void)
  2. {
  3. {
  4. n = d * d - 1;
  5. blank_tile = n;
  6. for (int i = 0; i < d; i++){
  7. for (int j = 0; j < d; j++) {
  8. board[i][j] = n;
  9. n--;
  10. }
  11. }
  12.  
  13. n = blank_tile;
  14.  
  15. // switches the last two tiles if the board is of an odd dimension
  16. if ((d % 2) != 0) {
  17. int temp = board[d][d-1];
  18. board[d][d-1] = board[d][d-2];
  19. board[d][d-2] = temp;
  20. }
  21. }
  22. }
  23.  
  24. /**
  25. * Prints the board in its current state.
  26. */
  27. void draw(void)
  28. {
  29. int current = 0;
  30. for (int i = 0; i < d; i++){
  31. for (int j = 0; j < d; j++) {
  32. // prints the underscore or blank tile
  33. if (current == blank_tile){
  34. printf("|_|");
  35. } else {
  36. printf("|%d|", board[i][j]);
  37. }
  38. current++;
  39. }
  40. printf("\n");
  41. }
  42. }
  43.  
  44. /**
  45. * If tile borders empty space, moves tile and returns true, else
  46. * returns false.
  47. */
  48. bool move(int tile)
  49. {
  50. int temp = n - tile + 1;
  51. tile = temp;
  52.  
  53. if (tile < 0 || tile > n)
  54. return false;
  55. //printf("Value: %d\n", tile);
  56.  
  57. if (((tile % d) != 0 && (tile - 1) == blank_tile) || // checks to the left and makes sure that it it is not up against left edge
  58. ((tile % d) != (d-1) && (tile + 1) == blank_tile) || // makes sure that it is not up against right edge and checks to the right
  59. (tile - d) == blank_tile || // checks upward
  60. (tile + d) == blank_tile) { // checks downward
  61. int blank_row = blank_tile / d;
  62. int blank_col = blank_tile % d;
  63. int tile_row = tile / d;
  64. int tile_col = tile % d;
  65. board[blank_row][blank_col] = board[tile_row][tile_col];
  66. blank_tile = tile;
  67. return true;
  68. }
  69. return false;
  70. }
  71.  
  72. /**
  73. * Returns true if game is won (i.e., board is in winning configuration),
  74. * else false.
  75. */
  76. bool won(void)
  77. {
  78. int current_tile = -1;
  79. for (int i = 0; i < d; i++){
  80. for (int j = 0; j < d; j++) {
  81. if (board[i][j] > current_tile) {
  82. current_tile = board[i][j];
  83. } else {
  84. return false;
  85. }
  86. }
  87. }
  88. return true;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement