~ajpaon/squell

d2cef6d561561613ff68582aa42ce15a2231d290 — Andrew Paon 10 months ago 38085e7
Don't allow players to reshuffle new pieces via undo

Previously, when a player received new pieces they could undo and
re-place their last piece to get a new random set of pieces.

Now we use reentrant rand functions and store their state on struct
Game. When a previous version of Game is restored, so is the previous
PRNG state, thus we get the same set of pieces next time they are
refilled.
1 files changed, 17 insertions(+), 8 deletions(-)

M main.c
M main.c => main.c +17 -8
@@ 262,24 262,31 @@ struct Game {
  enum GameState state;
  int score;

  struct drand48_data prng_state;

  // player input
  int active_piece;
  int active_row;
  int active_column;
};

struct Piece random_piece() { return PIECES[random() % NPIECES]; }
struct Piece random_piece(struct Game *g) {
  long result;
  lrand48_r(&g->prng_state, &result);

  return PIECES[result % NPIECES];
}

void fill_table(struct Game *g) {
  g->table[0] = random_piece();
  g->table[0] = random_piece(g);

  // No duplicate pieces
  do {
    g->table[1] = random_piece();
    g->table[1] = random_piece(g);
  } while (g->table[0].field == g->table[1].field);

  do {
    g->table[2] = random_piece();
    g->table[2] = random_piece(g);
  } while (g->table[0].field == g->table[2].field ||
           g->table[1].field == g->table[2].field);
}


@@ 555,10 562,6 @@ void handle_quit(int score) {
}

void game_main() {
  long seed;
  time(&seed);
  srand(seed);

  char header[] = "                        _ _ \n"
                  "   ___  __ _ _   _  ___| | |\n"
                  "  / __|/ _` | | | |/ _ \\ | |\n"


@@ 587,6 590,12 @@ void game_main() {

  struct Game game = {0};

  {
    long seed;
    time(&seed);
    srand48_r(seed, &game.prng_state);
  }

  game.state = CHOOSING_PIECE;

  fill_table(&game);