-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathOneLoneCoder_Tetris.PGE.cpp
333 lines (273 loc) · 10.6 KB
/
OneLoneCoder_Tetris.PGE.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
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
/*
OneLoneCoder.com - Command Line Tetris
"Put Your Money Where Your Mouth Is" - @Javidx9
License
~~~~~~~
Copyright (C) 2018 Javidx9
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions; See license for details.
Original works located at:
https://www.github.com/onelonecoder
https://www.onelonecoder.com
https://www.youtube.com/javidx9
GNU GPLv3
https://github.com/OneLoneCoder/videos/blob/master/LICENSE
From Javidx9 :)
~~~~~~~~~~~~~~~
Hello! Ultimately I don't care what you use this for. It's intended to be
educational, and perhaps to the oddly minded - a little bit of fun.
Please hack this, change it and use it in any way you see fit. You acknowledge
that I am not responsible for anything bad that happens as a result of
your actions. However this code is protected by GNU GPLv3, see the license in the
github repo. This means you must attribute me if you use it. You can view this
license here: https://github.com/OneLoneCoder/videos/blob/master/LICENSE
Cheers!
Background
~~~~~~~~~~
I made a video "8-Bits of advice for new programmers" (https://youtu.be/vVRCJ52g5m4)
and suggested that building a tetris clone instead of Dark Sould IV might be a better
approach to learning to code. Tetris is nice as it makes you think about algorithms.
Controls are Arrow keys Left, Right & Down. Use Z to rotate the piece.
You score 25pts per tetronimo, and 2^(number of lines)*100 when you get lines.
Future Modifications
~~~~~~~~~~~~~~~~~~~~
1) Show next block and line counter
Author
~~~~~~
Twitter: @javidx9
Blog: www.onelonecoder.com
Video:
~~~~~~
https://youtu.be/8OK8_tHeCIA
Last Updated: 30/03/2017
*/
/* Alterations to original (console) code - Joseph21 - 2022-08-16
* - removed "using namespace std" and added explicit scope resolution operator where needed
* - added "using namespace std::chrono_literals to resolve errors on ms literal
* Port to ConsoleGameEngine - 2022-08-16
* - removed a number of include directives since they are already done in olcConsoleGameEngine.h
* - Created a class Tetris_CGE and put most of the before global variables in it as class variables
* - Added OnUserCreate() and put tetromino initialization in it
* - Added OnUserUpdate() and put all user interaction in it (calls to GetAsyncKeyState() rewritten
* to calls to GetKey(), applied in a little lambda key_touched())
* - Replaced the call to swprintf_s() with DrawString() call with the same (score) information
* - Replaced all references to screen[] with calls to Draw()
* - Rewrote main() to construct and start the console game engine
* Port to PixelGameEngine - 2022-08-16
* - standard porting stuff - see cheat sheet for generic adaptations needed for port
* - Introduced a lambda CGE_Draw() to emulate the Draw() of one glyph CGE style
* - Adapted screen resolution
*/
#include <thread>
using namespace std::chrono_literals;
#define OLC_PGE_APPLICATION
#include "olcPixelGameEngine.h"
#define PIX_X 2
#define PIX_Y 2
int nScreenWidth = 80; // Screen Size X (columns)
int nScreenHeight = 30; // Screen Size Y (rows)
int nScore = 0;
class Tetris_PGE : public olc::PixelGameEngine {
public:
Tetris_PGE() {
sAppName = "Tetris_PGE";
}
private:
std::string tetromino[7]; // for storing tetris objects
int nFieldWidth = 12; // dimensions of playing field
int nFieldHeight = 18;
unsigned char *pField = nullptr; // pointer to dyn. alloc.d playing field
int Rotate(int px, int py, int r)
{
int pi = 0;
switch (r % 4)
{
case 0: // 0 degrees // 0 1 2 3
pi = py * 4 + px; // 4 5 6 7
break; // 8 9 10 11
//12 13 14 15
case 1: // 90 degrees //12 8 4 0
pi = 12 + py - (px * 4); //13 9 5 1
break; //14 10 6 2
//15 11 7 3
case 2: // 180 degrees //15 14 13 12
pi = 15 - (py * 4) - px; //11 10 9 8
break; // 7 6 5 4
// 3 2 1 0
case 3: // 270 degrees // 3 7 11 15
pi = 3 - py + (px * 4); // 2 6 10 14
break; // 1 5 9 13
} // 0 4 8 12
return pi;
}
bool DoesPieceFit(int nTetromino, int nRotation, int nPosX, int nPosY)
{
// All Field cells >0 are occupied
for (int px = 0; px < 4; px++)
for (int py = 0; py < 4; py++)
{
// Get index into piece
int pi = Rotate(px, py, nRotation);
// Get index into field
int fi = (nPosY + py) * nFieldWidth + (nPosX + px);
// Check that test is in bounds. Note out of bounds does
// not necessarily mean a fail, as the long vertical piece
// can have cells that lie outside the boundary, so we'll
// just ignore them
if (nPosX + px >= 0 && nPosX + px < nFieldWidth)
{
if (nPosY + py >= 0 && nPosY + py < nFieldHeight)
{
// In Bounds so do collision check
if (tetromino[nTetromino][pi] != '.' && pField[fi] != 0)
return false; // fail on first hit
}
}
}
return true;
}
int nCurrentPiece = 0;
int nCurrentRotation = 0;
int nCurrentX = nFieldWidth / 2;
int nCurrentY = 0;
int nSpeed = 20;
int nSpeedCount = 0;
bool bForceDown = false;
bool bRotateHold = true;
int nPieceCount = 0;
std::vector<int> vLines;
bool bGameOver = false;
protected:
virtual bool OnUserCreate()
{
tetromino[0].append("..X...X...X...X."); // Tetronimos 4x4
tetromino[1].append("..X..XX...X.....");
tetromino[2].append(".....XX..XX.....");
tetromino[3].append("..X..XX..X......");
tetromino[4].append(".X...XX...X.....");
tetromino[5].append(".X...X...XX.....");
tetromino[6].append("..X...X..XX.....");
pField = new unsigned char[nFieldWidth*nFieldHeight]; // Create play field buffer
for (int x = 0; x < nFieldWidth; x++) // Board Boundary
for (int y = 0; y < nFieldHeight; y++)
pField[y*nFieldWidth + x] = (x == 0 || x == nFieldWidth - 1 || y == nFieldHeight - 1) ? 9 : 0;
return true;
}
virtual bool OnUserUpdate( float fElapsedTime )
{
// Timing =======================
std::this_thread::sleep_for(50ms); // Small Step = 1 Game Tick
nSpeedCount++;
bForceDown = (nSpeedCount == nSpeed);
// Input ========================
auto key_touched = [=]( olc::Key nKey ) {
return (GetKey( nKey ).bPressed || GetKey( nKey ).bHeld);
};
// Handle player movement
if (key_touched( olc::Key::RIGHT ) && DoesPieceFit(nCurrentPiece, nCurrentRotation, nCurrentX + 1, nCurrentY )) {
nCurrentX = nCurrentX + 1;
}
if (key_touched( olc::Key::LEFT ) && DoesPieceFit(nCurrentPiece, nCurrentRotation, nCurrentX - 1, nCurrentY )) {
nCurrentX = nCurrentX - 1;
}
if (key_touched( olc::Key::DOWN ) && DoesPieceFit(nCurrentPiece, nCurrentRotation, nCurrentX, nCurrentY + 1 )) {
nCurrentY = nCurrentY + 1;
}
// Rotate, but latch to stop wild spinning
if (key_touched( olc::Key::Z ))
{
nCurrentRotation += (bRotateHold && DoesPieceFit(nCurrentPiece, nCurrentRotation + 1, nCurrentX, nCurrentY)) ? 1 : 0;
bRotateHold = false;
}
else
bRotateHold = true;
// Game Logic ===================
// Force the piece down the playfield if it's time
if (bForceDown)
{
// Update difficulty every 50 pieces
nSpeedCount = 0;
nPieceCount++;
if (nPieceCount % 50 == 0)
if (nSpeed >= 10) nSpeed--;
// Test if piece can be moved down
if (DoesPieceFit(nCurrentPiece, nCurrentRotation, nCurrentX, nCurrentY + 1))
nCurrentY++; // It can, so do it!
else
{
// It can't! Lock the piece in place
for (int px = 0; px < 4; px++)
for (int py = 0; py < 4; py++)
if (tetromino[nCurrentPiece][Rotate(px, py, nCurrentRotation)] != '.')
pField[(nCurrentY + py) * nFieldWidth + (nCurrentX + px)] = nCurrentPiece + 1;
// Check for lines
for (int py = 0; py < 4; py++)
if(nCurrentY + py < nFieldHeight - 1)
{
bool bLine = true;
for (int px = 1; px < nFieldWidth - 1; px++)
bLine &= (pField[(nCurrentY + py) * nFieldWidth + px]) != 0;
if (bLine)
{
// Remove Line, set to =
for (int px = 1; px < nFieldWidth - 1; px++)
pField[(nCurrentY + py) * nFieldWidth + px] = 8;
vLines.push_back(nCurrentY + py);
}
}
nScore += 25;
if(!vLines.empty()) nScore += (1 << vLines.size()) * 100;
// Pick New Piece
nCurrentX = nFieldWidth / 2;
nCurrentY = 0;
nCurrentRotation = 0;
nCurrentPiece = rand() % 7;
// If piece does not fit straight away, game over!
bGameOver = !DoesPieceFit(nCurrentPiece, nCurrentRotation, nCurrentX, nCurrentY);
}
}
// Display ======================
Clear( olc::BLACK );
// little lambda to emulate CGE's Draw() call
auto CGE_Draw = [=]( int x, int y, char c ) {
DrawString( x * 8, y * 8, std::string( 1, c ));
};
// Draw Field
for (int x = 0; x < nFieldWidth; x++)
for (int y = 0; y < nFieldHeight; y++)
CGE_Draw( x + 2, y + 2, " ABCDEFG=#"[pField[y*nFieldWidth + x]] );
// Draw Current Piece
for (int px = 0; px < 4; px++)
for (int py = 0; py < 4; py++)
if (tetromino[nCurrentPiece][Rotate(px, py, nCurrentRotation)] != '.')
CGE_Draw( nCurrentX + px + 2, nCurrentY + py + 2, nCurrentPiece + 65 );
// Draw Score
std::string sScore = "SCORE: " + std::to_string( nScore );
DrawString( (nFieldWidth + 6) * 8, 2 * 8, sScore );
// Animate Line Completion
if (!vLines.empty())
{
for (auto &v : vLines)
for (int px = 1; px < nFieldWidth - 1; px++)
{
for (int py = v; py > 0; py--)
pField[py * nFieldWidth + px] = pField[(py - 1) * nFieldWidth + px];
pField[px] = 0;
}
vLines.clear();
}
return !bGameOver;
}
};
int main()
{
// use olcConsoleGameEngine derived app
Tetris_PGE game;
game.Construct( nScreenWidth * 8, nScreenHeight * 8, PIX_X, PIX_Y );
game.Start();
// Oh Dear - game over!
std::cout << "Game over!! Score: " << nScore << std::endl;
system("pause");
return 0;
}