Here's the second part using just functions. The code's a bit ugly though.
Code:
/*Minesweeper BS
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
#include <iostream>
int GetRand(int min, int max);
void count_mines_around(char[][10],int x[],int y[],int N);
using namespace std;
int main()
{
char array[10][10];
int i, r, N,n,nt;
int x[80];
int y[80];
cout<<"Randomly placing 5 mines..."<<endl;
N=5;
for (int i=0; i<N; i++)
{
n = GetRand(0,8);
x[i]=n;
//cout<<" "<<x[i];
}
cout<<endl;
for (int j=0; j<N; j++)
{
nt = GetRand(0,8);
y[j]=nt;
}
cout<<endl;
//initialise array
for (int a=0; a<9; a++)
{
for (int b=0; b<9; b++)
{
array[a][b]=' ';
}
}
for (int i=0; i<9; i++)
{
for(int j=0; j<9; j++)
{
for (int k=0; k<N; k++)
{
if((i==x[k])&&(j==y[k]))
{
array[i][j]='*';
}
}
}
}
for (int i=0; i <9; i++)
{
for (int j=0; j<9; j++)
{
cout<<"["<<array[i][j]<<"]";
}
cout<<endl;
}
count_mines_around(array,x,y,N);
int stop;
cin>>stop;
return 0;
}
int GetRand(int min, int max)
{
static int Init = 0;
int r;
if (Init == 0)
{
/*
* As Init is static, it will remember it's value between
* function calls. We only want srand() run once, so this
* is a simple way to ensure that happens.
*/
srand(time(NULL));
Init = 1;
}
/*
* Formula:
* rand() % N <- To get a number between 0 - N-1
* Then add the result to min, giving you
* a random number between min - max.
*/
r = (rand() % (max - min + 1) + min);
return r;
}
void count_mines_around(char array[10][10],int x[10],int y[10],int N)
{
char array_t[10][10];
for (int i=0; i<9 ; i++)
{
for (int j=0; j<9; j++)
{
int i_n=i-1;
int j_n=j-1;
int counts=0;
int counter=0;
for (int y=i_n; y<i_n+3; y++)
{
for(int z=j_n; z<j_n+3; z++)
{
counter++;
if ((y>=0)&& (y<=8))
{
if ((z>=0)&& (z<=8))
{
if (counter!=5)
{
if(array[y][z]=='*')
{
counts++;
}
}
}
}
}
}
counter=0;
//cout<<counts;
if (counts==0)
{
array_t[i][j]=' ';
}
if(counts==1)
{
array_t[i][j]='1';
}
if(counts==2)
{
array_t[i][j]='2';
}
if(counts==3)
{
array_t[i][j]='3';
}
if(counts==4)
{
array_t[i][j]='4';
}
if(counts==5)
{
array_t[i][j]='5';
}
if(counts==6)
{
array_t[i][j]='5';
}
if(counts==7)
{
array_t[i][j]='7';
}
if(counts==8)
{
array_t[i][j]='8';
}
if(counts==9)
{
array_t[i][j]='9';
}
counts=0;
}
}
cout<<""<<endl;
cout<<""<<endl;
for (int i=0; i <9; i++)
{
for (int j=0; j<9; j++)
{
for (int k=0; k<N; k++)
{
if((i==x[k])&&(j==y[k]))
{
array_t[i][j]='*';
}
}
cout<<"["<<array_t[i][j]<<"]";
}
cout<<endl;
}
}
Sample output:
Code:
Randomly placing 5 mines...
[ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][*]
[ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][*]
[ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][*][ ][ ][*][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][*][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][1][1]
[ ][ ][ ][ ][ ][ ][ ][1][*]
[ ][ ][ ][ ][ ][ ][ ][1][1]
[ ][ ][ ][ ][ ][ ][ ][1][1]
[ ][ ][ ][ ][ ][ ][ ][1][*]
[ ][ ][ ][1][1][1][1][2][2]
[ ][ ][ ][1][*][1][1][*][1]
[ ][1][1][2][1][1][1][1][1]
[ ][1][*][1][ ][ ][ ][ ][ ]