I am making the game of the boats in C, and I want to make the arrangement of the boats of the computer player (played against the computer), be random. For this he had thought of generating random numbers and assigning them to the coordinates of the board. I try the algorithm to generate the numbers in a test file and everything works fine:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
// Declaracion de variables
int fila,i;
int hora = time(NULL);
//semilla de rand
srand(hora);
//ciclo generar 2 coordenadas
for(i = 0; i<1; i++)
{
fila = rand()%10+1;
printf("%d\n",fila);
}
return (fila);
}
I compile and run it without any errors, and it prints a random number.
After trying it out on this loose file, I decide to put it into my game code:
I first declare and seed rand() globally , before main:
int hora = time(NULL);
//semilla rand()
srand(hora);
And this is one of the functions that should generate a random number:
int filaAle()
{
// Declaracion de variables
int fila,i;
//ciclo generar 2 coordenadas
for(i = 0; i<2; i++)
{
fila = rand()%10+1;
printf("%d\n",fila);
}
return fila;
}
When compiling, these are the errors that it gives me (I open the ones with details):
I don't know how to fix these errors, and I need to put this feature to work. Is there any solution?
Thanks in advance.
You can NOT call the
time()
and functionssrand()
BEFORE the methodmain
. If you want to have the variablehora
as a global variable you must initialize it with a constant value. The C99 standard defines in point 6.7.8 paragraph 4:Remember that in a C program the first function called is
main
(with certain exceptions). Therefore, your code intends to call two functions before the functionmain
is executed.One possible solution is that you get the seed for your random generator inside the same function that will assign the random numbers, avoiding using these variables as globals -which on the other hand is a very bad programming practice-.