AllenYuan

Untitled

May 27th, 2020
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. #include <SFML/Graphics.hpp>
  2. #include <time.h>
  3. using namespace sf;
  4.  
  5. int main()
  6. {
  7. srand(time(0));
  8.  
  9. RenderWindow app(VideoMode(480, 480), "Minesweeper");
  10.  
  11. int w = 32; // width of a texture rectangle
  12. int grid[12][12]; // grid, encoded by index of rectangle in tiles.jpg to display
  13. int sgrid[12][12]; // shown grid
  14.  
  15. // load texture/sprite
  16. Texture t;
  17. t.loadFromFile("/Users/alleyuan/code-snippets/16_games/05 Minesweeper/images/tiles.jpg");
  18. Sprite s(t);
  19.  
  20. // set initial state of sgrid and grid
  21. for (int i = 1; i <= 10; i++)
  22. for (int j = 1; j <= 10; j++)
  23. {
  24. sgrid[i][j] = 10; // all squares untouched to the player
  25. if (rand()%5 == 0) grid[i][j] = 9; // 1/5 chance of placing a mine
  26. else (grid[i][j]) = 0; // else set an empty grid
  27. }
  28.  
  29. // set mine counts
  30. for (int i = 1; i <= 10; i++)
  31. for (int j = 1; j <= 10; j++)
  32. {
  33. int n = 0;
  34. if (grid[i][j] == 9) continue;
  35. if (grid[i+1][j] == 9) n++;
  36. if (grid[i][j+1] == 9) n++;
  37. if (grid[i-1][j] == 9) n++;
  38. if (grid[i][j-1] == 9) n++;
  39. if (grid[i+1][j+1] == 9) n++;
  40. if (grid[i-1][j-1] == 9) n++;
  41. if (grid[i-1][j+1] == 9) n++;
  42. if (grid[i+1][j-1] == 9) n++;
  43. grid[i][j] = n;
  44. }
  45.  
  46. while (app.isOpen()) // game loop
  47. {
  48. // event handlers
  49. Event e;
  50. while (app.pollEvent(e))
  51. {
  52. if (e.type == Event::Closed)
  53. app.close();
  54. }
  55.  
  56. // redraw sgrid
  57. app.clear(Color::White);
  58. for (int i = 1; i <= 10; i++)
  59. for (int j = 1; j <= 10; j++)
  60. {
  61. sgrid[i][j] = grid[i][j]; // test for grid generation
  62. s.setTextureRect(IntRect(sgrid[i][j]*w,0,w,w)); // paint the sgrid[i][j]th rectangle
  63. s.setPosition(i*w, j*w);
  64. app.draw(s);
  65. }
  66.  
  67. app.display();
  68. }
  69.  
  70. return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment