-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
629 lines (545 loc) · 17.5 KB
/
Copy pathmain.cpp
File metadata and controls
629 lines (545 loc) · 17.5 KB
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
#include "Board.h"
#include "Tetromino.h"
#include "Bot.h"
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
const int WINDOW_WIDTH = 500;
const int WINDOW_HEIGHT = 700;
class Game {
public:
Game();
~Game();
bool init();
void run();
void shutdown();
void setBotMode(bool enabled, int maxTurns = 100, int delayMs = 0);
bool botCompletedSuccessfully() const { return m_botCompletedSuccessfully; }
private:
SDL_Window* m_window;
SDL_Renderer* m_renderer;
TTF_Font* m_font;
Board m_board;
Tetromino m_currentPiece;
Tetromino m_nextPiece;
int m_score;
int m_level;
int m_lines;
bool m_gameOver;
bool m_paused;
bool m_botMode;
int m_botTurns;
int m_maxBotTurns;
int m_botDelay;
bool m_botCompletedSuccessfully;
Bot m_bot;
Uint32 m_lastDropTime;
Uint32 m_dropInterval;
void handleEvents();
void update();
void draw();
void drawText(const char* text, int x, int y, SDL_Color color);
void spawnPiece();
void hardDrop();
void resetGame();
void executeBotMove();
};
Game::Game()
: m_window(nullptr)
, m_renderer(nullptr)
, m_font(nullptr)
, m_currentPiece(TetrominoType::I)
, m_nextPiece(TetrominoType::I)
, m_score(0)
, m_level(1)
, m_lines(0)
, m_gameOver(false)
, m_paused(false)
, m_botMode(false)
, m_botTurns(0)
, m_maxBotTurns(100)
, m_botDelay(0)
, m_botCompletedSuccessfully(false)
, m_lastDropTime(0)
, m_dropInterval(500)
{
srand(static_cast<unsigned>(time(nullptr)));
}
Game::~Game() {
shutdown();
}
bool Game::init() {
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
return false;
}
if (TTF_Init() < 0) {
fprintf(stderr, "TTF_Init failed: %s\n", TTF_GetError());
return false;
}
m_window = SDL_CreateWindow(
"Tetris",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
WINDOW_WIDTH,
WINDOW_HEIGHT,
SDL_WINDOW_SHOWN
);
if (!m_window) {
fprintf(stderr, "SDL_CreateWindow failed: %s\n", SDL_GetError());
return false;
}
m_renderer = SDL_CreateRenderer(
m_window,
-1,
SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC
);
if (!m_renderer) {
fprintf(stderr, "SDL_CreateRenderer failed: %s\n", SDL_GetError());
return false;
}
m_font = TTF_OpenFont("/System/Library/Fonts/Supplemental/Arial.ttf", 18);
if (!m_font) {
m_font = TTF_OpenFont("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 18);
}
if (!m_font) {
fprintf(stderr, "TTF_OpenFont failed: %s\n", TTF_GetError());
return false;
}
resetGame();
return true;
}
void Game::resetGame() {
m_board.reset();
m_score = 0;
m_level = 1;
m_lines = 0;
m_gameOver = false;
m_paused = false;
m_dropInterval = 500;
m_lastDropTime = SDL_GetTicks();
spawnPiece();
m_nextPiece.setType(Tetromino::randomType());
}
void Game::spawnPiece() {
m_currentPiece = m_nextPiece;
m_nextPiece.setType(Tetromino::randomType());
if (!m_board.isValidMove(m_currentPiece, 0, 0)) {
m_gameOver = true;
}
}
void Game::hardDrop() {
while (m_board.isValidMove(m_currentPiece, 0, 1)) {
m_currentPiece.move(0, 1);
m_score += 2;
}
m_board.placeTetromino(m_currentPiece);
int cleared = m_board.clearLines();
if (cleared > 0) {
m_lines += cleared;
m_score += cleared * cleared * 100;
m_level = 1 + m_lines / 10;
m_dropInterval = 500 - (m_level - 1) * 50;
if (m_dropInterval < 100) m_dropInterval = 100;
}
spawnPiece();
}
void Game::setBotMode(bool enabled, int maxTurns, int delayMs) {
m_botMode = enabled;
m_maxBotTurns = maxTurns;
m_botDelay = delayMs;
m_botTurns = 0;
m_botCompletedSuccessfully = false;
}
void Game::executeBotMove() {
if (!m_botMode) return;
// Check if we've already completed the target turns (set success even if game over)
if (m_botTurns >= m_maxBotTurns && !m_botCompletedSuccessfully) {
printf("Bot completed %d turns. Final score: %d, Lines: %d\n",
m_botTurns, m_score, m_lines);
m_botCompletedSuccessfully = true;
m_gameOver = true;
m_paused = true;
return;
}
// If game over, don't continue
if (m_gameOver) return;
// Find the best move using lookahead with the next piece
Move bestMove = m_bot.findBestMoveWithLookahead(m_board, m_currentPiece, m_nextPiece);
// Apply rotations
for (int i = 0; i < bestMove.rotations; ++i) {
Tetromino rotated = m_currentPiece;
rotated.rotate();
if (m_board.isValidRotation(rotated)) {
m_currentPiece.rotate();
}
}
// Move to target x position
int currentX = m_currentPiece.getX();
while (currentX < bestMove.x) {
if (m_board.isValidMove(m_currentPiece, 1, 0)) {
m_currentPiece.move(1, 0);
currentX++;
} else {
break;
}
}
while (currentX > bestMove.x) {
if (m_board.isValidMove(m_currentPiece, -1, 0)) {
m_currentPiece.move(-1, 0);
currentX--;
} else {
break;
}
}
// Hard drop to place the piece
while (m_board.isValidMove(m_currentPiece, 0, 1)) {
m_currentPiece.move(0, 1);
m_score += 2;
}
// Apply delay if set (for watching the bot play)
if (m_botDelay > 0) {
SDL_Delay(m_botDelay);
}
// Place the piece
m_board.placeTetromino(m_currentPiece);
int cleared = m_board.clearLines();
if (cleared > 0) {
m_lines += cleared;
m_score += cleared * cleared * 100;
m_level = 1 + m_lines / 10;
m_dropInterval = 500 - (m_level - 1) * 50;
if (m_dropInterval < 100) m_dropInterval = 100;
}
m_botTurns++;
spawnPiece();
// Check if we just completed the target turns (check after spawn in case spawn fails)
if (m_botTurns >= m_maxBotTurns) {
printf("Bot completed %d turns. Final score: %d, Lines: %d\n",
m_botTurns, m_score, m_lines);
m_botCompletedSuccessfully = true;
m_gameOver = true;
m_paused = true;
return;
}
// Print progress every 10 turns
if (m_botTurns % 10 == 0) {
printf("Bot turn %d/%d - Score: %d, Lines: %d\n",
m_botTurns, m_maxBotTurns, m_score, m_lines);
}
}
void Game::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
m_gameOver = true;
m_paused = true;
}
if (event.type == SDL_KEYDOWN) {
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
case SDLK_q:
m_gameOver = true;
m_paused = true;
break;
case SDLK_r:
resetGame();
break;
case SDLK_p:
m_paused = !m_paused;
break;
default:
break;
}
if (!m_gameOver && !m_paused) {
switch (event.key.keysym.sym) {
case SDLK_LEFT:
if (m_board.isValidMove(m_currentPiece, -1, 0)) {
m_currentPiece.move(-1, 0);
}
break;
case SDLK_RIGHT:
if (m_board.isValidMove(m_currentPiece, 1, 0)) {
m_currentPiece.move(1, 0);
}
break;
case SDLK_DOWN:
if (m_board.isValidMove(m_currentPiece, 0, 1)) {
m_currentPiece.move(0, 1);
m_score += 1;
}
break;
case SDLK_UP:
case SDLK_x: {
Tetromino rotated = m_currentPiece;
rotated.rotate();
if (m_board.isValidRotation(rotated)) {
m_currentPiece.rotate();
}
break;
}
case SDLK_z: {
Tetromino rotated = m_currentPiece;
rotated.rotate();
rotated.rotate();
rotated.rotate();
if (m_board.isValidRotation(rotated)) {
m_currentPiece.rotate();
m_currentPiece.rotate();
m_currentPiece.rotate();
}
break;
}
case SDLK_SPACE:
hardDrop();
break;
default:
break;
}
}
}
}
}
void Game::update() {
if (m_gameOver || m_paused) return;
// In bot mode, execute moves immediately
if (m_botMode) {
executeBotMove();
m_lastDropTime = SDL_GetTicks();
return;
}
Uint32 currentTime = SDL_GetTicks();
if (currentTime - m_lastDropTime >= m_dropInterval) {
if (m_board.isValidMove(m_currentPiece, 0, 1)) {
m_currentPiece.move(0, 1);
} else {
m_board.placeTetromino(m_currentPiece);
int cleared = m_board.clearLines();
if (cleared > 0) {
m_lines += cleared;
m_score += cleared * cleared * 100;
m_level = 1 + m_lines / 10;
m_dropInterval = 500 - (m_level - 1) * 50;
if (m_dropInterval < 100) m_dropInterval = 100;
}
spawnPiece();
}
m_lastDropTime = currentTime;
}
}
void Game::drawText(const char* text, int x, int y, SDL_Color color) {
SDL_Surface* surface = TTF_RenderText_Solid(m_font, text, color);
if (surface) {
SDL_Texture* texture = SDL_CreateTextureFromSurface(m_renderer, surface);
if (texture) {
SDL_Rect dst = {x, y, surface->w, surface->h};
SDL_RenderCopy(m_renderer, texture, nullptr, &dst);
SDL_DestroyTexture(texture);
}
SDL_FreeSurface(surface);
}
}
void Game::draw() {
SDL_SetRenderDrawColor(m_renderer, 20, 20, 30, 255);
SDL_RenderClear(m_renderer);
// Draw board
m_board.draw(m_renderer);
// Draw current piece
if (!m_gameOver) {
const auto& shape = m_currentPiece.getShape();
SDL_Color color = m_currentPiece.getColor();
for (int y = 0; y < 5; ++y) {
for (int x = 0; x < 5; ++x) {
if (shape[y][x]) {
int boardX = m_currentPiece.getX() + x;
int boardY = m_currentPiece.getY() + y;
if (boardY >= 0) {
m_board.drawBlock(m_renderer, boardX, boardY, color);
}
}
}
}
}
// Draw sidebar
SDL_Color white = {255, 255, 255, 255};
SDL_Color gray = {180, 180, 180, 255};
int sidebarX = 400;
char scoreText[64];
snprintf(scoreText, sizeof(scoreText), "Score: %d", m_score);
drawText(scoreText, sidebarX, 50, white);
char levelText[64];
snprintf(levelText, sizeof(levelText), "Level: %d", m_level);
drawText(levelText, sidebarX, 80, white);
char linesText[64];
snprintf(linesText, sizeof(linesText), "Lines: %d", m_lines);
drawText(linesText, sidebarX, 110, white);
drawText("Next:", sidebarX, 160, white);
// Draw next piece preview
const auto& nextShape = m_nextPiece.getShape();
SDL_Color nextColor = m_nextPiece.getColor();
for (int y = 0; y < 5; ++y) {
for (int x = 0; x < 5; ++x) {
if (nextShape[y][x]) {
SDL_Rect block = {
sidebarX + x * 25,
190 + y * 25,
23,
23
};
SDL_SetRenderDrawColor(m_renderer, nextColor.r, nextColor.g, nextColor.b, nextColor.a);
SDL_RenderFillRect(m_renderer, &block);
}
}
}
// Controls
int controlsY = 350;
drawText("Controls:", sidebarX, controlsY, gray);
drawText("Left/Right - Move", sidebarX, controlsY + 30, gray);
drawText("Down - Soft Drop", sidebarX, controlsY + 55, gray);
drawText("Up/X - Rotate CW", sidebarX, controlsY + 80, gray);
drawText("Z - Rotate CCW", sidebarX, controlsY + 105, gray);
drawText("Space - Hard Drop", sidebarX, controlsY + 130, gray);
drawText("P - Pause", sidebarX, controlsY + 155, gray);
drawText("R - Restart", sidebarX, controlsY + 180, gray);
drawText("Q/ESC - Quit", sidebarX, controlsY + 205, gray);
if (m_gameOver) {
SDL_Rect overlay = {
0,
0,
WINDOW_WIDTH,
WINDOW_HEIGHT
};
SDL_SetRenderDrawColor(m_renderer, 0, 0, 0, 180);
SDL_RenderFillRect(m_renderer, &overlay);
SDL_Color red = {255, 50, 50, 255};
drawText("GAME OVER", 170, 300, red);
drawText("Press R to restart", 160, 340, white);
drawText("Press Q to quit", 165, 370, white);
}
if (m_paused && !m_gameOver) {
SDL_Rect overlay = {
0,
0,
WINDOW_WIDTH,
WINDOW_HEIGHT
};
SDL_SetRenderDrawColor(m_renderer, 0, 0, 0, 150);
SDL_RenderFillRect(m_renderer, &overlay);
drawText("PAUSED", 200, 320, white);
drawText("Press P to continue", 165, 360, gray);
}
SDL_RenderPresent(m_renderer);
}
void Game::run() {
while (true) {
handleEvents();
update();
// In bot mode, exit immediately on game over without drawing
if (m_botMode && m_gameOver) {
break;
}
draw();
if (m_gameOver && m_paused) {
break;
}
SDL_Delay(16);
}
}
void Game::shutdown() {
if (m_font) {
TTF_CloseFont(m_font);
m_font = nullptr;
}
if (m_renderer) {
SDL_DestroyRenderer(m_renderer);
m_renderer = nullptr;
}
if (m_window) {
SDL_DestroyWindow(m_window);
m_window = nullptr;
}
TTF_Quit();
SDL_Quit();
}
int main(int argc, char* argv[]) {
bool botMode = false;
int botTurns = 100;
int botDelay = 0;
std::string configFile = "";
// Parse command line arguments
for (int i = 1; i < argc; ++i) {
if (strcmp(argv[i], "--bot") == 0 || strcmp(argv[i], "-b") == 0) {
botMode = true;
// Check if next argument is a number
if (i + 1 < argc && argv[i + 1][0] != '-') {
botTurns = atoi(argv[i + 1]);
i++;
}
} else if (strcmp(argv[i], "--delay") == 0 || strcmp(argv[i], "-d") == 0) {
// Check if next argument is a number
if (i + 1 < argc && argv[i + 1][0] != '-') {
botDelay = atoi(argv[i + 1]);
i++;
}
} else if (strcmp(argv[i], "--config") == 0 || strcmp(argv[i], "-c") == 0) {
// Check if next argument is a file
if (i + 1 < argc && argv[i + 1][0] != '-') {
configFile = argv[i + 1];
i++;
}
} else if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
printf("Tetris Game\n");
printf("Usage: %s [options]\n", argv[0]);
printf("Options:\n");
printf(" --bot, -b [n] Run bot mode for n turns (default: 100)\n");
printf(" --delay, -d [ms] Delay between bot moves in ms (default: 0)\n");
printf(" --config, -c file Load custom piece definitions from file\n");
printf(" --help, -h Show this help message\n");
printf("\nConfig file format (pieces.cfg):\n");
printf(" F # Piece name (F, I, L, N, P, T, U, V, W, X, Y, Z)\n");
printf(" color: 255,105,180 # Optional color (r,g,b or r,g,b,a)\n");
printf(" 01000 # 5 rows of 5 characters (0=empty, 1=block)\n");
printf(" 11100\n");
printf(" 00000\n");
printf(" 00000\n");
printf(" 00000\n");
return 0;
}
}
// Load custom config if specified
if (!configFile.empty()) {
if (!Tetromino::loadConfig(configFile)) {
fprintf(stderr, "Failed to load config file: %s\n", configFile.c_str());
fprintf(stderr, "Using default pieces.\n");
}
}
if (botMode) {
printf("Starting Tetris Bot - will play for %d turns\n", botTurns);
if (botDelay > 0) {
printf("Bot delay: %dms per move\n", botDelay);
}
printf("Watch the game window to see the bot in action!\n");
}
Game game;
if (!game.init()) {
return 1;
}
if (botMode) {
game.setBotMode(true, botTurns, botDelay);
}
game.run();
// Return exit code based on bot completion
if (botMode) {
if (game.botCompletedSuccessfully()) {
printf("Bot SUCCESS: Completed all %d turns!\n", botTurns);
return 0;
} else {
printf("Bot FAILURE: Game over - target was %d turns\n", botTurns);
return 1;
}
}
return 0;
}