All pastes #1772801 Raw Edit

cards.c

public text v1 · immutable
#1772801 ·published 2010-01-31 06:13 UTC
rendered paste body
#include "cards.h"

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
	int *deck = deck_create();
	signed char c;
	deck_shuffle_std(deck);
	printf("Cards:\n");
	deck_print_num(deck);
/*	if ((c = deck_deal_first(deck)) != -1) {
		printf("Card dealt: %d (", c);
		card_print(c);
		printf(")\n");
		deck_print(deck);
		printf("\n");
	}*/
	deck_clear(deck);
	return 0;
}

int *deck_create() {
	int x, i;
	int *deck = (int *)malloc(sizeof(int)*DECK_SIZE);
	for (x = 1; x < (DECK_AMOUNT+1); x++) {
		for (i = 0; i < DECK_SIZE; i++) {
			*(deck + (i*x)) = i;
		}
	}
	return deck;
}

void deck_reset(int *deck) {
	int x, i;
	for (x = 0; x < DECK_AMOUNT; x++) {
		for (i = 0; i < DECK_SIZE; i++) *(deck + (i*x)) = i;
	}
	return;
}

void card_print(int card) {
	char suit[4][9] = { "Spades", "Hearts", "Diamonds", "Clubs" };
	char number[13][6] = { "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" };
	if (card == -1) {
		printf("Dealt Card");
		return;
	}
	printf("%s of %s", *(number + (card%13)), *(suit + (card/13)));
	return;
}

void deck_print(int *deck) {
	int x;
	if (deck == NULL) return;
	for (x = 0; x < (DECK_SIZE/4); x++) {
		card_print(*(deck+x));
		printf("\t\t");
		card_print(*(deck+x+1));
		printf("\t\t");
		card_print(*(deck+x+2));
		printf("\t\t");
		card_print(*(deck+x+3));
		printf("\n");
	}
	printf("\n");
	return;
}

void deck_print_num(int *deck) {
	int x;
	if (deck == NULL) return;
	for (x = 0; x < (DECK_SIZE/4); x++) {
		printf("%d\t%d\t%d\t%d\n", *(deck+x), *(deck+x+1), *(deck+x+2), *(deck+x+3));
	}
	printf("\n");
	return;
}

void deck_clear(int *deck) {
	if (deck == NULL) return;
	free(deck);
	return;
}

void deck_shuffle_std(int *deck) {
	int x, r;
	if (deck == NULL) return;
	srand((time(NULL)/getpid())+rand());
	for (x = 0; x < DECK_SIZE; x++) {
		r = rand()%DECK_SIZE;
		SWAP(deck[x], deck[r]);
	}
	return;
}

void deck_faro_shuffle(int *deck)  {
	int x;
	if (deck == NULL) return;
	for (x = 0; x < (DECK_SIZE/2); x += 2) SWAP(deck[x], deck[26+x]);
	return;
}

signed char deck_deal_first(int *deck) {
	int x;
	signed char r = 0;
	if (deck == NULL) return -1;
	for (x = 0; x < DECK_SIZE; x++) {
		if (*(deck + x) != -1) {
			r = *(deck + x);
			*(deck + x) = -1;
			break;
		}
	}
	return ((x == 52)? -1:r);
}