about summary refs log tree commit diff
path: root/stack.h
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--stack.h74
1 files changed, 74 insertions, 0 deletions
diff --git a/stack.h b/stack.h
new file mode 100644
index 0000000..46b9091
--- /dev/null
+++ b/stack.h
@@ -0,0 +1,74 @@
+/* Copyright (C) 2019  C. McEnroe <june@causal.agency>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef STACK_H
+#define STACK_H
+
+#include <SDL_stdinc.h>
+#include <assert.h>
+
+struct Stack {
+	Uint8 len;
+	Sint8 cards[52];
+};
+
+static inline void stackClear(struct Stack *stack) {
+	stack->len = 0;
+}
+
+static inline void stackPush(struct Stack *stack, Sint8 card) {
+	assert(stack->len < 52);
+	stack->cards[stack->len++] = card;
+}
+
+static inline Sint8 stackPop(struct Stack *stack) {
+	if (!stack->len) return 0;
+	return stack->cards[--stack->len];
+}
+
+static inline void stackFlipTo(struct Stack *dst, struct Stack *src, Uint8 n) {
+	if (n > src->len) n = src->len;
+	for (Uint8 i = 0; i < n; ++i) {
+		stackPush(dst, -stackPop(src));
+	}
+}
+
+static inline void stackMoveTo(struct Stack *dst, struct Stack *src, Uint8 n) {
+	if (n > src->len) n = src->len;
+	for (Uint8 i = 0; i < n; ++i) {
+		stackPush(dst, src->cards[src->len - n + i]);
+	}
+	src->len -= n;
+}
+
+static inline void stackDeck(struct Stack *stack) {
+	stackClear(stack);
+	for (Sint8 i = 1; i <= 52; ++i) {
+		stackPush(stack, -i);
+	}
+}
+
+// FIXME: Use a portable random.
+static inline void stackShuffle(struct Stack *stack) {
+	for (Uint8 i = stack->len - 1; i > 0; --i) {
+		Uint8 j = arc4random_uniform(i + 1);
+		Sint8 x = stack->cards[i];
+		stack->cards[i] = stack->cards[j];
+		stack->cards[j] = x;
+	}
+}
+
+#endif