-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontroller.cpp
113 lines (108 loc) · 3.24 KB
/
controller.cpp
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
#include "controller.h"
#include <map>
using namespace std;
Controller::Controller() {
model = new Model(20,10);
view = new View("Tetris", 1024, 768);
scoresfile.open("highscores.txt", ios::app);
fileFailedOpen = false;
paused = false;
started = false;
if (scoresfile.fail()) {
cout << "Outputfile failed to open." << endl;
fileFailedOpen = true;
}
// Decrease the update time interval to make game faster
milliSeconds = 250;
}
Controller::~Controller() {
delete model;
delete view;
scoresfile.close();
}
/*
References:
https://wiki.libsdl.org/SDL_PollEvent
https://wiki.libsdl.org/SDL_Event
*/
void Controller::loop() {
SDL_Event e;
unsigned int lastTime = 0, currentTime;
std::map<SDL_Keycode, Direction> direction;
direction[SDLK_UP] = UP;
direction[SDLK_DOWN] = DOWN;
direction[SDLK_LEFT] = LEFT;
direction[SDLK_RIGHT] = RIGHT;
while (!started) {
view->showStartScreen(model);
if (SDL_PollEvent(&e) != 0) {
switch (e.type) {
case SDL_QUIT:
return;
case SDL_KEYDOWN:
switch(e.key.keysym.sym) {
case SDLK_SPACE:
started = true;
break;
}
}
}
}
while(!model->gameOver()) {
if (paused) {
view->showPause(model);
if (SDL_PollEvent(&e) != 0) {
switch (e.type) {
case SDL_QUIT:
return;
case SDL_KEYDOWN:
switch(e.key.keysym.sym) {
case SDLK_p:
paused = false;
break;
}
}
}
} else {
currentTime = SDL_GetTicks();
// Do stuff here to animate as necessary
view->show(model);
if (currentTime > lastTime + milliSeconds) {
model->fall();
lastTime = currentTime;
}
if (SDL_PollEvent(&e) != 0) {
switch (e.type) {
case SDL_QUIT:
return;
case SDL_KEYDOWN:
switch(e.key.keysym.sym) {
case SDLK_UP:
case SDLK_DOWN:
case SDLK_LEFT:
case SDLK_RIGHT:
model->go(direction[e.key.keysym.sym]);
break;
case SDLK_p:
paused = true;
break;
case SDLK_SPACE:
model->instantFall();
break;
default:
break;
}
case SDL_MOUSEBUTTONDOWN:
break;
}
}
}
}
if (!fileFailedOpen) {
scoresfile << endl << "Rows completed: " << model->rowCount << "\t"
<< "(milli seconds between Tetrominoes: " << milliSeconds << ")" << endl;
}
// TODO: show something nice?
view->showGameOver(model);
SDL_Delay(5000);
}