-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgameserver.cpp
More file actions
220 lines (195 loc) · 6.23 KB
/
Copy pathgameserver.cpp
File metadata and controls
220 lines (195 loc) · 6.23 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
#include "gameserver.h"
#include <QHostAddress>
#include <QJsonDocument>
#include <QJsonObject>
#include <QTcpServer>
#include <QTcpSocket>
namespace {
QByteArray toLine(const QJsonObject& o)
{
return QJsonDocument(o).toJson(QJsonDocument::Compact) + '\n';
}
} // namespace
// ---------------------------------------------------------------------------
// Room
// ---------------------------------------------------------------------------
Room::Room(int id, QTcpSocket* a, QTcpSocket* b, QObject* parent)
: QObject(parent), m_id(id), m_a(a), m_b(b)
{
m_model.newGame(); // 权威布局(种子由系统熵决定,随 matched 下发)
}
void Room::sendTo(QTcpSocket* s, const QJsonObject& o)
{
if (s && s->state() == QAbstractSocket::ConnectedState)
s->write(toLine(o));
}
void Room::sendError(QTcpSocket* s, const QString& msg)
{
QJsonObject o;
o[QStringLiteral("type")] = QStringLiteral("error");
o[QStringLiteral("message")] = msg;
sendTo(s, o);
}
void Room::start()
{
for (int p = 0; p < 2; p++) {
QJsonObject o;
o[QStringLiteral("type")] = QStringLiteral("matched");
o[QStringLiteral("seed")] = qint64(m_model.seedUsed());
o[QStringLiteral("you")] = p;
o[QStringLiteral("state")] = m_model.buildFilteredState(p);
sendTo(socket(p), o);
}
}
void Room::sendState()
{
for (int p = 0; p < 2; p++) {
QJsonObject o;
o[QStringLiteral("type")] = QStringLiteral("state");
o[QStringLiteral("state")] = m_model.buildFilteredState(p);
sendTo(socket(p), o);
}
}
void Room::handleAction(QTcpSocket* from, const QString& action)
{
if (m_finished)
return;
const int p = playerNo(from);
if (p != m_model.currentPlayer()) {
sendError(from, QStringLiteral("not your turn"));
return;
}
if (!m_model.executeAction(action)) {
sendError(from, QStringLiteral("illegal action"));
return;
}
QJsonObject ar;
ar[QStringLiteral("type")] = QStringLiteral("action_result");
ar[QStringLiteral("ok")] = true;
ar[QStringLiteral("result")] = int(m_model.lastResult());
ar[QStringLiteral("yourTurn")] = (m_model.currentPlayer() != p);
sendTo(from, ar);
sendState();
const int w = m_model.winner();
if (w != -1)
finishGame(w, QStringLiteral("sink"));
}
void Room::handleSurrender(QTcpSocket* from)
{
if (m_finished)
return;
const int p = playerNo(from);
if (p != m_model.currentPlayer()) {
sendError(from, QStringLiteral("not your turn"));
return;
}
m_model.surrender();
finishGame(m_model.winner(), QStringLiteral("surrender"));
}
void Room::finishGame(int winner, const QString& reason)
{
m_finished = true;
for (int p = 0; p < 2; p++) {
QJsonObject o;
o[QStringLiteral("type")] = QStringLiteral("game_over");
o[QStringLiteral("winner")] = winner;
o[QStringLiteral("reason")] = reason;
sendTo(socket(p), o);
}
emit over(m_id);
}
// ---------------------------------------------------------------------------
// GameServer
// ---------------------------------------------------------------------------
GameServer::GameServer(QObject* parent)
: QObject(parent)
{
m_server = new QTcpServer(this);
connect(m_server, &QTcpServer::newConnection, this, &GameServer::onNewConnection);
}
bool GameServer::listen(quint16 port)
{
return m_server->listen(QHostAddress::Any, port);
}
quint16 GameServer::port() const
{
return m_server->serverPort();
}
void GameServer::onNewConnection()
{
while (QTcpSocket* s = m_server->nextPendingConnection()) {
m_buf.insert(s, QByteArray());
connect(s, &QTcpSocket::readyRead, this, [this, s]() { onReadyRead(s); });
connect(s, &QTcpSocket::disconnected, this, [this, s]() { onDisconnected(s); });
}
}
void GameServer::onReadyRead(QTcpSocket* s)
{
m_buf[s].append(s->readAll());
int idx;
while ((idx = m_buf[s].indexOf('\n')) >= 0) {
const QByteArray line = m_buf[s].left(idx).trimmed();
m_buf[s].remove(0, idx + 1);
if (!line.isEmpty())
processLine(s, line);
}
}
void GameServer::processLine(QTcpSocket* s, const QByteArray& line)
{
const QJsonObject msg = QJsonDocument::fromJson(line).object();
const QString type = msg[QStringLiteral("type")].toString();
if (type == QLatin1String("queue")) {
if (!m_pending.contains(s))
m_pending.append(s);
tryMatch();
} else if (Room* r = m_roomOf.value(s, nullptr)) {
if (type == QLatin1String("action")) {
const QString action = msg[QStringLiteral("payload")].toObject()[QStringLiteral("action")].toString();
r->handleAction(s, action);
} else if (type == QLatin1String("surrender")) {
r->handleSurrender(s);
} else if (type == QLatin1String("request_state")) {
r->sendState();
}
}
}
void GameServer::tryMatch()
{
while (m_pending.size() >= 2) {
QTcpSocket* a = m_pending.takeFirst();
QTcpSocket* b = m_pending.takeFirst();
Room* r = new Room(m_nextRoomId++, a, b, this);
connect(r, &Room::over, this, [this, r](int) { removeRoom(r); });
m_rooms.insert(r->id(), r);
m_roomOf.insert(a, r);
m_roomOf.insert(b, r);
r->start();
}
}
void GameServer::removeRoom(Room* r)
{
m_rooms.remove(r->id());
m_roomOf.remove(r->socket(0));
m_roomOf.remove(r->socket(1));
r->deleteLater();
}
void GameServer::onDisconnected(QTcpSocket* s)
{
m_pending.removeAll(s);
if (Room* r = m_roomOf.value(s, nullptr)) {
if (!r->finished()) {
const int winner = (s == r->socket(0)) ? 1 : 0; // 掉线者的对手获胜
QJsonObject o;
o[QStringLiteral("type")] = QStringLiteral("game_over");
o[QStringLiteral("winner")] = winner;
o[QStringLiteral("reason")] = QStringLiteral("opponent_left");
QTcpSocket* other = (s == r->socket(0)) ? r->socket(1) : r->socket(0);
if (other && other->state() == QAbstractSocket::ConnectedState)
other->write(toLine(o));
}
removeRoom(r);
}
m_roomOf.remove(s);
m_buf.remove(s);
s->deleteLater();
}