changeset 185:7103d6574062

core: add nrand function
author David Demelier <markand@malikania.fr>
date Tue, 03 Nov 2020 18:13:40 +0100
parents c92957c3b82b
children f37b8e95aaaa
files libcore/core/core.c libcore/core/util.c libcore/core/util.h
diffstat 3 files changed, 28 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/libcore/core/core.c	Mon Nov 02 18:35:44 2020 +0100
+++ b/libcore/core/core.c	Tue Nov 03 18:13:40 2020 +0100
@@ -16,12 +16,18 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
 
+#include <stddef.h>
+#include <stdlib.h>
+#include <time.h>
+
 #include "core.h"
 #include "sys.h"
 
 bool
 core_init(void)
 {
+	srand(time(NULL));
+
 	return sys_init();
 }
 
--- a/libcore/core/util.c	Mon Nov 02 18:35:44 2020 +0100
+++ b/libcore/core/util.c	Tue Nov 03 18:13:40 2020 +0100
@@ -16,6 +16,9 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
 
+#include <assert.h>
+#include <stdlib.h>
+
 #include <SDL.h>
 
 #include "util.h"
@@ -25,3 +28,11 @@
 {
 	SDL_Delay(ms);
 }
+
+unsigned int
+nrand(unsigned int lower, unsigned int upper)
+{
+	assert(upper <= RAND_MAX);
+
+	return (rand() % (upper - lower + 1)) + lower;
+}
--- a/libcore/core/util.h	Mon Nov 02 18:35:44 2020 +0100
+++ b/libcore/core/util.h	Tue Nov 03 18:13:40 2020 +0100
@@ -51,4 +51,15 @@
 void
 delay(unsigned int ms);
 
+/**
+ * Generate a random number between lower and upper (included).
+ *
+ * \pre upper must be <= RAND_MAX
+ * \param lower the lower bound
+ * \param upper the upper bound
+ * \return The generated number.
+ */
+unsigned int
+nrand(unsigned int lower, unsigned int upper);
+
 #endif /* !MOLKO_UTIL_H */