back to scratko.xyz
aboutsummaryrefslogtreecommitdiff
path: root/gameplay.cpp
blob: 0c6a1ab63372432839762f68399a2e2d7d21b31f (plain)
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
#include "gameplay.hpp"
#include "puzzle.hpp"
#include <FL/Fl_Group.H>
#include <FL/fl_ask.H>

#include <algorithm>
#include <memory>
#include <vector>

static bool is_next_to_empty_box(GameParams::coordinates empty_box_pos,
                                 GameParams::coordinates current_pos)
{
    return
        (current_pos.x - spacing - puzzle_size == empty_box_pos.x &&
         current_pos.y == empty_box_pos.y) ||
        (current_pos.x == empty_box_pos.x &&
         current_pos.y - spacing - puzzle_size == empty_box_pos.y) ||
        (current_pos.x + puzzle_size + spacing == empty_box_pos.x &&
         current_pos.y == empty_box_pos.y) ||
        (current_pos.x == empty_box_pos.x &&
         current_pos.y + puzzle_size + spacing == empty_box_pos.y);
}

static bool is_coordinate_match(GameParams::coordinates& first,
                                GameParams::coordinates& second)
{
    return first.x == second.x && first.y == second.y;
}

bool PuzzleGame::IsFinalPlacement(GameParams *gp)
{
    bool is_match = 1;
    auto lambda = [gp, &is_match](std::unique_ptr<Puzzle>& next_puzzle) {
        GameParams::coordinates pos_next_puzzle =
                                        { next_puzzle->x(), next_puzzle->y() };
        GameParams::coordinates target_pos =
                gp->standard_puzzle_coordinates[next_puzzle->sequence_number];
        if(!is_coordinate_match(pos_next_puzzle, target_pos))
            is_match = 0;
    };
    std::for_each(gp->puzzles.begin(), gp->puzzles.end(), lambda);
    return is_match;
}

void press_button_callback(Fl_Widget *w, void *params)
{
    GameParams *gp = reinterpret_cast<GameParams*>(params);
    GameParams::coordinates current_pos = { w->x(), w->y() };
    if(is_next_to_empty_box(gp->GetXYEmptyBox(), current_pos)) {
        w->position(gp->GetXYEmptyBox().x, gp->GetXYEmptyBox().y);
        gp->SetXYEmptyBox(current_pos.x, current_pos.y);
    }
    w->parent()->redraw();
    if(PuzzleGame::IsFinalPlacement(gp)) {
        int answer = fl_choice("You win. Play again?", "No", "Yes", nullptr);
        if(answer)
            PuzzleGame::StartGame(gp);
        else
            gp->win->hide();
    }
}

void PuzzleGame::StartGame(GameParams *gp)
{
    gp->ResetFreePuzzles();
    gp->CreateNewPuzzles();
    gp->win->redraw();
}