Facebook
From Diminutive Echidna, 5 Years ago, written in Plain Text.
This paste is a reply to Untitled from Innocent Ibis - view diff
Embed
Download Paste or View Raw
Hits: 443
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include "object.h"
  5. #include <assert.h>
  6. void Object_destroy(void *self)
  7. {
  8.  Object *obj = self;
  9.  if(obj) {
  10.  if(obj->description) free(obj->description);
  11.  free(obj);
  12.  }
  13. }
  14. void Object_describe(void *self)
  15. {
  16.  Object *obj = self;
  17.  printf("%s.\n", obj->description);
  18. }
  19. int Object_init(void *self)
  20. {
  21.  // do nothing really
  22.  return 1;
  23. }
  24. void *Object_move(void *self, Direction direction)
  25. {
  26.  printf("You can't go that direction.\n");
  27.  return NULL;
  28. }
  29. int Object_attack(void *self, int damage)
  30. {
  31.  printf("You can't attack that.\n");
  32.  return 0;
  33. }
  34. void *Object_new(size_t size, Object proto, char *description)
  35. {
  36.  // setup the default functions in case they aren't set
  37.  if(!proto.init) proto.init = Object_init;
  38.  if(!proto.describe) proto.describe = Object_describe;
  39.  if(!proto.destroy) proto.destroy = Object_destroy;
  40.  if(!proto.destroy) proto.destroy = Object_destroy;
  41.  if(!proto.attack) proto.attack = Object_attack;
  42.  if(!proto.move) proto.move = Object_move;
  43.  // this seems weird, but we can make a struct of one size,
  44.  // then point a different pointer at it to "cast" it
  45.  Object *el = calloc(1, size);
  46.  *el = proto;
  47.  // copy the description over
  48.  el->description = strdup(description);
  49.  // initialize it with whatever init we were given
  50.  if(!el->init(el)) {
  51.  // looks like it didn't initialize properly
  52.  el->destroy(el);
  53.  return NULL;
  54.  } else {
  55.  // all done, we made an object of any type
  56.  return el;
  57.  }
  58. }typedef enum {
  59.  NORTH, SOUTH, EAST, WEST
  60. } Direction;
  61. typedef struct {
  62.  char *description;
  63.  int (*init)(void *self);
  64.  void (*describe)(void *self);
  65.  void (*destroy)(void *self);
  66.  void *(*move)(void *self, Direction direction);
  67.  int (*attack)(void *self, int damage);
  68. } Object;
  69. int Object_init(void *self);
  70. void Object_destroy(void *self);
  71. void Object_describe(void *self);
  72. void *Object_move(void *self, Direction direction);
  73. int Object_attack(void *self, int damage);
  74. void *Object_new(size_t size, Object proto, char *description);
  75. #define NEW(T, N) Object_new(sizeof(T), T##Proto, N)
  76. #define _(N) proto.N
  77.  

Replies to Re: Untitled rss

Title Name Language When
Re: Re: Untitled Hot Pheasant text 5 Years ago.