MCPcopy Create free account
hub / github.com/LemonOSProject/LemonOS / Generate

Method Generate

Applications/Minesweeper/main.cpp:81–145  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

79 }
80
81 void Generate(int diff){
82 if(tiles){
83 for(int i = 0; i < mapSize.y; i++){
84 delete tiles[i];
85 }
86
87 delete tiles;
88 }
89
90 difficulty = diff;
91
92 mapSize = difficultySizes[difficulty];
93 int mineCount = difficultyMineCounts[difficulty];
94
95 bounds = {0, 0, mapSize.x * 16, mapSize.y * 16};
96 UpdateFixedBounds();
97
98 tiles = new Tile*[mapSize.y];
99 for(int i = 0; i < mapSize.y; i++)
100 tiles[i] = new Tile[mapSize.x];
101
102
103 timespec bTime;
104 clock_gettime(CLOCK_BOOTTIME, &bTime);
105 srand(bTime.tv_sec + bTime.tv_nsec);
106
107 while(mineCount--){
108 int x = rand() % mapSize.x;
109 int y = rand() % mapSize.y;
110
111 int i = 8;
112 while(tiles[y][x].type == MineTile && i--){ // Do not place a mine on a tile that already has a mine, try 8 times
113 x = rand() % mapSize.x;
114 y = rand() % mapSize.y;
115 }
116
117 tiles[y][x].type = MineTile;
118 }
119
120 for(int y = 0; y < mapSize.y; y++){
121 for(int x = 0; x < mapSize.x; x++){
122 Tile& tile = tiles[y][x];
123
124 tile.hidden = true;
125 tile.flagged = false;
126
127 if(tile.type == MineTile)
128 continue; // Don't calculate surrounding mines for mine tiles
129
130 for(int i = std::max(0, y - 1); i <= y + 1 && i < mapSize.y; i++){
131 if(x - 1 >= 0 && tiles[i][x - 1].type == MineTile){
132 tile.surroundingMines++;
133 }
134
135 if(tiles[i][x].type == MineTile){
136 tile.surroundingMines++;
137 }
138

Callers 1

mainFunction · 0.80

Calls 1

randFunction · 0.85

Tested by

no test coverage detected