summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRichard Maw <richard.maw@gmail.com>2013-04-15 21:40:34 +0100
committerRichard Maw <richard.maw@gmail.com>2013-04-15 21:40:34 +0100
commit68c0699679368e8f4373fd3df274cc1df9389a51 (patch)
treec83a2883bfa0b8d568acc6727457fee06cff8979
downloadhigher-lower-68c0699679368e8f4373fd3df274cc1df9389a51.tar.bz2
Add a higher-lower guessing game
-rw-r--r--Makefile15
-rw-r--r--README2
-rw-r--r--higher-lower.c80
3 files changed, 97 insertions, 0 deletions
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..134b1bf
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,15 @@
+CC = gcc
+OBJS = higher-lower.o
+BINS = higher-lower
+
+CFLAGS = -std=c99 `pkg-config --cflags luajit`
+LDLIBS = `pkg-config --libs-only-l luajit`
+LDFLAGS = `pkg-config --libs-only-L luajit`
+
+all: $(BINS)
+
+higher-lower: $(OBJS)
+
+.PHONY: clean
+clean:
+ $(RM) $(OBJS) $(BINS)
diff --git a/README b/README
new file mode 100644
index 0000000..e2ddf3f
--- /dev/null
+++ b/README
@@ -0,0 +1,2 @@
+This is a higher-lower guessing game, used as a vehicle to show some
+more interesting aspects of binding Lua.
diff --git a/higher-lower.c b/higher-lower.c
new file mode 100644
index 0000000..e118fa9
--- /dev/null
+++ b/higher-lower.c
@@ -0,0 +1,80 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <getopt.h>
+#include <lauxlib.h>
+#include <lua.h>
+
+static int rand_range(int min, int max){
+ return min + rand() / (RAND_MAX / (max - min + 1) + 1);
+}
+
+/* Ugly global variables for state */
+static int call_count = 0;
+static int target;
+
+int check_match(int guess){
+ call_count += 1;
+ if (guess > target) {
+ return 1;
+ } else if (guess < target) {
+ return -1;
+ } else {
+ return 0;
+ }
+}
+
+/* Using the given strategy and bounds, attempt to guess the hidden
+ random number */
+int strategy_iterate(int (*check)(int guess), int lower, int upper){
+ for (int i = lower; i <= upper; ++i){
+ if (check(i) == 0){
+ return i;
+ }
+ }
+ return 0;
+}
+
+/* Use processed command line arguments to generate a random number,
+ then delegate to a strategy to guess the number */
+int process_strategy(int min, int max){
+ int guess;
+ target = rand_range(min, max);
+
+ guess = strategy_iterate(check_match, min, max);
+ if (guess != target){
+ fprintf(stderr, "Incorrect guess, got %d, wanted %d\n",
+ guess, target);
+ return 1;
+ }
+
+ printf("Guessed %d in %d attempts\n", target, call_count);
+
+ return 0;
+}
+
+/* Process command line arguments and hand them off to process_strategy */
+int main(int argc, char *argv[]){
+ int min = 0;
+ int max = 99;
+
+ {
+ int opt;
+ while ((opt = getopt(argc, argv, "u:l:")) != -1) {
+ switch (opt) {
+ case 'u':
+ max = atoi(optarg);
+ break;
+ case 'l':
+ min = atoi(optarg);
+ break;
+ default:
+ fprintf(stderr,
+ "Usage: %s [-u max] [-l min]",
+ argv[0]);
+ return 1;
+ }
+ }
+ }
+
+ return process_strategy(min, max);
+}