misc(refactor): extract command handlers and centralize error handling

- Move command-specific logic out of main.rs into Server::handle_* methods
  (parsing remains in main and handlers accept already-parsed input).
- Handlers now return Result and return Err("ERROR:...") instead of sending
  error messages directly to clients.
- main.rs now logs handler errors to console and sends the error string to
  the client (removed `continue` statements after error sends).
- Move end_game_check from main.rs into lib.rs for reuse.
- Update handler implementations to follow the new error-returning pattern.
This commit is contained in:
2025-12-30 22:26:26 -05:00
Unverified
parent b5d71051a6
commit b416dc17ad
5 changed files with 1143 additions and 878 deletions

View File

@@ -1,15 +1,12 @@
use connect4_moderator_server::{*};
use connect4_moderator_server::types::{*};
use connect4_moderator_server::tournaments::{*};
use connect4_moderator_server::types::*;
use connect4_moderator_server::*;
use futures_util::{SinkExt, StreamExt};
use rand::Rng;
use std::env;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::RwLock;
use tokio_tungstenite::{accept_async, tungstenite::Message};
use tracing::{error, info, warn};
use tracing::{error, info};
// TODO: Allow random "player1" in demo mode
// TODO: Support reconnecting behaviors
@@ -26,31 +23,31 @@ async fn main() -> Result<(), anyhow::Error> {
let args: Vec<String> = env::args().collect();
let demo_mode = args.get(1).is_some() && args.get(1).unwrap() == "demo";
let tournament_type = if !demo_mode {
if let Some(tourney) = args.get(1) {
tourney.clone()
} else {
"round_robin".to_string()
}
} else { "round_robin".to_string() };
let admin_password = env::var("ADMIN_AUTH").unwrap_or_else(|_| String::from("admin"));
info!("Admin password: {}", admin_password);
let admin_password = Arc::new(admin_password);
let tournament_type = if !demo_mode {
if let Some(tourney) = args.get(1) {
tourney.clone()
} else {
"round_robin".to_string()
}
} else {
"round_robin".to_string()
};
let admin_password = env::var("ADMIN_AUTH").unwrap_or_else(|_| String::from("admin"));
info!("Admin password: {}", admin_password);
let admin_password = Arc::new(admin_password);
let addr = "0.0.0.0:8080";
let listener = TcpListener::bind(&addr).await?;
info!("WebSocket server listening on: {}", addr);
let server_data = Arc::new(
Server::new(admin_password.as_ref().clone(), demo_mode, tournament_type)
);
let server_data = Arc::new(Server::new(
admin_password.as_ref().clone(),
demo_mode,
tournament_type,
));
while let Ok((stream, addr)) = listener.accept().await {
tokio::spawn(handle_connection(
stream,
addr,
server_data.clone(),
));
tokio::spawn(handle_connection(stream, addr, server_data.clone()));
}
Ok(())
@@ -84,534 +81,163 @@ async fn handle_connection(
match msg {
Ok(Message::Text(text)) => {
info!("Received text from {}: {}", addr, text);
if text.starts_with("CONNECT:") {
let requested_username = text.split(":").collect::<Vec<&str>>()[1].to_string();
if requested_username.is_empty() {
let _ = send(&tx, &format!("ERROR:INVALID:ID:{}", requested_username));
continue;
}
let mut is_taken = false;
let clients_guard = sd.clients.read().await;
for client in clients_guard.values() {
if requested_username == client.read().await.username {
let _ = send(&tx, &format!("ERROR:INVALID:ID:{}", requested_username));
is_taken = true;
break;
}
}
if is_taken {
continue;
}
drop(clients_guard);
// not taken
sd.observers.write().await.remove(&addr);
sd.usernames.write().await.insert(requested_username.clone(), addr);
sd.clients.write().await.insert(
addr.to_string().parse()?,
Arc::new(RwLock::new(Client::new(
requested_username,
tx.clone(),
addr.to_string().parse()?,
))),
);
let _ = send(&tx, "CONNECT:ACK");
}
else if text == "READY" {
let clients_guard = sd.clients.read().await;
if clients_guard.get(&addr).is_none() {
let _ = send(&tx, "ERROR:INVALID");
continue;
}
if clients_guard.get(&addr).unwrap().read().await.ready {
let _ = send(&tx, "ERROR:INVALID");
continue;
}
let mut client = clients_guard.get(&addr).unwrap().write().await;
client.ready = true;
let _ = send(&tx, "READY:ACK");
if sd.demo_mode {
let match_id: u32 = gen_match_id(&sd.matches).await;
let new_match = Arc::new(RwLock::new(Match::new(
match_id,
addr.to_string().parse()?,
addr.to_string().parse()?,
)));
sd.matches.write().await.insert(match_id, new_match.clone());
client.ready = false;
client.current_match = Some(match_id);
client.color = Color::Red;
let _ = send(&tx, "GAME:START:1");
}
}
else if text.starts_with("PLAY:") {
let clients_guard = sd.clients.read().await;
let client = clients_guard.get(&addr);
// Check if client is valid
if client.is_none() || client.unwrap().read().await.current_match.is_none()
{
let _ = send(&tx, "ERROR:INVALID:MOVE");
continue;
}
let client = client.unwrap().read().await;
let matches_guard = sd.matches.read().await;
let current_match =
matches_guard.get(&client.current_match.unwrap()).unwrap().read().await;
let opponent_addr =
if addr == current_match.player1 {
current_match.player2
} else {
current_match.player1
};
let opponent_connection =
if addr == current_match.player1 {
clients_guard.get(&current_match.player2).unwrap().read().await.connection.clone()
} else {
clients_guard.get(&current_match.player1).unwrap().read().await.connection.clone()
};
let opponent_username =
if addr == current_match.player1 {
clients_guard.get(&current_match.player2).unwrap().read().await.username.clone()
} else {
clients_guard.get(&current_match.player1).unwrap().read().await.username.clone()
};
// Check if it's their move
let mut invalid = false;
if (current_match.ledger.is_empty() && current_match.player1 != addr) ||
(current_match.ledger.last().is_some() && current_match.ledger.last().unwrap().0 == client.color)
{
let _ = send(&tx, "ERROR:INVALID:MOVE");
invalid = true;
}
let column_parse = text.split(":").collect::<Vec<&str>>()[1].parse::<usize>();
drop(current_match);
drop(matches_guard);
let mut matches_guard = sd.matches.write().await;
let mut current_match = matches_guard
.get_mut(&client.current_match.unwrap())
.unwrap()
.write()
.await;
// Check if valid move
if let Ok(column) = column_parse {
if column >= 7 && !invalid {
let _ = send(&tx, "ERROR:INVALID:MOVE");
invalid = true;
}
if current_match.board[column][5] != Color::None && !invalid {
let _ = send(&tx, "ERROR:INVALID:MOVE");
invalid = true;
}
} else {
let _ = send(&tx, "ERROR:INVALID:MOVE");
invalid = true;
}
// Terminate games if a player makes an invalid move
if invalid {
let current_match_id = current_match.id;
let viewers = current_match.viewers.clone();
drop(current_match);
drop(matches_guard);
drop(client);
drop(clients_guard);
if sd.demo_mode {
terminate_match(current_match_id, &sd.matches, &sd.clients, &sd.observers, sd.demo_mode).await;
tx.send(Message::Close(None))?;
} else {
let _ = send(&tx, "GAME:LOSS");
let _ = send(&opponent_connection, "GAME:WINS");
broadcast_message(&viewers, &sd.observers, &format!("GAME:WIN:{}", opponent_username)).await;
let mut clients_guard = sd.clients.write().await;
let mut client = clients_guard.get_mut(&addr).unwrap().write().await;
client.current_match = None;
client.color = Color::None;
drop(client);
let mut opponent = clients_guard.get_mut(&opponent_addr).unwrap().write().await;
opponent.current_match = None;
opponent.color = Color::None;
opponent.score += 1;
drop(opponent);
sd.matches.write().await.remove(&current_match_id).unwrap();
}
continue;
} else {
// Place it
current_match.place_token(client.color.clone(), column_parse.clone()?);
current_match.move_to_dispatch = (client.color.clone(), column_parse.clone()?);
}
// broadcast the move to viewers
broadcast_message(
&current_match.viewers,
&sd.observers,
&format!("GAME:MOVE:{}:{}", client.username, column_parse.clone()?),
)
.await;
// Check game end conditions
let (winner, filled) = end_game_check(&current_match.board);
if winner != Color::None {
if winner == client.color {
let _ = send(&tx, "GAME:WINS");
if !sd.demo_mode {
let _ = send(&opponent_connection, "GAME:LOSS");
let parts: Vec<&str> = text.split(':').collect();
let cmd = parts[0];
match cmd {
"CONNECT" => {
if parts.len() > 1 {
let requested_username = parts[1].to_string();
if let Err(e) =
sd.handle_connect(addr, tx.clone(), requested_username).await
{
error!("handle_connect: {}", e);
let _ = send(&tx, e.to_string().as_str());
}
broadcast_message(
&current_match.viewers,
&sd.observers,
&format!("GAME:WIN:{}", client.username),
)
.await;
} else {
let _ = send(&tx, "GAME:LOSS");
if !sd.demo_mode {
let _ = send(&opponent_connection, "GAME:WINS");
let _ = send(&tx, "ERROR:INVALID:ID:");
}
}
"READY" => {
if let Err(e) = sd.handle_ready(addr, tx.clone()).await {
error!("handle_ready: {}", e);
let _ = send(&tx, e.to_string().as_str());
}
}
"PLAY" => {
if parts.len() > 1 {
match parts[1].parse::<usize>() {
Ok(column) => {
if let Err(e) = sd.handle_play(addr, tx.clone(), column).await {
error!("handle_play: {}", e);
let _ = send(&tx, e.to_string().as_str());
}
}
Err(_) => {
let _ = send(&tx, "ERROR:INVALID:MOVE");
}
}
broadcast_message(
&current_match.viewers,
&sd.observers,
&format!("GAME:WIN:{}", opponent_username),
)
.await;
} else {
let _ = send(&tx, "ERROR:INVALID:MOVE");
}
} else if filled {
let _ = send(&tx, "GAME:DRAW");
if !sd.demo_mode {
let _ = send(&opponent_connection, "GAME:DRAW");
}
"PLAYER" => {
if parts.get(1) == Some(&"LIST") {
if let Err(e) = sd.handle_player_list(tx.clone()).await {
error!("handle_player_list: {}", e);
let _ = send(&tx, e.to_string().as_str());
}
}
broadcast_message(&current_match.viewers, &sd.observers, "GAME:DRAW").await;
}
// remove match from matchmaker
if winner != Color::None || filled {
let current_match_id = current_match.id;
drop(client);
drop(current_match);
drop(clients_guard);
let clients_guard = sd.clients.read().await;
let mut client = clients_guard.get(&addr).unwrap().write().await;
if client.color == winner {
client.score += 1;
}
client.current_match = None;
client.color = Color::None;
drop(client);
let mut opponent = clients_guard.get(&opponent_addr).unwrap().write().await;
if opponent.color == winner {
opponent.score += 1;
}
opponent.current_match = None;
opponent.color = Color::None;
drop(opponent);
matches_guard.remove(&current_match_id).unwrap();
if !sd.demo_mode && matches_guard.is_empty() {
drop(matches_guard);
drop(clients_guard);
let mut tournament_guard = sd.tournament.write().await;
let tourney = tournament_guard.as_mut().unwrap();
tourney.write().await.next(&sd.clients, &sd.matches, &sd.observers).await;
if tourney.read().await.is_completed() {
*tournament_guard = None;
}
}
continue;
"GAME" => {
if parts.get(1) == Some(&"LIST") {
if let Err(e) = sd.handle_game_list(tx.clone()).await {
error!("handle_game_list: {}", e);
let _ = send(&tx, e.to_string().as_str());
}
} else if parts.get(1) == Some(&"WATCH") && parts.len() > 2 {
match parts[2].parse::<u32>() {
Ok(match_id) => {
if let Err(e) =
sd.handle_game_watch(tx.clone(), match_id, addr).await
{
error!("handle_game_watch: {}", e);
let _ = send(&tx, e.to_string().as_str());
}
}
Err(_) => {
let _ = send(&tx, "ERROR:INVALID:WATCH");
}
}
} else if parts.get(1) == Some(&"TERMINATE") && parts.len() > 2 {
match parts[2].parse::<u32>() {
Ok(match_id) => {
if let Err(e) =
sd.handle_game_terminate(tx.clone(), addr, match_id).await
{
error!("handle_game_terminate: {}", e);
let _ = send(&tx, e.to_string().as_str());
}
}
Err(_) => {
let _ = send(&tx, "ERROR:INVALID:TERMINATE");
}
}
}
}
"ADMIN" => {
if parts.get(1) == Some(&"AUTH") && parts.len() > 2 {
if let Err(e) =
sd.handle_admin_auth(tx.clone(), addr, parts[2].to_string()).await
{
error!("handle_admin_auth: {}", e);
let _ = send(&tx, e.to_string().as_str());
}
} else if parts.get(1) == Some(&"KICK") && parts.len() > 2 {
if let Err(e) =
sd.handle_admin_kick(tx.clone(), addr, parts[2].to_string()).await
{
error!("handle_admin_kick: {}", e);
let _ = send(&tx, e.to_string().as_str());
}
}
}
"TOURNAMENT" => {
if parts.get(1) == Some(&"START") {
if let Err(e) = sd.handle_tournament_start(tx.clone(), addr).await {
error!("handle_tournament_start: {}", e);
let _ = send(&tx, e.to_string().as_str());
}
} else if parts.get(1) == Some(&"CANCEL") {
if let Err(e) = sd.handle_tournament_cancel(tx.clone(), addr).await {
error!("handle_tournament_cancel: {}", e);
let _ = send(&tx, e.to_string().as_str());
}
} else if parts.get(1) == Some(&"WAIT") && parts.len() > 2 {
match parts[2].parse::<f64>() {
Ok(v) => {
if let Err(e) =
sd.handle_tournament_wait(tx.clone(), addr, v).await
{
error!("handle_tournament_wait: {}", e);
let _ = send(&tx, e.to_string().as_str());
}
}
Err(_) => {
let _ = send(&tx, "ERROR:INVALID:TOURNAMENT");
}
}
}
}
"GET" => {
if parts.get(1) == Some(&"MOVE_WAIT") {
if let Err(e) = sd.handle_get_move_wait(tx.clone()).await {
error!("handle_get_move_wait: {}", e);
let _ = send(&tx, e.to_string().as_str());
}
} else if parts.get(1) == Some(&"TOURNAMENT_STATUS") {
if let Err(e) = sd.handle_get_tournament_status(tx.clone()).await {
error!("handle_get_tournament_status: {}", e);
let _ = send(&tx, e.to_string().as_str());
}
}
}
_ => {
let _ = send(&tx, "ERROR:UNKNOWN");
}
let connection_to_send = if !sd.demo_mode { opponent_connection.clone() } else { tx.clone() };
let column = if !sd.demo_mode { column_parse.clone()? } else { random_move(&current_match.board) };
if sd.demo_mode {
let move_to_dispatch = current_match.move_to_dispatch.clone();
current_match.ledger.push(move_to_dispatch);
current_match.move_to_dispatch = (Color::Yellow, column);
current_match.place_token(Color::Yellow, column);
}
let waiting = *sd.waiting_timeout.read().await as i64 + (rand::rng().random_range(0..=50) - 25);
let matches_move = sd.matches.clone();
let observers_move = sd.observers.clone();
let match_id_move = current_match.id;
let demo_mode_move = sd.demo_mode;
current_match.wait_thread = Some(tokio::spawn(async move {
tokio::time::sleep(tokio::time::Duration::from_millis(waiting as u64)).await;
let mut matches_guard = matches_move.write().await;
let mut current_match = matches_guard.get_mut(&match_id_move).unwrap().write().await;
let move_to_dispatch = current_match.move_to_dispatch.clone();
current_match.ledger.push(move_to_dispatch);
current_match.move_to_dispatch = (Color::None, 0);
if demo_mode_move {
broadcast_message(
&current_match.viewers,
&observers_move,
&format!("GAME:MOVE:{}:{}", "demo", column),
).await;
}
drop(current_match);
drop(matches_guard);
let _ = send(&connection_to_send, &format!("OPPONENT:{}", column));
}));
}
else if text == "PLAYER:LIST" {
let clients_guard = sd.clients.read().await;
let mut to_send = "PLAYER:LIST:".to_string();
for client_guard in clients_guard.values() {
let player = client_guard.read().await;
to_send += player.username.as_str(); to_send += ",";
to_send += if player.ready { "true" } else { "false" }; to_send += ",";
to_send += if player.current_match.is_some() { "true" } else { "false" };
to_send += "|";
}
to_send.remove(to_send.len() - 1);
let _ = send(&tx, to_send.as_str());
}
else if text == "GAME:LIST" {
let matches_guard = sd.matches.read().await;
let clients_guard = sd.clients.read().await;
let mut to_send = "GAME:LIST:".to_string();
for match_guard in matches_guard.values() {
let a_match = match_guard.read().await;
let player1 = clients_guard.get(&a_match.player1).unwrap().read().await;
let player2 = clients_guard.get(&a_match.player2).unwrap().read().await;
to_send += a_match.id.to_string().as_str();
to_send += ","; to_send += player1.username.as_str(); to_send += ",";
to_send += if player1.username == player2.username { "demo" } else { player2.username.as_str() };
to_send += "|";
}
to_send.remove(to_send.len() - 1);
let _ = send(&tx, to_send.as_str());
}
else if text.starts_with("GAME:WATCH:") {
let match_id_parse = text.split(":").collect::<Vec<&str>>()[2].parse::<u32>();
match match_id_parse {
Ok(match_id) => {
let result = watch(&sd.matches, match_id, addr).await;
if result.is_err() { let _ = send(&tx, "ERROR:INVALID:WATCH"); continue; }
let clients_guard = sd.clients.read().await;
let matches_guard = sd.matches.read().await;
let the_match = matches_guard.get(&match_id).unwrap().read().await;
let player1 = clients_guard.get(&the_match.player1).unwrap().read().await.username.clone();
let mut player2 = clients_guard.get(&the_match.player2).unwrap().read().await.username.clone();
if sd.demo_mode { player2 = "demo".to_string(); }
let ledger = the_match.ledger.clone();
drop(clients_guard);
drop(the_match);
drop(matches_guard);
let mut message = format!("GAME:WATCH:ACK:{},{},{}|", match_id, player1, player2);
for a_move in ledger {
if a_move.0 == Color::Red {
message += &format!("{},{}|", player1, a_move.1);
} else {
message += &format!("{},{}|", player2, a_move.1);
}
}
message.pop();
let _ = send(&tx, &message);
}
Err(_) => { let _ = send(&tx, "ERROR:INVALID:WATCH"); continue; }
}
}
else if text.starts_with("ADMIN:AUTH:") {
if sd.admin.read().await.is_some() {
let _ = send(&tx, "ERROR:INVALID:AUTH");
continue;
}
let password_parse = text.split(":").collect::<Vec<&str>>()[2];
if password_parse != *sd.admin_password {
let _ = send(&tx, "ERROR:INVALID:AUTH");
continue;
}
let mut admin_guard = sd.admin.write().await;
*admin_guard = Some(addr.to_string().parse()?);
let _ = send(&tx, "ADMIN:AUTH:ACK");
}
else if text.starts_with("ADMIN:KICK:") {
if !auth_check(&sd.admin, addr).await {
let _ = send(&tx, "ERROR:INVALID:AUTH");
}
let kick_username = text.split(":").collect::<Vec<&str>>()[2];
let usernames_guard = sd.usernames.read().await;
let clients_guard = sd.clients.read().await;
let kick_addr_result = usernames_guard.get(kick_username);
match kick_addr_result {
Some(kick_addr) => {
let kick_client = clients_guard.get(kick_addr).unwrap().read().await;
kick_client.connection.send(Message::Close(None))?;
},
None => {
let _ = send(&tx, "ERROR:INVALID:KICK");
continue
}
}
}
else if text.starts_with("GAME:TERMINATE:") {
if !auth_check(&sd.admin, addr).await {
let _ = send(&tx, "ERROR:INVALID:AUTH");
}
let match_id_parse = text.split(":").collect::<Vec<&str>>()[2].parse::<u32>();
if match_id_parse.is_err() { let _ = send(&tx, "ERROR:INVALID:TERMINATE"); continue; }
terminate_match(match_id_parse?, &sd.matches, &sd.clients, &sd.observers, sd.demo_mode).await;
if !sd.demo_mode && sd.matches.read().await.is_empty() {
let mut tournament_guard = sd.tournament.write().await;
let tourney = tournament_guard.as_mut().unwrap();
tourney.write().await.next(&sd.clients, &sd.matches, &sd.observers).await;
if tourney.read().await.is_completed() {
*tournament_guard = None;
}
}
}
else if text == "TOURNAMENT:START" {
if !auth_check(&sd.admin, addr).await {
let _ = send(&tx, "ERROR:INVALID:AUTH");
}
if sd.tournament.read().await.is_some() || sd.demo_mode {
let _ = send(&tx, "ERROR:INVALID:TOURNAMENT");
continue;
}
let mut clients_guard = sd.clients.write().await;
let mut ready_players = Vec::new();
for (client_addr, client_guard) in clients_guard.iter_mut() {
if client_guard.read().await.ready {
ready_players.push(*client_addr);
}
}
if ready_players.len() < 3 {
let _ = send(&tx, "ERROR:INVALID:TOURNAMENT");
continue;
}
drop(clients_guard);
let mut tourney = match sd.tournament_type.as_str() {
"round_robin" => RoundRobin::new(&ready_players),
&_ => RoundRobin::new(&ready_players),
};
tourney.start(&sd.clients, &sd.matches).await;
let mut tournament_guard = sd.tournament.write().await;
*tournament_guard = Some(Arc::new(RwLock::new(tourney)));
let _ = send(&tx, "TOURNAMENT:START:ACK");
}
else if text == "TOURNAMENT:CANCEL" {
if !auth_check(&sd.admin, addr).await {
let _ = send(&tx, "ERROR:INVALID:AUTH");
}
if sd.tournament.read().await.is_none() || sd.demo_mode {
let _ = send(&tx, "ERROR:INVALID:TOURNAMENT");
continue;
}
let mut tournament_guard = sd.tournament.write().await;
let tourney = tournament_guard.as_mut().unwrap();
tourney.write().await.cancel(&sd.clients, &sd.matches, &sd.observers).await;
*tournament_guard = None;
let _ = send(&tx, "TOURNAMENT:CANCEL:ACK");
}
else if text.starts_with("TOURNAMENT:WAIT:") {
if !auth_check(&sd.admin, addr).await {
let _ = send(&tx, "ERROR:INVALID:AUTH");
}
let new_timeout = text.split(":").collect::<Vec<&str>>()[2].parse::<f64>()?;
*sd.waiting_timeout.write().await = (new_timeout * 1000.0) as u64;
}
else if text == "GET:MOVE_WAIT" {
let mut msg = "GET:MOVE_WAIT:".to_string();
msg += &(*sd.waiting_timeout.read().await as f64 / 1000f64).to_string();
let _ = send(&tx, &msg);
}
else if text == "GET:TOURNAMENT_STATUS" {
let status = sd.tournament.read().await.is_some();
if sd.demo_mode {
let _ = send(&tx, "GET:TOURNAMENT_STATUS:DEMO");
} else {
let mut msg = "GET:TOURNAMENT_STATUS:".to_string();
msg += status.to_string().as_str();
let _ = send(&tx, &msg);
}
}
else {
let _ = send(&tx, "ERROR:UNKNOWN");
}
}
Ok(Message::Close(_)) => {
info!("Client {} disconnected", addr);
break;
}
Ok(Message::Binary(_)) => { let _ = send(&tx, "ERROR:UNKNOWN"); }
Ok(_) => {}, // Ping packets, we can ignore, they get handled for us
Ok(Message::Binary(_)) => {
let _ = send(&tx, "ERROR:UNKNOWN");
}
Ok(_) => {} // Ping packets, we can ignore, they get handled for us
Err(e) => {
error!("WebSocket error for {}: {}", addr, e);
break;
},
}
}
}
@@ -619,25 +245,32 @@ async fn handle_connection(
send_task.abort();
// Remove and terminate any matches
// We may not be a client disconnecting, do this check
let clients_guard = sd.clients.read().await;
if clients_guard.get(&addr).is_some() {
let client = clients_guard.get(&addr).unwrap().read().await;
let username = client.username.clone();
if let Some(match_id) = client.current_match {
drop(client);
terminate_match(match_id, &sd.matches, &sd.clients, &sd.observers, sd.demo_mode).await;
} else {
drop(client);
}
// We may not be a client disconnecting, do this check
let clients_guard = sd.clients.read().await;
if clients_guard.get(&addr).is_some() {
let client = clients_guard.get(&addr).unwrap().read().await;
let username = client.username.clone();
if let Some(match_id) = client.current_match {
drop(client);
terminate_match(
match_id,
&sd.matches,
&sd.clients,
&sd.observers,
sd.demo_mode,
)
.await;
} else {
drop(client);
}
drop(clients_guard);
drop(clients_guard);
sd.clients.write().await.remove(&addr);
sd.usernames.write().await.remove(&username);
}
sd.clients.write().await.remove(&addr);
sd.usernames.write().await.remove(&username);
}
sd.observers.write().await.remove(&addr);
sd.observers.write().await.remove(&addr);
let mut admin_guard = sd.admin.write().await;
if let Some(admin_addr) = *admin_guard {
@@ -651,55 +284,3 @@ async fn handle_connection(
Ok(())
}
fn end_game_check(board: &[Vec<Color>]) -> (Color, bool) {
let mut result = (Color::None, false);
let mut any_empty = true;
for x in 0..7 {
for y in 0..6 {
let color = board[x][y].clone();
let mut horizontal_end = true;
let mut vertical_end = true;
let mut diagonal_end_up = true;
let mut diagonal_end_down = true;
if any_empty && color == Color::None {
any_empty = false;
}
for i in 0..4 {
if x + i >= 7 || board[x + i][y] != color && horizontal_end {
horizontal_end = false;
}
if y + i >= 6 || board[x][y + i] != color && vertical_end {
vertical_end = false;
}
if x + i >= 7 || y + i >= 6 || board[x + i][y + i] != color && diagonal_end_up {
diagonal_end_up = false;
}
if x + i >= 7 || (y as i32 - i as i32) < 0 ||
board[x + i][y - i] != color && diagonal_end_down {
diagonal_end_down = false;
}
}
if horizontal_end || vertical_end || diagonal_end_up || diagonal_end_down {
result = (color.clone(), false);
break;
}
}
if result.0 != Color::None {
break;
}
}
if any_empty && result.0 == Color::None {
result.1 = true;
}
result
}