AllenYuan

Untitled

May 28th, 2020
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. #include <SFML/Graphics.hpp>
  2. #include <iostream>
  3.  
  4. using namespace sf;
  5.  
  6. int main()
  7. {
  8. // app window
  9. RenderWindow app(VideoMode(256,256), "15-Puzzle!");
  10. app.setFramerateLimit(60);
  11.  
  12. Texture t;
  13. t.loadFromFile("/Users/alleyuan/code-snippets/16_games/06 15-Puzzle/images/15.png");
  14.  
  15. int w = 64; // width of square in texture
  16. int grid[6][6] = {0}; // grid
  17. Sprite sprite[20]; // blocks
  18.  
  19. // set grid (position -> number) and sprites (number -> sprite)
  20. int n = 0;
  21. for (int i = 0; i < 4; i++)
  22. for (int j = 0; j < 4; j++)
  23. {
  24. n++;
  25. sprite[n].setTexture(t);
  26. sprite[n].setTextureRect(IntRect(i*w,j*w,w,w));
  27. grid[i+1][j+1] = n;
  28. }
  29.  
  30. // game loop
  31. while (app.isOpen())
  32. {
  33. Event e;
  34. // event handlers
  35. while (app.pollEvent(e))
  36. {
  37. if (e.type == Event::Closed)
  38. app.close();
  39.  
  40. if (e.type == Event::MouseButtonPressed)
  41. // left click handler
  42. if (e.key.code == Mouse::Left)
  43. {
  44. // grab mouse coordinates
  45. Vector2i pos = Mouse::getPosition(app);
  46. int x = pos.x/w + 1;
  47. int y = pos.y/w + 1;
  48.  
  49. int dx = 0;
  50. int dy = 0;
  51.  
  52. // find the offset of (x,y) from the blank square
  53. if (grid[x+1][y] == 16) { dx = 1; dy = 0; };
  54. if (grid[x][y+1] == 16) { dx = 0; dy = 1; };
  55. if (grid[x][y-1] == 16) { dx = 0; dy = -1; };
  56. if (grid[x-1][y] == 16) { dx = -1; dy = 0; };
  57.  
  58. // swap (x,y) with the blank square if they're adjacent along the coordinate axes
  59. int n = grid[x][y];
  60. grid[x][y] = 16;
  61. grid[x+dx][y+dy] = n;
  62. }
  63. }
  64.  
  65. app.clear(Color::White);
  66. for (int i = 0; i < 4; i++)
  67. for (int j = 0; j < 4; j++)
  68. {
  69. int n = grid[i+1][j+1];
  70. sprite[n].setPosition(i*w,j*w);
  71. app.draw(sprite[n]);
  72. }
  73.  
  74. app.display();
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment