summary refs log tree commit diff stats
path: root/gamestate.cpp
blob: 953d35b3aacac4587eee1d4f08f93c9e9049b7ea (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
#include "gamestate.h"

#include <SDL_ttf.h>

#include <algorithm>
#include <bitset>
#include <deque>
#include <fstream>
#include <iostream>
#include <list>
#include <memory>
#include <random>
#include <set>
#include <sstream>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>

#include "highscore.h"
#include "hs_state.h"
#include "hslist.h"
#include "mazeoflife.h"
#include "titlestate.h"
#include "util.h"

using board_type = std::bitset<WIDTH * HEIGHT>;

void setRendererAliveColor(SDL_Renderer* renderer, int level) {
  switch ((level / 10) % 5) {
    case 0:
      SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
      break;  // Black
    case 1:
      SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
      break;  // Red
    case 2:
      SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
      break;  // Green
    case 3:
      SDL_SetRenderDrawColor(renderer, 85, 85, 85, 255);
      break;  // Dark Gray
    case 4:
      SDL_SetRenderDrawColor(renderer, 255, 0, 255, 255);
      break;  // Magenta
  }
}

void setRendererDeadColor(SDL_Renderer* renderer, int level) {
  switch ((level / 10) % 5) {
    case 0:
      SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
      break;  // White
    case 1:
      SDL_SetRenderDrawColor(renderer, 255, 192, 203, 255);
      break;  // Pink
    case 2:
      SDL_SetRenderDrawColor(renderer, 0, 255, 255, 255);
      break;  // Cyan
    case 3:
      SDL_SetRenderDrawColor(renderer, 170, 170, 170, 255);
      break;  // Light Gray
    case 4:
      SDL_SetRenderDrawColor(renderer, 255, 128, 0, 255);
      break;  // Orange
  }
}

void incrementIfNeighbor(int x, int y, const board_type& temp, int playerx,
                         int playery, int& tick) {
  int nx = x;
  int ny = y;

  wrap(x, y);

  if (!((nx != x) && (ny != y))) {
    if ((temp[x + y * WIDTH]) || ((playerx == x) && (playery == y)) ||
        ((x == 15) && (y == 15))) {
      ++tick;
    }
  }
}

bool applyNeighbors(int x, int y, const board_type& temp, int playerx,
                    int playery) {
  int neighbors = 0;

  incrementIfNeighbor(x - 1, y - 1, temp, playerx, playery, neighbors);
  incrementIfNeighbor(x - 1, y, temp, playerx, playery, neighbors);
  incrementIfNeighbor(x - 1, y + 1, temp, playerx, playery, neighbors);
  incrementIfNeighbor(x, y - 1, temp, playerx, playery, neighbors);
  incrementIfNeighbor(x, y + 1, temp, playerx, playery, neighbors);
  incrementIfNeighbor(x + 1, y - 1, temp, playerx, playery, neighbors);
  incrementIfNeighbor(x + 1, y, temp, playerx, playery, neighbors);
  incrementIfNeighbor(x + 1, y + 1, temp, playerx, playery, neighbors);

  if (temp[x + y * WIDTH]) {
    return ((neighbors >= 1) && (neighbors <= 4));
  } else {
    return (neighbors == 3);
  }
}

class GameBoard {
 public:
  GameBoard(Game& game, int level, int playerx, int playery) {
    for (;;) {
      initialize(game, level);
      updateable_.set();
      oldx_ = playerx;
      oldy_ = playery;

      for (int i = 0; i < 50; i++) {
        tick(playerx, playery);
      }

      if (solve(playerx, playery)) {
        break;
      } else {
        std::cout << "Impossible board: " << playerx << "," << playery << ","
                  << dump() << std::endl;
      }
    }
  }

  void tick(int playerx, int playery) {
    board_type temp{blocks_};
    board_type tempdateable{updateable_};
    if ((playerx != oldx_) || (playery != oldy_)) {
      for (int dy = -1; dy <= 1; dy++) {
        for (int dx = -1; dx <= 1; dx++) {
          int tdx = oldx_ + dx;
          int tdy = oldy_ + dy;
          wrap(tdx, tdy);
          tempdateable.set(tdx + tdy * WIDTH);

          tdx = playerx + dx;
          tdy = playery + dy;
          wrap(tdx, tdy);
          tempdateable.set(tdx + tdy * WIDTH);
        }
      }
    }

    oldx_ = playerx;
    oldy_ = playery;

    updateable_.reset();

    for (int y = 0; y < HEIGHT; y++) {
      for (int x = 0; x < WIDTH; x++) {
        if (((x == 15) && (y == 15)) || (!tempdateable[x + y * WIDTH])) {
          continue;
        }

        blocks_[x + y * WIDTH] = applyNeighbors(x, y, temp, playerx, playery);

        if (temp[x + y * WIDTH] != blocks_[x + y * WIDTH]) {
          for (int dy = -1; dy <= 1; dy++) {
            for (int dx = -1; dx <= 1; dx++) {
              int tdx = x + dx;
              int tdy = y + dy;
              wrap(tdx, tdy);
              updateable_.set(tdx + tdy * WIDTH);
            }
          }
        }
      }
    }
  }

  void render(SDL_Renderer* renderer, int level) const {
    SDL_Rect block;
    block.w = 16;
    block.h = 16;

    for (int y = 0; y < HEIGHT; y++) {
      for (int x = 0; x < WIDTH; x++) {
        block.x = x * 16;
        block.y = y * 16;

        if (blocks_[x + y * WIDTH]) {
          setRendererAliveColor(renderer, level);
        } else {
          setRendererDeadColor(renderer, level);
        }

        SDL_RenderFillRect(renderer, &block);
      }
    }
  }

  bool isObstructed(int x, int y) const {
    return blocks_[x + y * WIDTH] || (x == 15 && y == 15);
  }

  bool operator<(const GameBoard& other) const {
    for (int i = WIDTH * HEIGHT - 1; i >= 0; i--) {
      if (blocks_[i] ^ other.blocks_[i]) {
        return other.blocks_[i];
      }
    }

    return false;
  }

  using coord = std::tuple<int, int>;

 private:
  void initialize(Game& game, int level) {
    for (int y = 0; y < HEIGHT; y++) {
      for (int x = 0; x < WIDTH; x++) {
        blocks_[x + y * WIDTH] = false;

        switch (level / 10 + 1) {
          case 1:
            if ((x > 13) && (x < 17) && (y > 13) && (y < 17)) {
              blocks_[x + y * WIDTH] =
                  std::bernoulli_distribution(0.5)(game.rng);
            }
            break;
          case 2:
          case 3:
            if ((x > 12) && (x < 18) && (y > 12) && (y < 18)) {
              blocks_[x + y * WIDTH] =
                  std::bernoulli_distribution(0.5)(game.rng);
            }
            break;
          case 4:
          case 5:
            if ((x > 11) && (x < 19) && (y > 11) && (y < 19)) {
              blocks_[x + y * WIDTH] =
                  std::bernoulli_distribution(0.5)(game.rng);
            }
            break;
          default:
            blocks_[x + y * WIDTH] = std::bernoulli_distribution(0.5)(game.rng);
        }
      }
    }

    blocks_[15 + 15 * WIDTH] = false;
  }

  bool solve(int playerx, int playery) const {
    std::deque<std::tuple<GameBoard, coord, int>> search;
    std::unordered_map<board_type, board_type> done;

    // Assume that the player will not move while the board is changing, so tick
    // the board until it either stops changing, or it reaches a state that it
    // has already been in (in the case of alternating systems).
    {
      GameBoard original = *this;

      std::unordered_set<board_type> pastStates;
      pastStates.insert(original.blocks_);

      while (original.updateable_.any()) {
        original.tick(playerx, playery);

        if (pastStates.count(original.blocks_)) {
          break;
        }

        pastStates.insert(original.blocks_);
      }

      search.emplace_front(std::move(original), coord{playerx, playery}, 0);
    }

    // Use breadth first search to find a solution.
    bool exists = false;
    while (!search.empty()) {
      auto cur = std::move(search.front());
      search.pop_front();

      GameBoard& cbr = std::get<0>(cur);
      coord& cpl = std::get<1>(cur);
      int cns = std::get<2>(cur);

      // If it has been over 100 generations, give up.
      if (cns > 100) {
        continue;
      }

      int cplx = std::get<0>(cpl);
      int cply = std::get<1>(cpl);

      // If this section of this board state has already been checked, skip it.
      if (done.count(cbr.blocks_) &&
          done.at(cbr.blocks_)[cplx + cply * WIDTH]) {
        continue;
      }

      // Use a flood fill to find a set of positions accessible to the player
      // without modifying the board state, as well as a set of positions
      // adjacent to the flood that /will/ modify the board state.
      board_type flood;
      std::deque<coord> front;
      front.push_front(cpl);
      flood[cplx + cply * WIDTH] = true;

      std::set<coord> edges;

      while (!front.empty()) {
        coord frontLoc = std::move(front.front());
        front.pop_front();

        // Iterate over the positions 4-adjacent to the current one.
        for (coord& fc : std::list<coord>{
                 {std::get<0>(frontLoc) - 1, std::get<1>(frontLoc)},
                 {std::get<0>(frontLoc) + 1, std::get<1>(frontLoc)},
                 {std::get<0>(frontLoc), std::get<1>(frontLoc) - 1},
                 {std::get<0>(frontLoc), std::get<1>(frontLoc) + 1},
             }) {
          wrap(std::get<0>(fc), std::get<1>(fc));
          int fcx = std::get<0>(fc);
          int fcy = std::get<1>(fc);

          // If this position is already in the flood, skip it.
          if (flood[fcx + fcy * WIDTH]) {
            continue;
          }

          // If the player could not move into this position, skip it.
          if (cbr.isObstructed(fcx, fcy)) {
            continue;
          }

          // If this position is adjacent to the event, then the board is
          // solvable.
          if (((fcx == 15) && ((fcy == 14) || (fcy == 16))) ||
              ((fcy == 15) && ((fcx == 14) || (fcx == 16)))) {
            exists = true;
            break;
          }

          // Check if the player moving would cause any positions 8-adjacent to
          // the start or end positions to change. This is more efficient than
          // copying the board state and then running tick.
          bool changed = false;
          for (int dy = -1; dy <= 1; dy++) {
            for (int dx = -1; dx <= 1; dx++) {
              if (dx == 0 && dy == 0) {
                continue;
              }

              int cpldx = cplx + dx;
              int cpldy = cply + dy;
              wrap(cpldx, cpldy);

              if (cbr.isObstructed(cpldx, cpldy) !=
                  applyNeighbors(cpldx, cpldy, cbr.blocks_, fcx, fcy)) {
                changed = true;
                break;
              }

              int fcxdx = fcx + dx;
              int fcydy = fcy + dy;
              wrap(fcxdx, fcydy);

              if (cbr.isObstructed(fcxdx, fcydy) !=
                  applyNeighbors(fcxdx, fcydy, cbr.blocks_, fcx, fcy)) {
                changed = true;
                break;
              }
            }

            if (changed) {
              break;
            }
          }

          // If moving to this position would change the board state, add it to
          // the set of edges; otherwise, add it to the flood and the flood
          // front.
          if (changed) {
            edges.insert(fc);
          } else {
            flood[fcx + fcy * WIDTH] = true;
            front.push_back(fc);
          }
        }

        if (exists) {
          break;
        }
      }

      if (exists) {
        break;
      }

      // Add the flood to the set of checked positions for this board state.
      done[cbr.blocks_] |= flood;

      // Add the edges to the search queue.
      for (const coord& newLoc : edges) {
        GameBoard nextState1 = cbr;
        nextState1.tick(std::get<0>(newLoc), std::get<1>(newLoc));

        // Assume that the player will not move while the board is changing, so
        // tick the board until it either stops changing, or it reaches a state
        // that it has already been in (in the case of alternating systems).
        std::unordered_set<board_type> pastStates;
        pastStates.insert(nextState1.blocks_);

        while (nextState1.updateable_.any()) {
          nextState1.tick(std::get<0>(newLoc), std::get<1>(newLoc));

          if (pastStates.count(nextState1.blocks_)) {
            break;
          }

          pastStates.insert(nextState1.blocks_);
        }

        if (!done.count(nextState1.blocks_) ||
            !done.at(nextState1.blocks_)[std::get<0>(newLoc) +
                                         std::get<1>(newLoc) * WIDTH]) {
          search.emplace_back(std::move(nextState1), newLoc, cns + 1);
        }
      }
    }

    return exists;
  }

  std::string dump() const {
    std::stringstream output;
    output << std::hex;
    for (int i = 0; i < WIDTH * HEIGHT / 4; i++) {
      int chunk = (8 * blocks_[i * 4]) + (4 * blocks_[i * 4 + 1]) +
                  (2 * blocks_[i * 4 + 2]) + blocks_[i * 4 + 3];
      output << chunk;
    }

    return output.str();
  }

  board_type blocks_;
  board_type updateable_;
  int oldx_;
  int oldy_;
};

std::unique_ptr<State> startNewLevel(int level,
                                     std::unique_ptr<GameBoard> board,
                                     int playerx, int playery);

class LoadGameState : public State {
 public:
  LoadGameState(int level) : level_(level) {}

  std::unique_ptr<State> operator()(Game& game) {
    std::ostringstream wintitle;
    wintitle << "Maze Of Life - Level " << level_;
    SDL_SetWindowTitle(game.window.get(), wintitle.str().c_str());

    // Randomly place the player in a corner
    int playerx, playery;
    switch (std::uniform_int_distribution(0, 3)(game.rng)) {
      case 0: {
        playerx = 1;
        playery = 1;
        break;
      }
      case 1: {
        playerx = 1;
        playery = HEIGHT - 2;
        break;
      }
      case 2: {
        playerx = WIDTH - 2;
        playery = HEIGHT - 2;
        break;
      }
      case 3: {
        playerx = WIDTH - 2;
        playery = 1;
        break;
      }
    }

    // Display the level number
    setRendererDeadColor(game.renderer.get(), level_);
    SDL_RenderClear(game.renderer.get());

    font_ptr font = loadFont(100);
    SDL_Color fontColor = {0, 0, 0, 0};
    std::string levelnum = std::to_string(level_);
    surface_ptr dispsurf = surface_ptr(
        TTF_RenderText_Solid(font.get(), levelnum.c_str(), fontColor));
    texture_ptr disptext = texture_ptr(
        SDL_CreateTextureFromSurface(game.renderer.get(), dispsurf.get()));

    SDL_Rect pos;
    SDL_QueryTexture(disptext.get(), NULL, NULL, &pos.w, &pos.h);
    pos.x = 240 - (pos.w / 2);
    pos.y = 240 - (pos.h / 2);

    SDL_RenderCopy(game.renderer.get(), disptext.get(), NULL, &pos);
    SDL_RenderPresent(game.renderer.get());

    // Do 50 gens of Conway
    std::unique_ptr<GameBoard> board =
        std::make_unique<GameBoard>(game, level_, playerx, playery);

    // Wait a bit
    SDL_Delay(500);

    // Start the level
    return startNewLevel(level_, std::move(board), playerx, playery);
  }

 private:
  int level_;
};

class PlayGameState : public State {
 public:
  PlayGameState(int level, std::unique_ptr<GameBoard> board, int playerx,
                int playery)
      : level_(level),
        board_(std::move(board)),
        playerx_(playerx),
        playery_(playery) {}

  std::unique_ptr<State> operator()(Game& game) {
    SDL_Event e;

    // Tick board
    board_->tick(playerx_, playery_);

    // Paint board
    board_->render(game.renderer.get(), level_);

    // Paint event
    SDL_Rect block;
    block.w = 16;
    block.h = 16;
    block.x = 15 * 16;
    block.y = 15 * 16;
    SDL_SetRenderDrawColor(game.renderer.get(), 0, 0, 255, 255);
    SDL_RenderFillRect(game.renderer.get(), &block);

    // Paint player
    block.x = playerx_ * 16;
    block.y = playery_ * 16;
    SDL_SetRenderDrawColor(game.renderer.get(), 255, 255, 0, 255);
    SDL_RenderFillRect(game.renderer.get(), &block);

    SDL_RenderPresent(game.renderer.get());

    while (SDL_PollEvent(&e)) {
      if (e.type == SDL_QUIT) {
        game.should_quit = true;

        return nullptr;
      } else if (e.type == SDL_KEYDOWN) {
        bool trymove = false;
        int to_x = playerx_;
        int to_y = playery_;

        switch (e.key.keysym.sym) {
          case SDLK_LEFT: {
            trymove = true;
            to_x--;
            break;
          }
          case SDLK_RIGHT: {
            trymove = true;
            to_x++;
            break;
          }
          case SDLK_UP: {
            trymove = true;
            to_y--;
            break;
          }
          case SDLK_DOWN: {
            trymove = true;
            to_y++;
            break;
          }
          case SDLK_ESCAPE: {
            SDL_SetWindowTitle(game.window.get(), "");

            std::unique_ptr<HighscoreList> hslist =
                HighscoreList::GetLocalHighscores();
            if (hslist->addHighscore(Highscore("", level_)) <= 10) {
              return std::make_unique<EnterHighscoreState>(game, level_);
            } else {
              return std::make_unique<DisplayAndReturnLocalHighscoreListState>(
                  game);
            }

            break;
          }
        }

        if (trymove && move(to_x, to_y)) {
          return std::make_unique<LoadGameState>(level_ + 1);
        }
      }
    }

    SDL_Delay(5);

    return nullptr;
  }

 private:
  bool move(int x, int y) {
    wrap(x, y);

    // Are we at the event?
    if ((x == 15) && (y == 15)) {
      return true;
    }

    // Can we even go there?
    if (!board_->isObstructed(x, y)) {
      playerx_ = x;
      playery_ = y;
    }

    return false;
  }

  int level_;
  std::unique_ptr<GameBoard> board_;
  int playerx_;
  int playery_;
};

std::unique_ptr<State> startNewLevel(int level,
                                     std::unique_ptr<GameBoard> board,
                                     int playerx, int playery) {
  return std::make_unique<PlayGameState>(level, std::move(board), playerx,
                                         playery);
}

std::unique_ptr<State> GameState::operator()(Game&) {
  return std::make_unique<LoadGameState>(0);
}