From 1169992d50ce930143efe2851d02e7dfa0304e29 Mon Sep 17 00:00:00 2001 From: Ian C Date: Fri, 21 Dec 2018 11:27:26 +0000 Subject: Split code up into separate objects. --- pile.c | 146 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 146 insertions(+) create mode 100644 pile.c (limited to 'pile.c') 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 . + + ------------------------------------------------------------------------- + + Implements a pile of cards + +*/ +#include + +#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 +*/ -- cgit v1.2.3