forked from HaikuArchives/Haiku2048
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TerminalBoard.cpp
133 lines (117 loc) · 2.39 KB
/
TerminalBoard.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
/*
* Copyright (c) 2015 Markus Himmel
* This file is distributed under the terms of the MIT license
*/
#include <String.h>
#include "Game.h"
#include "TerminalBoard.h"
#include <string>
#include <map>
#include <iostream>
#include <iomanip>
int32 control(void *data);
TerminalBoard::TerminalBoard(Game *target)
:
GameBoard(target)
{
fControlID = spawn_thread(&control, "TerminalBoard control keeper",
B_NORMAL_PRIORITY, (void *)target);
}
TerminalBoard::~TerminalBoard()
{
}
void
TerminalBoard::gameStarted()
{
showBoard();
resume_thread(fControlID);
}
void
TerminalBoard::gameEnded()
{
suspend_thread(fControlID);
std::cout << "Game has ended." << std::endl;
}
void
TerminalBoard::boardChanged(bool canUndo)
{
showBoard();
}
void
TerminalBoard::nameRequest()
{
std::cout << "Please type in your name and press enter in the window." << std::endl;
}
uint32
digits(uint32 num)
{
uint32 result = 1;
while (num > 10)
{
result++;
num /= 10;
}
return result;
}
int32
control(void *data)
{
Game *target = (Game *)data;
BMessenger messenger(NULL, target);
while (true)
{
int32 c = std::cin.get();
if (c == 'w' || c == 'a' || c == 's' || c == 'd'){
BMessage move(H2048_MAKE_MOVE);
move.AddInt32("direction", c);
messenger.SendMessage(&move);
} else if (c == 'u') {
BMessage undo(H2048_UNDO_MOVE);
messenger.SendMessage(&undo);
} else {
continue;
}
std::cout << std::endl;
}
}
void
TerminalBoard::showBoard()
{
uint32 width = 1;
for (uint32 x = 0; x < fTarget->SizeX(); x++)
{
for (uint32 y = 0; y < fTarget->SizeY(); y++)
{
uint32 digl = digits(1 << fTarget->BoardAt(x, y));
width = width > digl ? width : digl;
}
}
BString dashes;
uint32 numDashes = fTarget->SizeX() * (width + 1) + 1;
for (uint32 i = 0; i < numDashes; i++)
{
dashes << "-";
}
for (uint32 y = 0; y < fTarget->SizeY(); y++)
{
// Header
std::cout << dashes << "\n|";
for (uint32 x = 0; x < fTarget->SizeX(); x++)
{
uint32 tileValue = fTarget->BoardAt(x, y);
std::cout << std::setw(width);
if (tileValue != 0)
std::cout << (1 << tileValue);
else
std::cout << " ";
std::cout << "|";
}
std::cout << '\n';
}
std::cout << dashes << "\nHigh Score: " << fTarget->Score_Highest();
if(fTarget->Username()[0])
std::cout << " by " << fTarget->Username() << std::endl;
else
std::cout << std::endl;
std::cout << "Score: " << fTarget->Score() << std::endl;
}