C++

No description

fork
loading
Files
  • main.cpp
  • boilerplate
  • pseudo-code.txt
main.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
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
#define LD_USE_TERMCOLOR
#define LD_USE_LINENOISE

#include "boilerplate/ld_output.hpp"
#include "boilerplate/ld_input.hpp"
#include "boilerplate/ld_tui.hpp"
#include "boilerplate/ld_prng.hpp"

#include <clocale>

enum TicTacToeSpot : unsigned int {
	SPOT_EMPTY,
	SPOT_X,
	SPOT_O
};

enum TicTacToeStatus : unsigned int {
	STATUS_PLAYING,
	STATUS_TIE,
	STATUS_PL1_WON,
	STATUS_PL2_WON
};

class TicTacToeBoard {
	std::vector<std::vector<TicTacToeSpot>> board;
	std::vector<std::vector<std::wstring>>  board_tbl;

	size_t size;

	public:
	size_t get_size() const {
		return size;
	}

	void clear(size_t _size = 0) {
		if (_size > 0) {
			size = _size;
		}

		board.clear();
		board_tbl.clear();

		for (size_t i = 0; i < size; i++) {
			std::vector<TicTacToeSpot> row;
			std::vector<std::wstring>  row_tbl;

			row.resize(size);
			row_tbl.resize(size, L"_");

			board.push_back(row);
			board_tbl.push_back(row_tbl);
		}
	}

	explicit TicTacToeBoard(size_t _size) : size(_size) {
		clear();
	}

	std::pair<
		std::pair<
			std::vector<size_t>,
			std::vector<size_t>
		>,
		std::vector<std::vector<std::wstring>>
	> tabulated() {
		return LD::tabulate(board_tbl);
	}

	std::wstring to_string() {
		return LD::render_tabulated(tabulated());
	}

	TicTacToeSpot at(const size_t row, const size_t col) {
		return board[row][col];
	}

	void set(const size_t row, const size_t col, const TicTacToeSpot spot) {
		if (spot != SPOT_EMPTY) {
			board[row][col]     = spot;
			board_tbl[row][col] = spot == SPOT_O ? L"O" : L"X";
		}
	}

	TicTacToeSpot ldiagonal_win() {
		TicTacToeSpot looking = board[0][0];

		for (int i = 1; i < size; i++) {
			if (board[i][i] != looking) {
				return SPOT_EMPTY;
			}
		}

		return looking;
	}

	TicTacToeSpot rdiagonal_win() {
		TicTacToeSpot looking = board[0][size - 1];

		for (int i = 1; i < size; i++) {
			if (board[i][size - 1 - i] != looking) {
				return SPOT_EMPTY;
			}
		}

		return looking;
	}

	TicTacToeSpot horizontal_win(size_t row) {
		TicTacToeSpot looking = board[row][0];

		for (size_t i = 1; i < size; i++) {
			if (board[row][i] != looking) {
				return SPOT_EMPTY;
			}
		}

		return looking;
	}

	TicTacToeSpot any_horizontal_win() {
		for (size_t i = 0; i < size; i++) {
			TicTacToeSpot win = horizontal_win(i);

			if (win != SPOT_EMPTY) {
				return win;
			}
		}

		return SPOT_EMPTY;
	}

	TicTacToeSpot vertical_win(size_t col) {
		TicTacToeSpot looking = board[0][col];

		for (size_t i = 1; i < size; i++) {
			if (board[i][col] != looking) {
				return SPOT_EMPTY;
			}
		}

		return looking;
	}

	TicTacToeSpot any_vertical_win() {
		for (size_t i = 0; i < size; i++) {
			TicTacToeSpot win = vertical_win(i);

			if (win != SPOT_EMPTY) {
				return win;
			}
		}

		return SPOT_EMPTY;
	}

	bool ldiagonal_tie() {
		TicTacToeSpot looking = board[0][0];

		for (int i = 1; i < size; i++) {
			if (looking == SPOT_EMPTY) {
				looking = board[i][i];
			}

			if (board[i][i] != SPOT_EMPTY &&
			    board[i][i] != looking) {
				return true;
			}
		}

		return false;
	}

	bool rdiagonal_tie() {
		TicTacToeSpot looking = board[0][size - 1];

		for (int i = 1; i < size; i++) {
			if (looking == SPOT_EMPTY) {
				looking = board[i][size - 1 - i];
			}

			if (board[i][size - 1 - i] != SPOT_EMPTY &&
			    board[i][size - 1 - i] != looking) {
				return true;
			}
		}

		return false;
	}

	bool horizontal_tie(size_t row) {
		TicTacToeSpot looking = board[row][0];

		for (size_t i = 1; i < size; i++) {
			if (looking == SPOT_EMPTY) {
				looking = board[row][i];
			}

			if (board[row][i] != SPOT_EMPTY &&
			    board[row][i] != looking) {
				return true;
			}
		}

		return false;
	}

	bool all_horizontal_tie() {
		for (size_t i = 0; i < size; i++) {
			bool tie = horizontal_tie(i);

			if (!tie) {
				return false;
			}
		}

		return true;
	}

	bool vertical_tie(size_t col) {
		TicTacToeSpot looking = board[0][col];

		for (size_t i = 1; i < size; i++) {
			if (looking == SPOT_EMPTY) {
				looking = board[i][col];
			}

			if (board[i][col] != SPOT_EMPTY &&
			    board[i][col] != looking) {
				return true;
			}
		}

		return false;
	}

	bool all_vertical_tie() {
		for (size_t i = 0; i < size; i++) {
			bool tie = vertical_tie(i);

			if (!tie) {
				return false;
			}
		}

		return true;
	}

	bool has_tie() {
		/**
		 * we don't care about which so just add them up
		 */
		if (ldiagonal_win() + rdiagonal_win() + any_horizontal_win() +
		    any_vertical_win() > 0) {
			return false;
		}

		return ldiagonal_tie() && rdiagonal_tie() && all_horizontal_tie() &&
		       all_vertical_tie();
	}

	TicTacToeSpot ldiagonal_inhab(TicTacToeSpot looking) {
		for (int i = 1; i < size; i++) {
			if (board[i][i] != SPOT_EMPTY &&
			    board[i][i] != looking) {
				return board[i][i];
			}
		}

		return looking;
	}

	TicTacToeSpot rdiagonal_inhab(TicTacToeSpot looking) {
		for (int i = 1; i < size; i++) {
			if (board[i][size - 1 - i] != SPOT_EMPTY &&
			    board[i][size - 1 - i] != looking) {
				return board[i][size - 1 - i];
			}
		}

		return looking;
	}

	TicTacToeSpot horizontal_inhab(size_t row) {
		TicTacToeSpot looking = board[row][0];

		for (size_t i = 1; i < size; i++) {
			if (looking == SPOT_EMPTY) {
				looking = board[row][i];
			}

			if (board[row][i] != SPOT_EMPTY &&
			    board[row][i] != looking) {
				return board[row][i];
			}
		}

		return looking;
	}

	std::pair<size_t, TicTacToeSpot> any_horizontal_inhab(
		TicTacToeSpot looking) {
		for (size_t i = 0; i < size; i++) {
			TicTacToeSpot inhab = horizontal_inhab(i);

			if (inhab == looking || inhab == SPOT_EMPTY) {
				return {i, inhab};
			}
		}

		return {size, SPOT_EMPTY};
	}

	TicTacToeSpot vertical_inhab(size_t col) {
		TicTacToeSpot looking = board[0][col];

		for (size_t i = 1; i < size; i++) {
			if (looking == SPOT_EMPTY) {
				looking = board[i][col];
			}

			if (board[i][col] != SPOT_EMPTY &&
			    board[i][col] != looking) {
				return board[i][col];
			}
		}

		return looking;
	}

	std::pair<size_t, TicTacToeSpot> any_vertical_inhab(TicTacToeSpot looking) {
		for (size_t i = 0; i < size; i++) {
			TicTacToeSpot inhab = vertical_inhab(i);

			if (inhab == looking || inhab == SPOT_EMPTY) {
				return {i, inhab};
			}
		}

		return {size, SPOT_EMPTY};
	}

	size_t ldiagonal_count(TicTacToeSpot looking) {
		size_t count = 0;

		for (int i = 1; i < size; i++) {
			if (board[i][i] == looking) {
				count++;
			}
		}

		return count;
	}

	size_t rdiagonal_count(TicTacToeSpot looking) {
		size_t count = 0;

		for (int i = 1; i < size; i++) {
			if (board[size - 1 - i][i] == looking) {
				count++;
			}
		}

		return count;
	}

	size_t horizontal_count(TicTacToeSpot looking, size_t row) {
		size_t count = 0;

		for (size_t i = 0; i < size; i++) {
			if (board[row][i] == looking) {
				count++;
			}
		}

		return count;
	}

	size_t vertical_count(TicTacToeSpot looking, size_t col) {
		size_t count = 0;

		for (size_t i = 0; i < size; i++) {
			if (board[i][col] == looking) {
				count++;
			}
		}

		return count;
	}

	TicTacToeStatus get_status() {
		TicTacToeSpot win = ldiagonal_win();

		if (win == SPOT_EMPTY) {
			win = rdiagonal_win();
		}

		if (win == SPOT_EMPTY) {
			win = any_horizontal_win();
		}

		if (win == SPOT_EMPTY) {
			win = any_vertical_win();
		}

		if (win != SPOT_EMPTY) {
			return win == SPOT_O
			       ? STATUS_PL1_WON
			       : STATUS_PL2_WON;
		}

		return has_tie() ? STATUS_TIE : STATUS_PLAYING;
	}
};

class TicTacToeGame {
	TicTacToeBoard board;

	/**
	 * Whether or not it's player 1's turn
	 */
	bool player1_turn;

	public:
	explicit TicTacToeGame(size_t board_size, bool _player1_turn = true)
		: board(board_size), player1_turn(_player1_turn) {}

	explicit TicTacToeGame(TicTacToeBoard _board, bool _player1_turn = true)
		: board(std::move(_board)), player1_turn(_player1_turn) {}

	std::pair<size_t, size_t> pick() {
		using LD::TUI::Keys;

		size_t row  = 0;
		size_t col  = 0;
		size_t size = board.get_size();

		/**
		 * print the table (WITHOUT A NEWLINE) and then return the cursor to the
		 * contents of the first cell
		 *
		 * we don't need a newline, we'll erase this afterwards
		 */
		LD::ofl(board.to_string() +
		        LD::ANSI::c_back(size * 4 - 1) +
		        LD::ANSI::c_up(size * 2 - 1));

		bool quit = false;

		while (!quit) {
			/**
			 * get one keypress
			 */
			Keys::Key key  = LD::TUI::getch();
			bool      bell = true;

			switch (key) {
				case Keys::RIGHT:
					/**
					 * move right one col, make sure col is never >= size
					 */
					if (col < size - 1) {
						bell = false;

						LD::ofl(LD::ANSI::c_forward(4));
						col++;
					}

					break;
				case Keys::LEFT:
					/**
					 * move left one col
					 */
					if (col > 0) {
						bell = false;

						LD::ofl(LD::ANSI::c_back(4));
						col--;
					}

					break;
				case Keys::DOWN:
					/**
					 * move down one row, make sure row is always smaller than
					 * size
					 */
					if (row < size - 1) {
						bell = false;

						LD::ofl(LD::ANSI::c_down(2));
						row++;
					}

					break;
				case Keys::UP:
					/**
					 * move up one row
					 */
					if (row > 0) {
						bell = false;

						LD::ofl(LD::ANSI::c_up(2));
						row--;
					}

					break;
				case Keys::LF:
					if (board.at(row, col) == SPOT_EMPTY) {
						bell = false;
						quit = true;
					}

					break;
				default:
					break;
			}

			/**
			 * `bell` is basically an indicator of if an actual action was
			 * performed
			 *
			 * if it's true, that means nothing happened, so ring a bell to let
			 * the user know
			 */
			if (bell) {
				LD::ofl(LD::ANSI::bel());
			}
		}

		/**
		 * restore cursor to top-left of table (on the border) and erase
		 */
		LD::ofl(LD::ANSI::c_back(col * 4 + 2) +
		        LD::ANSI::c_up(row * 2 + 1) +
		        LD::ANSI::erase_screen(LD::ANSI::ESCREENFROMC));

		return {row, col};
	}

	void play(const size_t row, const size_t col) {
		board.set(row, col, player1_turn ? SPOT_O : SPOT_X);

		player1_turn = !player1_turn;
	}

	std::wstring to_string() {
		return board.to_string();
	}

	bool is_player1_turn() {
		return player1_turn;
	}

	TicTacToeStatus get_status() {
		return board.get_status();
	}

	std::pair<size_t, size_t> pick_random() {
		/**
		 * stores all possibilities
		 */
		std::vector<std::pair<size_t, size_t>> possibilities;

		/**
		 * add all empty spots to the possibilities
		 */
		size_t      size = board.get_size();
		for (size_t row  = 0; row < size; row++) {
			for (size_t col = 0; col < size; col++) {
				if (board.at(row, col) == SPOT_EMPTY) {
					possibilities.emplace_back(row, col);
				}
			}
		}

		/**
		 * no possibilities? there's nothing we can do
		 */
		if (possibilities.empty()) {
			throw std::runtime_error("No possibilities for random choice");
		}

		/**
		 * shuffle and choose the first possibility
		 */
		std::mt19937 rng = LD::get_secure_RNG();
		std::shuffle(possibilities.begin(), possibilities.end(), rng);
		return possibilities[0];
	}

	std::pair<size_t, size_t> pick_smart() {
		size_t size = board.get_size();

		TicTacToeSpot inhab = board.ldiagonal_inhab(SPOT_X);

		/**
		 * if there is any horizontal move that can be blocked, block it
		 */
		for (size_t row = 0; row < size; row++) {
			if (board.horizontal_count(SPOT_O, row) == size - 1) {
				for (size_t col = 0; col < size; col++) {
					if (board.at(row, col) == SPOT_EMPTY) {
						return {row, col};
					}
				}
			}
		}

		/**
		 * if there is any vertical move that can be blocked, block it
		 */
		for (size_t col = 0; col < size; col++) {
			if (board.vertical_count(SPOT_O, col) == size - 1) {
				for (size_t row = 0; row < size; row++) {
					if (board.at(row, col) == SPOT_EMPTY) {
						return {row, col};
					}
				}
			}
		}

		/**
		 * the middle is a good move on odd-sized boards, when there are no
		 * other moves to block
		 *
		 * even if there are diagonals to block, this move would block any
		 * of them if it succeeds
		 */
		size_t middle = size / 2;
		if (size % 2 == 1 && board.at(middle, middle) == SPOT_EMPTY) {
			return {middle, middle};
		}

		/**
		 * if the user can be blocked, block it, else if there is no tie in the
		 * ldiagonal (top-left to bottom-right) then play
		 */
		if (board.ldiagonal_count(SPOT_O) == size - 1 ||
		    board.ldiagonal_inhab(SPOT_X) != SPOT_O) {
			for (size_t i = 0; i < size; i++) {
				if (board.at(i, i) == SPOT_EMPTY) {
					return {i, i};
				}
			}
		}

		/**
		 * if player 1 can be blocked, block it, else if there is no tie in the
		 * rdiagonal (top-right to bottom-left) then play
		 */
		if (board.rdiagonal_count(SPOT_O) == size - 1 ||
		    board.rdiagonal_inhab(SPOT_X) != SPOT_O) {
			for (size_t i = 0; i < size; i++) {
				size_t row = size - 1 - i;

				if (board.at(row, i) == SPOT_EMPTY) {
					return {row, i};
				}
			}
		}

		/**
		 * there are no moves to block, so find out which ones we can play
		 */
		std::pair<size_t, TicTacToeSpot>
			foundx = board.any_horizontal_inhab(SPOT_X),
			foundy = board.any_vertical_inhab(SPOT_X);

		/**
		 * play a horizontal move if there is a path available
		 */
		if (foundx.first != size) {
			for (size_t col = 0; col < board.get_size(); col++) {
				if (board.at(foundx.first, col) == SPOT_EMPTY) {
					return {foundx.first, col};
				}
			}
		}

		/**
		 * play a vertical move if there is a path available
		 */
		if (foundy.first != size) {
			for (size_t row = 0; row < board.get_size(); row++) {
				if (board.at(row, foundy.first) == SPOT_EMPTY) {
					return {row, foundy.first};
				}
			}
		}

		/**
		 * no options? pick a random spot, there will likely be a tie
		 */
		return pick_random();
	}
};

int main() {
	setlocale(LC_ALL, "");

	/**
	 * Two-player mode allows both players to pick and choose which spots to
	 * play
	 */
	bool two_player = false;

	/**
	 * Smart mode causes the computer to HATE YOU.
	 */
	bool smart_mode = false;

	/**
	 * Whether player 1 has the first turn.
	 */
	bool pl1_first_turn = false;

	/**
	 * Runtime error is thrown if the user wishes to quit, so quit cleanly if
	 * that happens
	 */
	try {
		two_player     = LD::get_yn(L"Would you like to use two-player mode?"
		                            L" [y/N] ", true);
		smart_mode     = !two_player &&
		                 LD::get_yn(L"Would you like to use smart mode?"
		                            L" [y/N] ", true);
		pl1_first_turn = LD::get_yn(L"Would you like to have the first turn?"
		                            L" [y/N] ", true);
	} catch (std::runtime_error &) {
		/**
		 * user requested to quit
		 */
		return 0;
	}

	/**
	 * The size of the board (both width and height, else diagonals wouldn't
	 * work)
	 */
	size_t board_size;

	/**
	 * force it out of the user!
	 */
	while (true) {
		if (LD::get_num_input(L"Board size? (3-5) > ", board_size, true)) {
			return 0;
		}

		if (board_size < 3) {
			LD::errnl(L"You can't use a board size smaller than 3!");
		} else if (board_size > 5) {
			LD::errnl(L"You can't use a board size larger than 5!");
		} else {
			break;
		}
	}

	/**
	 * instructions!
	 */
	LD::lognl(L"\nUse the arrow keys to navigate and the Enter key to select a"
	          L" space.");

	/**
	 * The game object used that stores the board and computer "AI"
	 */
	TicTacToeGame game(board_size, pl1_first_turn);

	/**
	 * the loop will flush this
	 */
	LD::o(L"\n\n");

	/**
	 * whether the game is running, or if it's a tie, or who won if it's not
	 */
	TicTacToeStatus status;

	while ((status = game.get_status()) == STATUS_PLAYING) {
		/**
		 * move the cursor up, erase the line, and print whose turn it is
		 * the cursor ends up right below the status
		 */
		LD::o(LD::ANSI::c_up(2) + LD::ANSI::erase_line(LD::ANSI::ELINEFROMC));
		LD::lognl(L"It's player " + std::wstring(game.is_player1_turn()
		                                         ? L"1's turn! (O)"
		                                         : L"2's turn! (X)"));
		LD::nl();

		/**
		 * if it's two-player mode, ask to pick anyway
		 *
		 * else, if it's not your turn, choose either smart or stupid mode based
		 * on which one you selected
		 */
		std::pair<size_t, size_t> played =
			                          (two_player || game.is_player1_turn())
			                          ? game.pick()
			                          : smart_mode
			                            ? game.pick_smart()
			                            : game.pick_random();

		/**
		 * this returns the cursor back to the beginning afterwards, so we don't
		 * have to consider where the cursor moved, it'll still be right after
		 * the status
		 */
		game.play(played.first, played.second);
	}

	LD::ofl(game.to_string() + L"\n\n");

	switch (status) {
		case STATUS_PL1_WON:
			LD::lognl(L"Player 1 won!");

			break;
		case STATUS_PL2_WON:
			if (two_player) {
				LD::lognl(L"Player 2 won!");
			} else {
				LD::lognl(L"The computer won!");
			}

			break;
		case STATUS_TIE:
			LD::lognl(L"It's a tie!");

			break;
		default:
			break;
	}

	try {
		if (LD::get_yn(L"Would you like to play again? [y/N] ", true)) {
			return main();
		}
	} catch (std::exception &) {}
}