summaryrefslogtreecommitdiff
path: root/pile.c
diff options
context:
space:
mode:
Diffstat (limited to 'pile.c')
-rw-r--r--pile.c146
1 files changed, 146 insertions, 0 deletions
diff --git a/pile.c b/pile.c
new file mode 100644
index 0000000..793cc7c
--- /dev/null
+++ b/pile.c
@@ -0,0 +1,146 @@
+/*
+
+ csol - CURSES solitaire
+
+ Copyright (C) 2018 Ian Cowburn (ianc@noddybox.co.uk)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+ -------------------------------------------------------------------------
+
+ Implements a pile of cards
+
+*/
+#include <stdlib.h>
+
+#include "pile.h"
+#include "util.h"
+
+void AddToPile(Pile *pile, Card card)
+{
+ pile->no++;
+
+ pile->card = realloc(pile->card, sizeof *pile->card * pile->no);
+
+ if (!pile->card)
+ {
+ Fatal("Failed to reallocate memory");
+ }
+ else
+ {
+ pile->card[pile->no - 1] = card;
+ }
+}
+
+void InsertBottomOfPile(Pile *pile, Card card)
+{
+ pile->no++;
+
+ pile->card = realloc(pile->card, sizeof *pile->card * pile->no);
+
+ if (!pile->card)
+ {
+ Fatal("Failed to reallocate memory");
+ }
+ else
+ {
+ int f;
+
+ for(f = pile->no - 1; f > 0; f--)
+ {
+ pile->card[f] = pile->card[f - 1];
+ }
+
+ pile->card[0] = card;
+ }
+}
+
+Card PopPile(Pile *pile)
+{
+ Card c = {0};
+
+ if (pile->no)
+ {
+ c = pile->card[pile->no - 1];
+
+ pile->no--;
+
+ if (pile->no)
+ {
+ pile->card = realloc(pile->card, sizeof *pile->card * pile->no);
+
+ if (!pile->card)
+ {
+ Fatal("Failed to reallocate memory");
+ }
+ }
+ else
+ {
+ free(pile->card);
+ pile->card = NULL;
+ }
+ }
+ else
+ {
+ free(pile->card);
+ pile->card = NULL;
+ }
+
+ return c;
+}
+
+Card TopOfPile(Pile *pile)
+{
+ Card c = {0};
+
+ if (pile->no)
+ {
+ c = pile->card[pile->no - 1];
+ }
+
+ return c;
+}
+
+void MoveTopCard(Pile *from, Pile *to)
+{
+ Card c;
+
+ if (from->no)
+ {
+ c = PopPile(from);
+ AddToPile(to, c);
+ }
+}
+
+void SwapPile(Pile *a, Pile *b)
+{
+ Pile t;
+
+ t = *a;
+ *a = *b;
+ *b = t;
+}
+
+void FreePile(Pile *p)
+{
+ if (p->card)
+ {
+ free(p->card);
+ p->card = NULL;
+ }
+}
+
+/*
+vim: ai sw=4 ts=8 expandtab
+*/