'I can't figure out why it works half the time
My own minesweeper I am trying to make
#include <time.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
int randNum(int minimum, int maximum);
int checkSurroundings(int x, int y);
//settings:
int diffi = 3; //how frequently mines show up, 1/n
const int width = 10, height = 10; //height and width of the board
int state[10][10]; //couldn't make it dynamic with W and H,
//it gives me an error that it is at file scope
int mineshape = 'X';
//the main
void main(){
srand(time(NULL)); //seeds the randomizer once at the start
state[height][height];
for(int y = 0; y < height; y++){
printf("/ ");
for(int x = 0; x < width; x++){
state[x][y] = randNum(0, diffi);
//assigns the board values accordingly
if (state[x][y] == diffi){
state[x][y] = mineshape;
}
else{
state[x][y] = checkSurroundings(x, y);
}
printf("%c ", state[x][y]);
}
printf("/ %d\n",y + 1);
}
}
the RNG I used to generate mine cells: (I don't think this has anything to do with the problem), I got it from google
int randNum(int minimum, int maximum){
int result = 0, low_num = 0, hi_num = 0;
if (minimum < maximum){
low_num = minimum;
hi_num = maximum + 1;
}
else{
low_num = maximum + 1;
hi_num = minimum;
}
result = (rand() % (hi_num - low_num)) + low_num;
return result;
}
this was my implementation to loop over the surrounding cells and check them:
/*int checkSurroundings(int x, int y){
int mines = 0, i, j;
for(j = y-1; j <= y+1; j++){
for(i = x-1; i <= x+1; i++){
if(state[i][j] == mineshape){
mines++;
}
}
}
return mines + 48;
}
*/
here I used a manual code to check surroundings, marked the broken instructions with x in the comment: both implementations have the same problem with checking all the cells around.
int checkSurroundings(int x, int y){
int mines = 0, i, j;
if(state[x-1][y-1] == mineshape){ //top left
mines++;
}
if(state[x][y-1] == mineshape){ //top
mines++;
}
if(state[x+1][y-1] == mineshape){ //top right
mines++;
}
if(state[x-1][y] == mineshape){ //left
mines++;
}
if(state[x+1][y] == mineshape){ //x right
mines++;
}
if(state[x-1][y+1] == mineshape){ //x bottom left
mines++;
}
if(state[x][y+1] == mineshape){ //x bottom
mines++;
}
if(state[x+1][y+1] == mineshape){ //x bottom right
mines++;
}
return mines + 48;
}
it for some reason doesn't check the cells at the right, bottom-left, bottom, bottom-right cells around the current cell, and I can't figure it out. I am new to coding, started learning C around 2 months ago.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|