summaryrefslogtreecommitdiff
path: root/server/player.cpp
blob: 6e1a7d3502637a81982367e2a9532c303e53f361 (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
#include "player.h"

#include <boost/bind.hpp>

Player::p Player::create(Connection::p c, boost::function<void (Player::p)> f) {
	Player::p p(new Player(c, f));
	p->start();
	return p;
}

Player::Player(Connection::p c, boost::function<void (Player::p)> f) : connection(c), timer(c->socket.get_io_service()), lobby_callback(f) {
	
}

void Player::start() {
	// Send Hello.
	connection->send(make_shared<Message::Hello>("aotenjoud git"));
	
	// Wait for Login.
	connection->recv(boost::bind(&Player::handle_login, shared_from_this(), _1));
}

void Player::handle_login(Message::p msg) {
	if(msg->type != Message::Types::Login) {
		return;
	}
	
	Message::Login::p login_msg = dynamic_pointer_cast<Message::Login>(msg);
	
	// Check if nick is invalid.
	if(login_msg->nick.size() == 0) {
		connection->send(make_shared<Message::LoginResponse>(false));
		connection->recv(boost::bind(&Player::handle_login, shared_from_this(), _1));
		return;
	}
	
	connection->send(make_shared<Message::LoginResponse>(true));
	
	nick_ = login_msg->nick;
	
	lobby_callback(shared_from_this());
}

void Player::handle_ready(Message::p msg) {
	if(msg->type != Message::Types::Ready) {
		return;
	}
	
	ready_callback();
}

void Player::handle_action(Message::p msg) {
	if(msg->type != Message::Types::RoundAction) {
		return;
	}
	
	Message::RoundAction::p action_msg = dynamic_pointer_cast<Message::RoundAction>(msg);
	
	action_msg->action.player = id;
	action_callback(action_msg->action);
}

std::string Player::nick() {
	return nick_;
}

void Player::game_start(boost::function<void ()> callback, std::vector<Player::p> players) {
	ready_callback = callback;
	
	Message::GameStart::p msg = make_shared<Message::GameStart>();
	
	for(std::vector<Player::p>::iterator i = players.begin(); i != players.end(); i++) {
		msg->players.push_back((*i)->nick());
	}
	msg->player_id = id;
	
	connection->send(msg);
	
	connection->recv(boost::bind(&Player::handle_ready, shared_from_this(), _1));
}

void Player::round_start() {
	connection->send(make_shared<Message::RoundStart>());
}

void Player::round_state(State state) {
	connection->send(make_shared<Message::RoundState>(state));
}

void Player::get_action(boost::function<void (Action)> callback) {
	action_callback = callback;
	
	connection->recv(boost::bind(&Player::handle_action, shared_from_this(), _1));
}