misc(refactor): moved tournament to seperate module
This commit is contained in:
127
src/lib.rs
Normal file
127
src/lib.rs
Normal file
@@ -0,0 +1,127 @@
|
||||
use std::{collections::HashMap, net::SocketAddr, sync::Arc};
|
||||
|
||||
use rand::Rng;
|
||||
use tokio::sync::{RwLock, mpsc::{UnboundedSender, error::SendError}};
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use tracing::error;
|
||||
|
||||
use crate::{tournaments::Tournament, types::{Client, Color, Match}};
|
||||
|
||||
pub mod types;
|
||||
pub mod tournaments;
|
||||
|
||||
pub type Clients = Arc<RwLock<HashMap<SocketAddr, Arc<RwLock<Client>>>>>;
|
||||
pub type Usernames = Arc<RwLock<HashMap<String, SocketAddr>>>;
|
||||
pub type Observers = Arc<RwLock<HashMap<SocketAddr, UnboundedSender<Message>>>>;
|
||||
pub type Matches = Arc<RwLock<HashMap<u32, Arc<RwLock<Match>>>>>;
|
||||
pub type WrappedTournament = Arc<RwLock<Option<Arc<RwLock<dyn Tournament + Send + Sync>>>>>;
|
||||
|
||||
pub async fn broadcast_message(addrs: &Vec<SocketAddr>, observers: &Observers, msg: &str) {
|
||||
for addr in addrs {
|
||||
let observers_guard = observers.read().await;
|
||||
let tx = observers_guard.get(addr);
|
||||
if tx.is_none() { continue; }
|
||||
let _ = send(tx.unwrap(), msg);
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn broadcast_message_all_observers(observers: &Observers, msg: &str) {
|
||||
let observers_guard = observers.read().await;
|
||||
for (_, tx) in observers_guard.iter() {
|
||||
let _ = send(tx, msg);
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn watch(matches: &Matches, new_match_id: u32, addr: SocketAddr) -> Result<(), String> {
|
||||
let matches_guard = matches.read().await;
|
||||
|
||||
for match_guard in matches_guard.values() {
|
||||
let mut found = false;
|
||||
let mut a_match = match_guard.write().await;
|
||||
for i in 0..a_match.viewers.len() {
|
||||
if a_match.viewers[i] == addr {
|
||||
a_match.viewers.remove(i);
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if found {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let result = matches_guard.get(&new_match_id);
|
||||
if result.is_none() {
|
||||
return Err("Match not found".to_string());
|
||||
}
|
||||
result.unwrap().write().await.viewers.push(addr);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn auth_check(admin: &Arc<RwLock<Option<SocketAddr>>>, addr: SocketAddr) -> bool {
|
||||
if admin.read().await.is_none() || admin.read().await.unwrap() != addr {
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub async fn gen_match_id(matches: &Matches) -> u32 {
|
||||
let matches_guard = matches.read().await;
|
||||
let mut result = rand::rng().random_range(100000..=999999);
|
||||
while matches_guard.get(&result).is_some() {
|
||||
result = rand::rng().random_range(100000..=999999);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn terminate_match(match_id: u32, matches: &Matches, clients: &Clients, observers: &Observers, demo_mode: bool) {
|
||||
let matches_guard = matches.read().await;
|
||||
let the_match = matches_guard.get(&match_id);
|
||||
if the_match.is_none() {
|
||||
error!("Tried to call terminate_match on invalid matchID: {}", match_id);
|
||||
}
|
||||
let the_match = the_match.unwrap().read().await;
|
||||
|
||||
if the_match.wait_thread.is_some() {
|
||||
the_match.wait_thread.as_ref().unwrap().abort();
|
||||
}
|
||||
|
||||
broadcast_message(&the_match.viewers, observers, "GAME:TERMINATED").await;
|
||||
|
||||
let clients_guard = clients.read().await;
|
||||
let mut player1 = clients_guard.get(&the_match.player1).unwrap().write().await;
|
||||
let _ = send(&player1.connection, "GAME:TERMINATED");
|
||||
player1.current_match = None;
|
||||
player1.color = Color::None;
|
||||
drop(player1);
|
||||
|
||||
if !demo_mode {
|
||||
let mut player2 = clients_guard.get(&the_match.player2).unwrap().write().await;
|
||||
let _ = send(&player2.connection, "GAME:TERMINATED");
|
||||
player2.current_match = None;
|
||||
player2.color = Color::None;
|
||||
drop(player2);
|
||||
}
|
||||
|
||||
drop(clients_guard);
|
||||
|
||||
drop(the_match);
|
||||
drop(matches_guard);
|
||||
|
||||
matches.write().await.remove(&match_id);
|
||||
}
|
||||
|
||||
pub fn random_move(board: &[Vec<Color>]) -> usize {
|
||||
let mut random = rand::rng().random_range(0..7);
|
||||
while board[random][5] != Color::None {
|
||||
random = rand::rng().random_range(0..7);
|
||||
}
|
||||
|
||||
random
|
||||
}
|
||||
|
||||
pub fn send(tx: &UnboundedSender<Message>, text: &str) -> Result<(), SendError<Message>> {
|
||||
tx.send(Message::text(text))
|
||||
}
|
||||
140
src/main.rs
140
src/main.rs
@@ -1,15 +1,12 @@
|
||||
mod types;
|
||||
|
||||
use crate::types::{*};
|
||||
use connect4_moderator_server::{*};
|
||||
use connect4_moderator_server::types::{*};
|
||||
use connect4_moderator_server::tournaments::{*};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use rand::Rng;
|
||||
use std::collections::HashMap;
|
||||
use std::env;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tokio::sync::mpsc::error::SendError;
|
||||
use tokio::sync::mpsc::UnboundedSender;
|
||||
use tokio::sync::RwLock;
|
||||
use tokio_tungstenite::{accept_async, tungstenite::Message};
|
||||
use tracing::{error, info, warn};
|
||||
@@ -44,27 +41,8 @@ async fn main() -> Result<(), anyhow::Error> {
|
||||
let listener = TcpListener::bind(&addr).await?;
|
||||
info!("WebSocket server listening on: {}", addr);
|
||||
|
||||
let clients: Clients = Arc::new(RwLock::new(HashMap::new()));
|
||||
let usernames: Usernames = Arc::new(RwLock::new(HashMap::new()));
|
||||
let observers: Observers = Arc::new(RwLock::new(HashMap::new()));
|
||||
let matches: Matches = Arc::new(RwLock::new(HashMap::new()));
|
||||
let admin: Arc<RwLock<Option<SocketAddr>>> = Arc::new(RwLock::new(None));
|
||||
let tournament: WrappedTournament = Arc::new(RwLock::new(None));
|
||||
let waiting_timeout: Arc<RwLock<u64>> = Arc::new(RwLock::new(5000));
|
||||
|
||||
let server_data = Arc::new(
|
||||
Server {
|
||||
clients,
|
||||
usernames,
|
||||
observers,
|
||||
matches,
|
||||
admin,
|
||||
admin_password,
|
||||
tournament,
|
||||
waiting_timeout,
|
||||
demo_mode,
|
||||
tournament_type,
|
||||
}
|
||||
Server::new(admin_password.as_ref().clone(), demo_mode, tournament_type)
|
||||
);
|
||||
|
||||
while let Ok((stream, addr)) = listener.accept().await {
|
||||
@@ -725,113 +703,3 @@ fn end_game_check(board: &[Vec<Color>]) -> (Color, bool) {
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
async fn broadcast_message(addrs: &Vec<SocketAddr>, observers: &Observers, msg: &str) {
|
||||
for addr in addrs {
|
||||
let observers_guard = observers.read().await;
|
||||
let tx = observers_guard.get(addr);
|
||||
if tx.is_none() { continue; }
|
||||
let _ = send(tx.unwrap(), msg);
|
||||
}
|
||||
}
|
||||
|
||||
async fn broadcast_message_all_observers(observers: &Observers, msg: &str) {
|
||||
let observers_guard = observers.read().await;
|
||||
for (_, tx) in observers_guard.iter() {
|
||||
let _ = send(tx, msg);
|
||||
}
|
||||
}
|
||||
|
||||
async fn watch(matches: &Matches, new_match_id: u32, addr: SocketAddr) -> Result<(), String> {
|
||||
let matches_guard = matches.read().await;
|
||||
|
||||
for match_guard in matches_guard.values() {
|
||||
let mut found = false;
|
||||
let mut a_match = match_guard.write().await;
|
||||
for i in 0..a_match.viewers.len() {
|
||||
if a_match.viewers[i] == addr {
|
||||
a_match.viewers.remove(i);
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if found {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let result = matches_guard.get(&new_match_id);
|
||||
if result.is_none() {
|
||||
return Err("Match not found".to_string());
|
||||
}
|
||||
result.unwrap().write().await.viewers.push(addr);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn auth_check(admin: &Arc<RwLock<Option<SocketAddr>>>, addr: SocketAddr) -> bool {
|
||||
if admin.read().await.is_none() || admin.read().await.unwrap() != addr {
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
async fn gen_match_id(matches: &Matches) -> u32 {
|
||||
let matches_guard = matches.read().await;
|
||||
let mut result = rand::rng().random_range(100000..=999999);
|
||||
while matches_guard.get(&result).is_some() {
|
||||
result = rand::rng().random_range(100000..=999999);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn terminate_match(match_id: u32, matches: &Matches, clients: &Clients, observers: &Observers, demo_mode: bool) {
|
||||
let matches_guard = matches.read().await;
|
||||
let the_match = matches_guard.get(&match_id);
|
||||
if the_match.is_none() {
|
||||
error!("Tried to call terminate_match on invalid matchID: {}", match_id);
|
||||
}
|
||||
let the_match = the_match.unwrap().read().await;
|
||||
|
||||
if the_match.wait_thread.is_some() {
|
||||
the_match.wait_thread.as_ref().unwrap().abort();
|
||||
}
|
||||
|
||||
broadcast_message(&the_match.viewers, observers, "GAME:TERMINATED").await;
|
||||
|
||||
let clients_guard = clients.read().await;
|
||||
let mut player1 = clients_guard.get(&the_match.player1).unwrap().write().await;
|
||||
let _ = send(&player1.connection, "GAME:TERMINATED");
|
||||
player1.current_match = None;
|
||||
player1.color = Color::None;
|
||||
drop(player1);
|
||||
|
||||
if !demo_mode {
|
||||
let mut player2 = clients_guard.get(&the_match.player2).unwrap().write().await;
|
||||
let _ = send(&player2.connection, "GAME:TERMINATED");
|
||||
player2.current_match = None;
|
||||
player2.color = Color::None;
|
||||
drop(player2);
|
||||
}
|
||||
|
||||
drop(clients_guard);
|
||||
|
||||
drop(the_match);
|
||||
drop(matches_guard);
|
||||
|
||||
matches.write().await.remove(&match_id);
|
||||
}
|
||||
|
||||
fn random_move(board: &[Vec<Color>]) -> usize {
|
||||
let mut random = rand::rng().random_range(0..7);
|
||||
while board[random][5] != Color::None {
|
||||
random = rand::rng().random_range(0..7);
|
||||
}
|
||||
|
||||
random
|
||||
}
|
||||
|
||||
fn send(tx: &UnboundedSender<Message>, text: &str) -> Result<(), SendError<Message>> {
|
||||
tx.send(Message::text(text))
|
||||
}
|
||||
|
||||
17
src/tournaments/mod.rs
Normal file
17
src/tournaments/mod.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use crate::{*};
|
||||
|
||||
pub mod round_robin;
|
||||
pub use round_robin::RoundRobin;
|
||||
|
||||
#[async_trait]
|
||||
pub trait Tournament {
|
||||
fn new(ready_players: &[SocketAddr]) -> Self where Self: Sized;
|
||||
async fn next(&mut self, clients: &Clients, matches: &Matches, observers: &Observers);
|
||||
async fn start(&mut self, clients: &Clients, matches: &Matches);
|
||||
async fn cancel(&mut self, clients: &Clients, matches: &Matches, observers: &Observers);
|
||||
fn is_completed(&self) -> bool;
|
||||
}
|
||||
174
src/tournaments/round_robin.rs
Normal file
174
src/tournaments/round_robin.rs
Normal file
@@ -0,0 +1,174 @@
|
||||
use std::{collections::HashMap, net::SocketAddr};
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use crate::{*};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RoundRobin {
|
||||
pub players: HashMap<u32, SocketAddr>,
|
||||
pub top_half: Vec<u32>,
|
||||
pub bottom_half: Vec<u32>,
|
||||
pub is_completed: bool,
|
||||
}
|
||||
|
||||
impl RoundRobin {
|
||||
async fn create_matches(&self, clients: &Clients, matches: &Matches) {
|
||||
let clients_guard = clients.read().await;
|
||||
for (i, id) in self.top_half.iter().enumerate() {
|
||||
let player1_addr = self.players.get(id).unwrap();
|
||||
let player2_addr = self.players.get(self.bottom_half.get(i).unwrap());
|
||||
|
||||
if player2_addr.is_none() { continue; }
|
||||
let player2_addr = player2_addr.unwrap();
|
||||
|
||||
let match_id: u32 = gen_match_id(matches).await;
|
||||
let new_match = Arc::new(RwLock::new(Match::new(
|
||||
match_id,
|
||||
*player1_addr,
|
||||
*player2_addr,
|
||||
)));
|
||||
|
||||
let match_guard = new_match.read().await;
|
||||
let mut player1 = clients_guard.get(player1_addr).unwrap().write().await;
|
||||
|
||||
player1.current_match = Some(match_id);
|
||||
player1.ready = false;
|
||||
|
||||
if match_guard.player1 == *player1_addr {
|
||||
player1.color = Color::Red;
|
||||
let _ = send(&player1.connection, "GAME:START:1");
|
||||
} else {
|
||||
player1.color = Color::Yellow;
|
||||
let _ = send(&player1.connection, "GAME:START:0");
|
||||
}
|
||||
|
||||
drop(player1);
|
||||
|
||||
let mut player2 = clients_guard.get(player2_addr).unwrap().write().await;
|
||||
|
||||
player2.current_match = Some(match_id);
|
||||
player2.ready = false;
|
||||
|
||||
if match_guard.player1 == *player2_addr {
|
||||
player2.color = Color::Red;
|
||||
let _ = send(&player2.connection, "GAME:START:1");
|
||||
} else {
|
||||
player2.color = Color::Yellow;
|
||||
let _ = send(&player2.connection, "GAME:START:0");
|
||||
}
|
||||
|
||||
drop(player2);
|
||||
|
||||
matches.write().await.insert(match_id, new_match.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tournament for RoundRobin {
|
||||
fn new(ready_players: &[SocketAddr]) -> RoundRobin {
|
||||
let mut result = RoundRobin {
|
||||
players: HashMap::new(),
|
||||
top_half: Vec::new(),
|
||||
bottom_half: Vec::new(),
|
||||
is_completed: false,
|
||||
};
|
||||
|
||||
let size = ready_players.len();
|
||||
|
||||
for (id, player) in ready_players.iter().enumerate() {
|
||||
result.players.insert(id as u32, *player);
|
||||
}
|
||||
|
||||
for i in 0..size / 2 {
|
||||
result.top_half.push(i as u32);
|
||||
}
|
||||
|
||||
for i in size / 2..size {
|
||||
result.bottom_half.push(i as u32);
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
async fn next(&mut self, clients: &Clients, matches: &Matches, observers: &Observers) {
|
||||
if self.is_completed {
|
||||
return;
|
||||
}
|
||||
|
||||
if self.top_half.len() <= 1 || self.bottom_half.is_empty() {
|
||||
self.is_completed = true;
|
||||
return;
|
||||
}
|
||||
|
||||
let last_from_top = self.top_half.pop().unwrap();
|
||||
let first_from_bottom = self.bottom_half.remove(0);
|
||||
|
||||
self.top_half.insert(1, first_from_bottom);
|
||||
self.bottom_half.push(last_from_top);
|
||||
|
||||
let expected_bottom_start = self.top_half.len() as u32;
|
||||
if self.top_half[1] == 1 && self.bottom_half[0] == expected_bottom_start {
|
||||
self.is_completed = true;
|
||||
}
|
||||
|
||||
if self.is_completed() {
|
||||
// Send scores
|
||||
let clients_guard = clients.read().await;
|
||||
let mut player_scores: Vec<(String, u32)> = Vec::new();
|
||||
for (_, player_addr) in self.players.iter() {
|
||||
let mut player = clients_guard.get(player_addr).unwrap().write().await;
|
||||
let _ = send(&player.connection.clone(), "TOURNAMENT:END");
|
||||
player_scores.push((player.username.clone(), player.score));
|
||||
player.score = 0;
|
||||
player.round_robin_id = 0;
|
||||
}
|
||||
|
||||
player_scores.sort_by(|a, b| b.1.cmp(&a.1));
|
||||
|
||||
let mut message = "TOURNAMENT:END:".to_string();
|
||||
for (player, score) in player_scores.iter() {
|
||||
message.push_str(&format!("{},{}|", player, score))
|
||||
}
|
||||
message.pop();
|
||||
|
||||
broadcast_message_all_observers(observers, &message).await;
|
||||
}
|
||||
else {
|
||||
// Create next matches
|
||||
self.create_matches(clients, matches).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn start(&mut self, clients: &Clients, matches: &Matches) {
|
||||
self.create_matches(clients, matches).await;
|
||||
}
|
||||
|
||||
async fn cancel(&mut self, clients: &Clients, matches: &Matches, observers: &Observers) {
|
||||
for (_, addr) in self.players.iter() {
|
||||
let clients_guard = clients.read().await;
|
||||
|
||||
let client = clients_guard.get(addr);
|
||||
if client.is_none() { continue; }
|
||||
let client = client.unwrap().read().await;
|
||||
let client_connection = client.connection.clone();
|
||||
let client_ready = client.ready;
|
||||
|
||||
let match_id = client.current_match;
|
||||
if match_id.is_none() { continue; }
|
||||
let match_id = match_id.unwrap();
|
||||
|
||||
drop(client);
|
||||
drop(clients_guard);
|
||||
|
||||
terminate_match(match_id, matches, clients, observers, false).await;
|
||||
|
||||
if !client_ready {
|
||||
let _ = send(&client_connection, "TOURNAMENT:END");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_completed(&self) -> bool { self.is_completed }
|
||||
}
|
||||
205
src/types.rs
205
src/types.rs
@@ -1,19 +1,11 @@
|
||||
use crate::*;
|
||||
use rand::Rng;
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::vec;
|
||||
use async_trait::async_trait;
|
||||
use tokio::sync::mpsc::UnboundedSender;
|
||||
use tokio::sync::RwLock;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use crate::{broadcast_message_all_observers, gen_match_id, send, terminate_match};
|
||||
|
||||
pub type Clients = Arc<RwLock<HashMap<SocketAddr, Arc<RwLock<Client>>>>>;
|
||||
pub type Usernames = Arc<RwLock<HashMap<String, SocketAddr>>>;
|
||||
pub type Observers = Arc<RwLock<HashMap<SocketAddr, UnboundedSender<Message>>>>;
|
||||
pub type Matches = Arc<RwLock<HashMap<u32, Arc<RwLock<Match>>>>>;
|
||||
pub type WrappedTournament = Arc<RwLock<Option<Arc<RwLock<dyn Tournament + Send + Sync>>>>>;
|
||||
|
||||
pub struct Server {
|
||||
pub clients: Clients,
|
||||
@@ -28,6 +20,23 @@ pub struct Server {
|
||||
pub tournament_type: String,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
pub fn new(admin_password: String, demo_mode: bool, tournament_type: String) -> Server {
|
||||
Server {
|
||||
clients: Arc::new(RwLock::new(HashMap::new())),
|
||||
usernames: Arc::new(RwLock::new(HashMap::new())),
|
||||
observers: Arc::new(RwLock::new(HashMap::new())),
|
||||
matches: Arc::new(RwLock::new(HashMap::new())),
|
||||
admin: Arc::new(RwLock::new(None)),
|
||||
admin_password: Arc::new(admin_password),
|
||||
tournament: Arc::new(RwLock::new(None)),
|
||||
waiting_timeout: Arc::new(RwLock::new(5000)),
|
||||
demo_mode,
|
||||
tournament_type,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Clone)]
|
||||
pub enum Color {
|
||||
Red,
|
||||
@@ -62,184 +71,6 @@ impl Client {
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait Tournament {
|
||||
fn new(ready_players: &[SocketAddr]) -> Self where Self: Sized;
|
||||
async fn next(&mut self, clients: &Clients, matches: &Matches, observers: &Observers);
|
||||
async fn start(&mut self, clients: &Clients, matches: &Matches);
|
||||
async fn cancel(&mut self, clients: &Clients, matches: &Matches, observers: &Observers);
|
||||
fn is_completed(&self) -> bool;
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RoundRobin {
|
||||
pub players: HashMap<u32, SocketAddr>,
|
||||
pub top_half: Vec<u32>,
|
||||
pub bottom_half: Vec<u32>,
|
||||
pub is_completed: bool,
|
||||
}
|
||||
|
||||
impl RoundRobin {
|
||||
async fn create_matches(&self, clients: &Clients, matches: &Matches) {
|
||||
let clients_guard = clients.read().await;
|
||||
for (i, id) in self.top_half.iter().enumerate() {
|
||||
let player1_addr = self.players.get(id).unwrap();
|
||||
let player2_addr = self.players.get(self.bottom_half.get(i).unwrap());
|
||||
|
||||
if player2_addr.is_none() { continue; }
|
||||
let player2_addr = player2_addr.unwrap();
|
||||
|
||||
let match_id: u32 = gen_match_id(matches).await;
|
||||
let new_match = Arc::new(RwLock::new(Match::new(
|
||||
match_id,
|
||||
*player1_addr,
|
||||
*player2_addr,
|
||||
)));
|
||||
|
||||
let match_guard = new_match.read().await;
|
||||
let mut player1 = clients_guard.get(player1_addr).unwrap().write().await;
|
||||
|
||||
player1.current_match = Some(match_id);
|
||||
player1.ready = false;
|
||||
|
||||
if match_guard.player1 == *player1_addr {
|
||||
player1.color = Color::Red;
|
||||
let _ = send(&player1.connection, "GAME:START:1");
|
||||
} else {
|
||||
player1.color = Color::Yellow;
|
||||
let _ = send(&player1.connection, "GAME:START:0");
|
||||
}
|
||||
|
||||
drop(player1);
|
||||
|
||||
let mut player2 = clients_guard.get(player2_addr).unwrap().write().await;
|
||||
|
||||
player2.current_match = Some(match_id);
|
||||
player2.ready = false;
|
||||
|
||||
if match_guard.player1 == *player2_addr {
|
||||
player2.color = Color::Red;
|
||||
let _ = send(&player2.connection, "GAME:START:1");
|
||||
} else {
|
||||
player2.color = Color::Yellow;
|
||||
let _ = send(&player2.connection, "GAME:START:0");
|
||||
}
|
||||
|
||||
drop(player2);
|
||||
|
||||
matches.write().await.insert(match_id, new_match.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tournament for RoundRobin {
|
||||
fn new(ready_players: &[SocketAddr]) -> RoundRobin {
|
||||
let mut result = RoundRobin {
|
||||
players: HashMap::new(),
|
||||
top_half: Vec::new(),
|
||||
bottom_half: Vec::new(),
|
||||
is_completed: false,
|
||||
};
|
||||
|
||||
let size = ready_players.len();
|
||||
|
||||
for (id, player) in ready_players.iter().enumerate() {
|
||||
result.players.insert(id as u32, *player);
|
||||
}
|
||||
|
||||
for i in 0..size / 2 {
|
||||
result.top_half.push(i as u32);
|
||||
}
|
||||
|
||||
for i in size / 2..size {
|
||||
result.bottom_half.push(i as u32);
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
async fn next(&mut self, clients: &Clients, matches: &Matches, observers: &Observers) {
|
||||
if self.is_completed {
|
||||
return;
|
||||
}
|
||||
|
||||
if self.top_half.len() <= 1 || self.bottom_half.is_empty() {
|
||||
self.is_completed = true;
|
||||
return;
|
||||
}
|
||||
|
||||
let last_from_top = self.top_half.pop().unwrap();
|
||||
let first_from_bottom = self.bottom_half.remove(0);
|
||||
|
||||
self.top_half.insert(1, first_from_bottom);
|
||||
self.bottom_half.push(last_from_top);
|
||||
|
||||
let expected_bottom_start = self.top_half.len() as u32;
|
||||
if self.top_half[1] == 1 && self.bottom_half[0] == expected_bottom_start {
|
||||
self.is_completed = true;
|
||||
}
|
||||
|
||||
if self.is_completed() {
|
||||
// Send scores
|
||||
let clients_guard = clients.read().await;
|
||||
let mut player_scores: Vec<(String, u32)> = Vec::new();
|
||||
for (_, player_addr) in self.players.iter() {
|
||||
let mut player = clients_guard.get(player_addr).unwrap().write().await;
|
||||
let _ = send(&player.connection.clone(), "TOURNAMENT:END");
|
||||
player_scores.push((player.username.clone(), player.score));
|
||||
player.score = 0;
|
||||
player.round_robin_id = 0;
|
||||
}
|
||||
|
||||
player_scores.sort_by(|a, b| b.1.cmp(&a.1));
|
||||
|
||||
let mut message = "TOURNAMENT:END:".to_string();
|
||||
for (player, score) in player_scores.iter() {
|
||||
message.push_str(&format!("{},{}|", player, score))
|
||||
}
|
||||
message.pop();
|
||||
|
||||
broadcast_message_all_observers(observers, &message).await;
|
||||
}
|
||||
else {
|
||||
// Create next matches
|
||||
self.create_matches(clients, matches).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn start(&mut self, clients: &Clients, matches: &Matches) {
|
||||
self.create_matches(clients, matches).await;
|
||||
}
|
||||
|
||||
async fn cancel(&mut self, clients: &Clients, matches: &Matches, observers: &Observers) {
|
||||
for (_, addr) in self.players.iter() {
|
||||
let clients_guard = clients.read().await;
|
||||
|
||||
let client = clients_guard.get(addr);
|
||||
if client.is_none() { continue; }
|
||||
let client = client.unwrap().read().await;
|
||||
let client_connection = client.connection.clone();
|
||||
let client_ready = client.ready;
|
||||
|
||||
let match_id = client.current_match;
|
||||
if match_id.is_none() { continue; }
|
||||
let match_id = match_id.unwrap();
|
||||
|
||||
drop(client);
|
||||
drop(clients_guard);
|
||||
|
||||
terminate_match(match_id, matches, clients, observers, false).await;
|
||||
|
||||
if !client_ready {
|
||||
let _ = send(&client_connection, "TOURNAMENT:END");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_completed(&self) -> bool { self.is_completed }
|
||||
}
|
||||
|
||||
pub struct Match {
|
||||
pub id: u32,
|
||||
pub board: Vec<Vec<Color>>,
|
||||
|
||||
Reference in New Issue
Block a user