Skip to content
Snippets Groups Projects
util.cpp 2.12 KiB
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <ctime>

#include "util.h"

int randrange(int min, int max) {
  int range = max - min + 1;
  return (rand() % range) + min;
}

int randchance(double prob) {
  int resolution = RAND_MAX;
  return (rand() % resolution) < (prob * resolution);
}

int sign(int x) {
  if (x > 0) return 1;
  if (x < 0) return -1;
  return 0;
}

void parse_args(int argc, char *argv[], args *args) {
  int i;
  
  // Default parameter values
  args->load = 0;
  args->save = 0;
  args->nummon = 7;
  args->seed = time(NULL);
  
  int valid = 1;
  
  for (i = 1; i < argc; i++) {
    if (!strcmp(argv[i], "--save")) {
      args->save = 1;
    }  else if (!strcmp(argv[i], "--load")) {
      args->load = 1;
    } else if (!strncmp(argv[i], "--seed=", 7)) {
      if (strlen(argv[i]) > 7) {
        args->seed = atoi(argv[i] + 7);
      } else {
        valid = 0;
      }
    } else if (!strncmp(argv[i], "--nummon=", 9)) {
      if (strlen(argv[i]) > 9) {
        args->nummon = atoi(argv[i] + 9);
      } else {
        valid = 0;
      }
    } else if (!strcmp(argv[i], "-h")) {
      valid = 0;
    } else {
      valid = 0;
    }
  }
  
  if (!valid) {
    fprintf(stderr, "Usage: %s [--load --save --seed=<seed> --nummon=<monsters to spawn>]\n", argv[0]);
    fprintf(stderr, "    --load:  \tInstead of generating a random dungeon, loads the saved dungeon\n\t\tfile from ~/.rlg327/dungeon\n");
    fprintf(stderr, "    --save:  \tSaves the dungeon to ~/.rlg327/dungeon\n");
    fprintf(stderr, "    --seed:  \tSeeds the random number generator to the given value. If not\n\t\tspecified, time(NULL) is used as the seed\n");
    fprintf(stderr, "    --nummon:\tSets the number of monsters to generate in the dungeon. If not\n\t\tspecified, the default is 7. Automatically capped at the number\n\t\tof empty spaces in the dungeon.\n");
    fprintf(stderr, "    -h:      \tPrints this help information and exits\n");
    exit(1);
  }
}
int position::operator==(const position &p) {
  return (x == p.x && y == p.y);
}

position &position::operator=(const position &p) {
  x = p.x;
  y = p.y;
  return *this;
}