AllenYuan

Untitled

May 27th, 2020
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 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. // grab the mouse location in the grid
  49. Vector2i pos = Mouse::getPosition(app);
  50. int x = pos.x/w;
  51. int y = pos.y/w;
  52.  
  53. // event handlers
  54. Event e;
  55. while (app.pollEvent(e))
  56. {
  57. // close window
  58. if (e.type == Event::Closed)
  59. app.close();
  60.  
  61. // reveal/flag grids in response to clicks
  62. if (e.type == Event::MouseButtonPressed)
  63. if (e.key.code == Mouse::Left) sgrid[x][y] = grid[x][y];
  64. else if (e.key.code == Mouse::Right) sgrid[x][y] = 11;
  65. }
  66.  
  67. // redraw sgrid
  68. app.clear(Color::White);
  69. for (int i = 1; i <= 10; i++)
  70. for (int j = 1; j <= 10; j++)
  71. {
  72. if (sgrid[x][y] == 9) sgrid[i][j] = grid[i][j]; // on clicking a mine, reveal the whole grid (game over)
  73. s.setTextureRect(IntRect(sgrid[i][j]*w,0,w,w)); // paint the sgrid[i][j]th rectangle
  74. s.setPosition(i*w, j*w);
  75. app.draw(s);
  76. }
  77.  
  78. app.display();
  79. }
  80.  
  81. return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment