-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhangman_server.cc
85 lines (71 loc) · 2.83 KB
/
hangman_server.cc
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
#include <iostream>
#include <memory>
#include <string>
#include <grpcpp/grpcpp.h>
#include "lib/message.grpc.pb.h"
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using message::HangmanRequest;
using message::HangmanResponse;
using message::Hangman;
struct HangmanGame {
std::string secretWord = "hangman";
std::string maskedWord = "_______";
std::vector<char> guessedLetters = {};
int remainingAttempts = 6;
void updateMaskedWord() {
for (char c : secretWord) {
if (std::find(guessedLetters.begin(), guessedLetters.end(), c) != guessedLetters.end()) {
for (int i = 0; i < secretWord.size(); ++i) {
if (secretWord[i] == c) {
maskedWord[i] = c;
}
}
}
}
}
};
class HangmanServiceImpl final : public Hangman::Service {
Status PlayHangman(ServerContext* context, grpc::ServerReaderWriter<message::HangmanResponse, message::HangmanRequest>* stream) override {
HangmanRequest request;
while (stream->Read(&request)) {
HangmanResponse response;
char guess = request.guess().at(0); // İlk karakteri al (kullanıcıdan tek harf alınacağı varsayılır)
game_.guessedLetters.push_back(guess);
if (game_.secretWord.find(guess) != std::string::npos) {
game_.updateMaskedWord();
response.set_word(game_.maskedWord); // Oyunun güncel kelimesini ayarlayın
response.set_remaining_attempts(game_.remainingAttempts); // Kalan tahmin hakkını ayarlayın
response.set_game_over(game_.maskedWord.find('_') == std::string::npos); // Oyunun bitip bitmediğini belirtin
} else {
--game_.remainingAttempts;
response.set_word(game_.maskedWord); // Oyunun güncel kelimesini ayarlayın
response.set_remaining_attempts(game_.remainingAttempts); // Kalan tahmin hakkını ayarlayın
response.set_game_over(game_.remainingAttempts <= 0); // Oyunun bitip bitmediğini belirtin
}
if(game_.remainingAttempts <= 0){
response.set_word(game_.secretWord);
}
stream->Write(response);
}
return Status::OK;
}
private:
HangmanGame game_;
};
void RunServer() {
std::string server_address("0.0.0.0:50051");
HangmanServiceImpl service;
ServerBuilder builder;
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
builder.RegisterService(&service);
std::unique_ptr<Server> server(builder.BuildAndStart());
std::cout << "Server listening on " << server_address << std::endl;
server->Wait();
}
int main() {
RunServer();
return 0;
}