aboutsummaryrefslogtreecommitdiff
path: root/main.cpp
blob: 148ae62f9237800d2953b79d987a4837283725c0 (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
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
#include "terminal-game-utils.hpp"
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <future>
#include <iostream>
#include <ostream>
#include <poll.h>
#include <queue>
#include <string>
#include <termios.h>
#include <thread>
#include <tuple>
#include <unistd.h>

struct termios orig_termios;

class Snake {
  private:
	struct mSnakeUnit {
		int x;
		int y;
		std::string appearance;
	};

	struct mCell {
		int x;
		int y;

		bool operator==(const mCell &other) const {
			return (x == other.x) && (y == other.y);
		}
	};

	const std::map<char, std::string> HEAD_ARROWS = {
		{'l', "◁"}, {'d', "▽"}, {'u', "△"}, {'r', "▷"}};

	const int GRACE_FRAMES = 3;
	const int BOARD_OFFSET_X = 2;
	const int BOARD_OFFSET_Y = 1;
	const int WIDTH, HEIGHT, STARTING_DELAY, MIN_DELAY;
	const double ACCELERATION = 0;

	std::mutex mKeyMutex;

	mSnakeUnit mLastDequeued;
	mSnakeUnit mApple;

	std::deque<mSnakeUnit> mSnake;
	std::queue<tgu::GameKey> mKeyQueue;

	std::vector<mCell> mUnoccupied;
	std::vector<mCell> mOccupied;

	int mGraceFrames = GRACE_FRAMES;
	char mSnakeDirection = 'r';
	int mApplesAte = 0;

	bool mGameNotOver = true;
	bool mPaused = false;

	std::string mRepeat(int times, std::string str) {
		std::string returned;
		for (int i = 0; i < times; i++)
			returned += str;
		return returned;
	}

	std::uint8_t mGetDirectionByte(mSnakeUnit pos, mSnakeUnit goal) {
		if (pos.x > goal.x)
			return 0b0001;
		if (pos.x < goal.x)
			return 0b1000;
		if (pos.y > goal.y)
			return 0b0100;
		if (pos.y < goal.y)
			return 0b0010;
		return 0b0000;
	}

	void mOccupy(int x, int y) {
		mCell val(x, y);

		std::erase(mUnoccupied, val);
		mOccupied.push_back(val);
	}

	void mOccupy(mCell val) {
		std::erase(mUnoccupied, val);
		mOccupied.push_back(val);
	}

	void mUnoccupy(int x, int y) {
		mCell val(x, y);

		std::erase(mOccupied, val);
		mUnoccupied.push_back(val);
	}

	void mUnoccupy(mCell val) {
		std::erase(mOccupied, val);
		mUnoccupied.push_back(val);
	}

	std::string mGetTurningCharacter(mSnakeUnit Before, mSnakeUnit Current,
									 mSnakeUnit After) {
		std::uint8_t BeforeDirection = mGetDirectionByte(Current, Before);
		std::uint8_t AfterDirection = mGetDirectionByte(Current, After);

		std::uint8_t CharacterBytes = BeforeDirection + AfterDirection;

		if (CharacterBytes == 0b1001)
			return "═";
		if (CharacterBytes == 0b0110)
			return "║";
		if (CharacterBytes == 0b1010)
			return "╔";
		if (CharacterBytes == 0b0011)
			return "╗";
		if (CharacterBytes == 0b1100)
			return "╚";
		if (CharacterBytes == 0b0101)
			return "╝";

		return "";
	}

	void mDrawBoardOutlines() {
		tgu::MoveCursor(0, 0);
		tgu::ClearTerminal();
		tgu::ClearTerminal();
		tgu::MoveCursor(0, 0);

		std::string horizontalLine = mRepeat(WIDTH * 2 + 1, "═");
		std::string horizontalSpaces = std::string(WIDTH * 2 - 1, ' ');

		std::cout << "╔" << horizontalLine + "╗\n\r";

		for (int i = 0; i < HEIGHT; i++) {
			std::cout << "║ " + horizontalSpaces << " ║\n\r";
		}

		std::cout << "╚" << horizontalLine + "╝";
	}

	char mFlipDirection(char c) {
		if (c == 'l')
			return 'r';
		else if (c == 'd')
			return 'u';
		else if (c == 'u')
			return 'd';
		else if (c == 'r')
			return 'l';
		else
			return ' ';
	}

	void mDie() {
		std::cout << "Die about it";
		tgu::ClearTerminal();
		tgu::MoveCursor(0, 0);
		tgu::MakeCursorVisible();
		exit(0);
	}

	bool IsInSnake(int x, int y) {
		for (mSnakeUnit &u : mSnake) {
			if (u.x == x && u.y == y)
				return true;
		}
		return false;
	}

	void mInputLoop() {
		tgu::GameKey key;
		while (mGameNotOver) {
			key = tgu::GetKeyPress();
			if (mKeyQueue.size() <= 2) {
				mKeyMutex.lock();
				mKeyQueue.push(key);
				mKeyMutex.unlock();
			}
		}
	}

	bool mHorizontalConnectors(mSnakeUnit a, mSnakeUnit b) {
		std::string horizontals = "╔╗╚╝◁▷";
		if (a.y != b.y)
			return false;

		if (horizontals.find(a.appearance) != std::string::npos &&
			horizontals.find(b.appearance) != std::string::npos)
			return true;

		return false;
	}

	void mInitializeApple() {
		int iPos = rand() % mUnoccupied.size();
		mCell apple(mUnoccupied[iPos].x, mUnoccupied[iPos].y);

		mOccupy(apple.x, apple.y);

		mApple = {apple.x, apple.y, "■"};
	}

	void mAddApple() {
		mApplesAte++;
		int iPos = rand() % mUnoccupied.size();
		mCell NewApple(mUnoccupied[iPos].x, mUnoccupied[iPos].y);

		mUnoccupy(mApple.x, mApple.y);
		mOccupy(NewApple.x, NewApple.y);

		mApple = {mUnoccupied[iPos].x, mUnoccupied[iPos].y, mApple.appearance};
	}

	std::tuple<int, int> mGetDirectionOffset(char c) {
		tgu::MoveCursor(30, 30);
		if (c == 'l')
			return std::tuple<int, int>(-1, 0);
		if (c == 'd')
			return std::tuple<int, int>(0, 1);
		if (c == 'u')
			return std::tuple<int, int>(0, -1);
		if (c == 'r') {
			return std::tuple<int, int>(1, 0);
		}

		std::cout << "Some ting wong. Direction is " << c;
		return std::tuple<int, int>(0, 0);
	}

	bool mProcessApple(int &PotentialX, int &PotentialY) {
		if (mApple.x == PotentialX && mApple.y == PotentialY) {
			mAddApple();
			return true;
		} else {
			return false;
		}
	}

	bool mCheckDeathTick(int &PotentialX, int &PotentialY) {
		if (PotentialX <= -1 || PotentialY <= -1 || PotentialX >= WIDTH ||
			PotentialY >= HEIGHT || IsInSnake(PotentialX, PotentialY)) {
			if (mGraceFrames <= 0) {
				mGameNotOver = false;
				mDie();
			} else {
				mGraceFrames = 0;
			}
			return true;
		} else {
			return false;
		}
	}

	mSnakeUnit mPopSnake() {
		mSnakeUnit tr = mSnake.front();
		mCell val(tr.x, tr.y);

		mUnoccupy(val);
		mSnake.pop_front();
		return tr;
	}

	void mPushSnake(mSnakeUnit input) {
		mCell val(input.x, input.y);

		mOccupy(val);
		mSnake.push_back(input);
	}

	void mAdvanceSnake(int &PotentialX, int &PotentialY) {
		mPushSnake({PotentialX, PotentialY, HEAD_ARROWS.at(mSnakeDirection)});
		mSnake[mSnake.size() - 2].appearance = mGetTurningCharacter(
			mSnake[mSnake.size() - 3], mSnake[mSnake.size() - 2],
			mSnake[mSnake.size() - 1]);
	}

	void mSnakeStep() {
		std::tuple<int, int> Offset = mGetDirectionOffset(mSnakeDirection);

		int PotentialX = mSnake.back().x + std::get<0>(Offset);
		int PotentialY = mSnake.back().y + std::get<1>(Offset);

		bool AteApple = mProcessApple(PotentialX, PotentialY);

		bool DeathTicked = mCheckDeathTick(PotentialX, PotentialY);

		if (!DeathTicked) {
			mGraceFrames = mGraceFrames + 1 >= GRACE_FRAMES ? GRACE_FRAMES
															: mGraceFrames + 1;
			mAdvanceSnake(PotentialX, PotentialY);

			if (!AteApple) {
				mLastDequeued = mPopSnake();
			}
		} else {
			mSnake.back().appearance = HEAD_ARROWS.at(mSnakeDirection);
			mLastDequeued = mSnakeUnit(-1, -1, " ");
		}
	}

	void mHandleGameInput(tgu::GameKey input) {
		char PotentialSnakeDirection;

		if (input == tgu::GameKey::W || input == tgu::GameKey::UPARROW ||
			input == tgu::GameKey::K)
			PotentialSnakeDirection = 'u';
		else if (input == tgu::GameKey::A || input == tgu::GameKey::LEFTARROW ||
				 input == tgu::GameKey::H)
			PotentialSnakeDirection = 'l';
		else if (input == tgu::GameKey::S || input == tgu::GameKey::DOWNARROW ||
				 input == tgu::GameKey::J)
			PotentialSnakeDirection = 'd';
		else if (input == tgu::GameKey::D ||
				 input == tgu::GameKey::RIGHTARROW ||
				 input == tgu::GameKey::L) {
			PotentialSnakeDirection = 'r';
		} else if (input == tgu::GameKey::ESCAPE || input == tgu::GameKey::P) {
			mPaused = true;
			return;
		} else if (input == tgu::GameKey::Q) {
			tgu::ClearTerminal();
			tgu::MoveCursor(0, 0);
			tgu::MakeCursorVisible();
			exit(0);
		} else
			return;

		if (PotentialSnakeDirection == mFlipDirection(mSnakeDirection))
			return;
		else
			mSnakeDirection = PotentialSnakeDirection;
	}

	void mHandlePausedInput(tgu::GameKey input) {
		if (input == tgu::GameKey::P || input == tgu::GameKey::ESCAPE)
			mPaused = false;

		if (input == tgu::GameKey::Q)
			mGameNotOver = false;
	}

	void mHandleInput() {
		tgu::GameKey popped = mKeyQueue.front();
		mKeyQueue.pop();

		if (mPaused)
			mHandlePausedInput(popped);
		else
			mHandleGameInput(popped);
	}

	void mGameTick() {
		mKeyMutex.lock();
		if (mKeyQueue.size() != 0) {
			mHandleInput();
		}
		mKeyMutex.unlock();

		if (!mPaused)
			mSnakeStep();
	}

	void mDrawSnake() {
		tgu::TextRGB(0, 255, 0);
		if (mLastDequeued.x != -1) {
			tgu::MoveCursor(mLastDequeued.y + BOARD_OFFSET_Y,
							(mLastDequeued.x * 2) + BOARD_OFFSET_X - 1);
			std::cout << "   ";
		}

		for (int i = 0; i < mSnake.size(); i++) {
			mSnakeUnit &s = mSnake[i];

			if (s.appearance == "═") {
				tgu::MoveCursor(s.y + BOARD_OFFSET_Y,
								(s.x * 2) + BOARD_OFFSET_X - 1);
				std::cout << mRepeat(3, s.appearance);
			} else {
				tgu::MoveCursor(s.y + BOARD_OFFSET_Y,
								(s.x * 2) + BOARD_OFFSET_X);
				std::cout << s.appearance;
			}

			if (i != 0 && mHorizontalConnectors(s, mSnake[i - 1])) {
				int x = std::max(s.x, mSnake[i - 1].x) * 2 + BOARD_OFFSET_X - 1;
				tgu::MoveCursor(s.y + BOARD_OFFSET_Y, x);
				std::cout << "═";
			}
		}

		tgu::TextRed();
		tgu::MoveCursor(mApple.y + BOARD_OFFSET_Y,
						mApple.x * 2 + BOARD_OFFSET_X);
		std::cout << mApple.appearance;

		tgu::TerminalColorReset();
		std::cout << std::flush;
	}

	void mGameLoop() {
		while (mGameNotOver) {
			int CalculatedDelay = STARTING_DELAY - (mApplesAte * ACCELERATION);
			int TickDelay =
				CalculatedDelay >= MIN_DELAY ? CalculatedDelay : MIN_DELAY;
			std::this_thread::sleep_for(std::chrono::milliseconds(TickDelay));
			mGameTick();

			mDrawSnake();
		}
	}

  public:
	struct GameSettings {
		int width = 14;
		int height = 14;
		int startingdelay = 400;
		int minimumdelay = 200;
		int acceleration = 10;
	};

	void mFillUnoccupied() {
		for (int i = 0; i < WIDTH; i++) {
			for (int j = 0; j < HEIGHT; j++) {
				mUnoccupied.push_back({i, j});
			}
		}
	}

	Snake(const GameSettings &settings)
		: WIDTH(settings.width), HEIGHT(settings.height),
		  STARTING_DELAY(settings.startingdelay),
		  ACCELERATION(settings.acceleration),
		  MIN_DELAY(settings.minimumdelay) {
		if (WIDTH < 5 || HEIGHT < 5) {
			std::cout << "Minimum board size of 5x5 not met.";
			return;
		}
	}

	void StartGame() {
		tgu::EnableRawMode();
		tgu::MakeCursorInvisible();
		tgu::EnterGameBuffer();
		tgu::ClearTerminal();
		std::cout << std::flush;

		mDrawBoardOutlines();

		mFillUnoccupied();
		mPushSnake({1, 2, "═"});
		mPushSnake({2, 2, "═"});
		mPushSnake({3, 2, "═"});
		mPushSnake({4, 2, "⇒"});
		mSnakeDirection = 'r';

		mInitializeApple();

		mDrawSnake();

		auto InputLoopResponse =
			std::async(std::launch::async, [this] { mInputLoop(); });

		mGameLoop();
	}

	static void SinglePrompt(std::string prompt, int &val) {
		std::string sTmp;
		int iTmp = 0;

		tgu::ClearTerminal();
		tgu::MoveCursor(0, 0);
		std::cout << prompt;
		tgu::TextRGB(144, 144, 144);
		std::cout << val;
		tgu::MoveCursor(0, prompt.size());
		tgu::TerminalColorReset();

		try {
			std::getline(std::cin, sTmp);
			iTmp = std::stoi(sTmp);
		} catch (const std::exception &e) {
			iTmp = val;
		}
		val = iTmp;
	}

	static GameSettings SettingsPrompt() {
		int width = 14;
		int height = 14;
		int startingdelay = 400;
		int mindelay = 200;
		int acceleration = 10;
		std::string prompt;

		tgu::EnterGameBuffer();

		SinglePrompt("Board Width: ", width);
		SinglePrompt("Board Height: ", height);
		SinglePrompt("Starting delay between steps (ms): ", startingdelay);
		SinglePrompt("Minimum delay: ", mindelay);
		SinglePrompt("Acceleration: ", acceleration);

		tgu::LeaveGameBuffer();

		GameSettings settings = {.width = width,
								 .height = height,
								 .startingdelay = startingdelay,
								 .minimumdelay = mindelay,
								 .acceleration = acceleration};

		return settings;
	}
};

int main() {
	Snake::GameSettings s = Snake::SettingsPrompt();
	std::cout << "Accel: " << s.acceleration << ", Width: " << s.width
			  << ", Height:" << s.height
			  << ", Starting delay:" << s.startingdelay << ", Min delay"
			  << s.minimumdelay << ", Accel:" << s.acceleration;
	Snake hi(s);
	hi.StartGame();
}