feat: huge refactor to data acessing, some API changes

This commit is contained in:
2026-03-23 14:52:53 -04:00
Unverified
parent c5738741f1
commit 12c5c675e2
6 changed files with 258 additions and 323 deletions

View File

@@ -17,24 +17,20 @@ pub mod server;
pub mod tournaments; pub mod tournaments;
pub mod types; pub mod types;
pub type Clients = Arc<RwLock<HashMap<SocketAddr, Arc<RwLock<Client>>>>>; pub type Clients = Arc<RwLock<HashMap<String, Arc<RwLock<Client>>>>>;
pub type Usernames = Arc<RwLock<HashMap<String, SocketAddr>>>; pub type Usernames = Arc<RwLock<HashMap<SocketAddr, String>>>;
pub type Observers = Arc<RwLock<HashMap<SocketAddr, UnboundedSender<Message>>>>; pub type Observers = Arc<RwLock<HashMap<SocketAddr, UnboundedSender<Message>>>>;
pub type Matches = Arc<RwLock<HashMap<u32, Arc<RwLock<Match>>>>>; pub type Matches = Arc<RwLock<HashMap<u32, Arc<RwLock<Match>>>>>;
pub type Reservations = Arc<RwLock<Vec<(String, String)>>>; pub type Reservations = Arc<RwLock<Vec<(String, String)>>>;
pub type WrappedTournament = Arc<RwLock<Option<Arc<RwLock<dyn Tournament + Send + Sync>>>>>; pub type WrappedTournament = Arc<RwLock<Option<Arc<RwLock<dyn Tournament + Send + Sync>>>>>;
pub const SERVER_PLAYER_USERNAME: &str = "The Server"; pub const SERVER_PLAYER_USERNAME: &str = "The Server";
pub const SERVER_PLAYER_ADDR: &str = "127.0.0.1:6666"; // pub const SERVER_PLAYER_ADDR: &str = "127.0.0.1:6666";
pub async fn broadcast_message(observers: &Observers, addrs: &Vec<SocketAddr>, msg: &str) { pub async fn broadcast_message(observers: &Observers, msg: &str) {
for addr in addrs { let observer_guard = observers.read().await;
let observers_guard = observers.read().await; for tx in observer_guard.values() {
let tx = observers_guard.get(addr); let _ = send(tx, msg);
if tx.is_none() {
continue;
}
let _ = send(tx.unwrap(), msg);
} }
} }

View File

@@ -49,10 +49,7 @@ async fn handle_connection(
let ws_stream = accept_async(stream).await?; let ws_stream = accept_async(stream).await?;
let (mut ws_sender, mut ws_receiver) = ws_stream.split(); let (mut ws_sender, mut ws_receiver) = ws_stream.split();
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Message>();
// Store the client
sd.observers.write().await.insert(addr, tx.clone());
// Spawn task to handle outgoing messages // Spawn task to handle outgoing messages
let send_task = tokio::spawn(async move { let send_task = tokio::spawn(async move {
@@ -99,6 +96,12 @@ async fn handle_connection(
let _ = send(&tx, e.to_string().as_str()); let _ = send(&tx, e.to_string().as_str());
} }
} }
"OBSERVE" => {
if let Err(e) = sd.handle_observe(addr, tx.clone()).await {
error!("handle_observe: {}", e);
let _ = send(&tx, e.to_string().as_str());
}
}
"READY" => { "READY" => {
if let Err(e) = sd.handle_ready(addr, tx.clone()).await { if let Err(e) = sd.handle_ready(addr, tx.clone()).await {
error!("handle_ready: {}", e); error!("handle_ready: {}", e);
@@ -303,24 +306,28 @@ async fn handle_connection(
// Remove and terminate any matches // Remove and terminate any matches
// We may not be a client disconnecting, do this check // We may not be a client disconnecting, do this check
let clients_guard = sd.clients.read().await; let clients_guard = sd.clients.read().await;
if clients_guard.get(&addr).is_some() { for client in clients_guard.values() {
let client = clients_guard.get(&addr).unwrap().read().await; let client = client.read().await;
let username = client.username.clone(); if client.addr == addr {
let tournament_guard = sd.tournament.read().await; let username = client.username.clone();
if client.current_match.is_some() { let tournament_guard = sd.tournament.read().await;
sd.disconnected_clients.write().await.push(username.clone()); if client.current_match.is_some() {
} else if tournament_guard.is_some() {
let tourney = tournament_guard.clone().unwrap();
if tourney.read().await.contains_player(addr) {
sd.disconnected_clients.write().await.push(username.clone()); sd.disconnected_clients.write().await.push(username.clone());
} else if tournament_guard.is_some() {
let tourney = tournament_guard.clone().unwrap();
if tourney.read().await.contains_player(username.clone()) {
sd.disconnected_clients.write().await.push(username.clone());
}
} }
drop(client);
drop(clients_guard);
sd.clients.write().await.remove(&username);
sd.usernames.write().await.remove(&addr);
break;
} }
drop(client);
drop(clients_guard);
sd.clients.write().await.remove(&addr);
sd.usernames.write().await.remove(&username);
} }
sd.observers.write().await.remove(&addr); sd.observers.write().await.remove(&addr);

View File

@@ -63,31 +63,23 @@ impl Server {
} }
let clients_guard = self.clients.read().await; let clients_guard = self.clients.read().await;
let mut reconnecting_client = None; let existing_client = clients_guard.get(&requested_username).cloned();
for client in clients_guard.values() { if existing_client.is_some() && !reconnecting {
if requested_username == client.read().await.username { return Err(anyhow::anyhow!(format!(
if reconnecting { "ERROR:INVALID:ID:{}",
reconnecting_client = Some(client.clone()); requested_username
break; )));
}
return Err(anyhow::anyhow!(format!(
"ERROR:INVALID:ID:{}",
requested_username
)));
}
} }
drop(clients_guard); drop(clients_guard);
self.remove_observer_from_all_matches(addr).await;
self.observers.write().await.remove(&addr); self.observers.write().await.remove(&addr);
self.usernames.write().await.insert(requested_username.clone(), addr); self.usernames.write().await.insert(addr, requested_username.clone());
let _ = send(&tx, "CONNECT:ACK"); let _ = send(&tx, "CONNECT:ACK");
if !reconnecting { if !reconnecting {
self.clients.write().await.insert( self.clients.write().await.insert(
addr.to_string().parse()?, requested_username.clone(),
Arc::new(RwLock::new(Client::new( Arc::new(RwLock::new(Client::new(
requested_username, requested_username,
tx.clone(), tx.clone(),
@@ -100,9 +92,8 @@ impl Server {
// reconnecting // reconnecting
self.disconnected_clients.write().await.retain(|name| name != &requested_username); self.disconnected_clients.write().await.retain(|name| name != &requested_username);
let client_guard = reconnecting_client.unwrap(); let client_guard = existing_client.unwrap();
let mut client = client_guard.write().await; let mut client = client_guard.write().await;
let old_addr = client.addr;
client.addr = addr; client.addr = addr;
client.connection = tx.clone(); client.connection = tx.clone();
// I don't think this will fail // I don't think this will fail
@@ -111,18 +102,6 @@ impl Server {
drop(client); drop(client);
let mut clients_guard = self.clients.write().await;
clients_guard.remove(&old_addr);
clients_guard.insert(addr, client_guard.clone());
drop(clients_guard);
let tournament_guard = self.tournament.read().await;
if tournament_guard.is_some() {
let tourney = tournament_guard.clone().unwrap();
tourney.write().await.inform_reconnect(old_addr, addr);
}
drop(tournament_guard);
let matches_guard = self.matches.read().await; let matches_guard = self.matches.read().await;
let mut the_match = matches_guard.get(&match_id).unwrap().write().await; let mut the_match = matches_guard.get(&match_id).unwrap().write().await;
if the_match.demo_mode { if the_match.demo_mode {
@@ -133,10 +112,10 @@ impl Server {
} else { } else {
the_match.ledger.clear(); the_match.ledger.clear();
the_match.board = vec![vec![Color::None; 6]; 7]; the_match.board = vec![vec![Color::None; 6]; 7];
let opponent_addr = if the_match.player1 == addr { let opponent_username = if the_match.player1 == requested_username {
the_match.player2 the_match.player2.clone()
} else { } else {
the_match.player1 the_match.player1.clone()
}; };
if the_match.wait_thread.is_some() { if the_match.wait_thread.is_some() {
@@ -148,7 +127,7 @@ impl Server {
} }
let clients_guard = self.clients.read().await; let clients_guard = self.clients.read().await;
let opponent = clients_guard.get(&opponent_addr).unwrap().read().await; let opponent = clients_guard.get(&opponent_username).unwrap().read().await;
let _ = send(&opponent.connection, "GAME:TERMINATED"); let _ = send(&opponent.connection, "GAME:TERMINATED");
let _ = send( let _ = send(
&tx, &tx,
@@ -171,16 +150,11 @@ impl Server {
) -> Result<(), anyhow::Error> { ) -> Result<(), anyhow::Error> {
let clients_guard = self.clients.read().await; let clients_guard = self.clients.read().await;
let disconnected_guard = self.disconnected_clients.read().await; let disconnected_guard = self.disconnected_clients.read().await;
let mut found_client = None; let found_client = if disconnected_guard.contains(&requested_username) {
clients_guard.get(&requested_username).cloned()
for client in clients_guard.values() { } else {
if requested_username == client.read().await.username { None
if disconnected_guard.contains(&requested_username) { };
found_client = Some(client.clone());
}
break;
}
}
drop(clients_guard); drop(clients_guard);
drop(disconnected_guard); drop(disconnected_guard);
@@ -188,15 +162,9 @@ impl Server {
if let Some(client_guard) = found_client { if let Some(client_guard) = found_client {
self.disconnected_clients.write().await.retain(|name| name != &requested_username); self.disconnected_clients.write().await.retain(|name| name != &requested_username);
let mut client = client_guard.write().await; let mut client = client_guard.write().await;
let old_addr = client.addr;
client.addr = addr; client.addr = addr;
client.connection = tx.clone(); client.connection = tx.clone();
let mut clients_guard = self.clients.write().await;
clients_guard.remove(&old_addr);
clients_guard.insert(addr, client_guard.clone());
drop(clients_guard);
let _ = send(&tx, "RECONNECT:ACK"); let _ = send(&tx, "RECONNECT:ACK");
let matches_guard = self.matches.read().await; let matches_guard = self.matches.read().await;
@@ -225,18 +193,19 @@ impl Server {
tx: UnboundedSender<Message>, tx: UnboundedSender<Message>,
) -> Result<(), anyhow::Error> { ) -> Result<(), anyhow::Error> {
let clients_guard = self.clients.read().await; let clients_guard = self.clients.read().await;
let client_opt = clients_guard.get(&addr).cloned(); let usernames_guard = self.usernames.read().await;
let username = usernames_guard.get(&addr).cloned();
if client_opt.is_none() { if username.is_none() {
return Err(anyhow::anyhow!("ERROR:INVALID:DISCONNECT")); return Err(anyhow::anyhow!("ERROR:INVALID:DISCONNECT"));
} }
drop(clients_guard); let username = username.unwrap();
let client = clients_guard.get(&username).cloned().unwrap();
let client = client.read().await;
let mut client = client_opt.as_ref().unwrap().write().await; drop(clients_guard);
self.usernames.write().await.remove(&client.username); drop(usernames_guard);
client.ready = false;
client.color = Color::None;
if client.current_match.is_some() { if client.current_match.is_some() {
let match_id = client.current_match.unwrap(); let match_id = client.current_match.unwrap();
@@ -245,51 +214,74 @@ impl Server {
self.terminate_match(match_id).await; self.terminate_match(match_id).await;
} }
self.clients.write().await.remove(&addr); self.clients.write().await.remove(&username);
self.observers.write().await.insert(addr, tx.clone()); self.usernames.write().await.remove(&addr);
let _ = send(&tx, "DISCONNECT:ACK"); let _ = send(&tx, "DISCONNECT:ACK");
Ok(()) Ok(())
} }
pub async fn handle_observe(
&self,
addr: SocketAddr,
tx: UnboundedSender<Message>,
) -> Result<(), anyhow::Error> {
if self.usernames.read().await.get(&addr).cloned().is_some() {
return Err(anyhow::anyhow!("ERROR:INVALID:OBSERVE"));
}
let mut observers_guard = self.observers.write().await;
if observers_guard.remove(&addr).is_some() {
let _ = send(&tx, "OBSERVE:ACK:0");
} else {
observers_guard.insert(addr, tx.clone());
let _ = send(&tx, "OBSERVE:ACK:1");
}
Ok(())
}
pub async fn handle_ready( pub async fn handle_ready(
&self, &self,
addr: SocketAddr, addr: SocketAddr,
tx: UnboundedSender<Message>, tx: UnboundedSender<Message>,
) -> Result<(), anyhow::Error> { ) -> Result<(), anyhow::Error> {
let clients_guard = self.clients.read().await; let clients_guard = self.clients.read().await;
if clients_guard.get(&addr).is_none() { let username = self.usernames.read().await.get(&addr).cloned();
if username.is_none() {
return Err(anyhow::anyhow!("ERROR:INVALID")); return Err(anyhow::anyhow!("ERROR:INVALID"));
} }
if clients_guard.get(&addr).unwrap().read().await.ready { let username = username.unwrap();
if clients_guard.get(&username).unwrap().read().await.ready {
return Err(anyhow::anyhow!("ERROR:INVALID:READY")); return Err(anyhow::anyhow!("ERROR:INVALID:READY"));
} }
let mut client = clients_guard.get(&addr).unwrap().write().await; let mut client = clients_guard.get(&username).unwrap().write().await;
let client_username = client.username.clone();
client.ready = true; client.ready = true;
let _ = send(&tx, "READY:ACK"); let _ = send(&tx, "READY:ACK");
drop(client); drop(client);
drop(clients_guard); drop(clients_guard);
if let Some(opponent_addr) = self.find_reservation_opponent(client_username).await { if let Some(opponent_username) = self.find_reservation_opponent(&username).await {
let clients_guard = self.clients.read().await; let clients_guard = self.clients.read().await;
let mut client = clients_guard.get(&addr).unwrap().write().await; let mut client = clients_guard.get(&username).unwrap().write().await;
let mut opponent = clients_guard.get(&opponent_addr).unwrap().write().await; let mut opponent = clients_guard.get(&opponent_username).unwrap().write().await;
let match_id: u32 = gen_match_id(&self.matches).await; let match_id: u32 = gen_match_id(&self.matches).await;
let new_match = Arc::new(RwLock::new(Match::new( let new_match = Arc::new(RwLock::new(Match::new(
match_id, match_id,
addr, username.clone(),
opponent_addr, opponent_username,
false, false,
))); )));
self.matches.write().await.insert(match_id, new_match.clone()); self.matches.write().await.insert(match_id, new_match.clone());
client.ready = false; client.ready = false;
client.current_match = Some(match_id); client.current_match = Some(match_id);
client.color = if new_match.read().await.player1 == addr { client.color = if new_match.read().await.player1 == username {
let _ = send(&tx, "GAME:START:1"); let _ = send(&tx, "GAME:START:1");
let _ = send(&opponent.connection, "GAME:START:0"); let _ = send(&opponent.connection, "GAME:START:0");
Color::Red Color::Red
@@ -313,26 +305,56 @@ impl Server {
} }
let clients_guard = self.clients.read().await; let clients_guard = self.clients.read().await;
let mut client = clients_guard.get(&addr).unwrap().write().await; let mut client = clients_guard.get(&username).unwrap().write().await;
let is_demo_mode = self.demo_mode.read().await.clone(); let is_demo_mode = self.demo_mode.read().await.clone();
if is_demo_mode { if is_demo_mode {
let match_id: u32 = gen_match_id(&self.matches).await; let match_id: u32 = gen_match_id(&self.matches).await;
let new_match = Arc::new(RwLock::new(Match::new( let new_match = Arc::new(RwLock::new(Match::new(
match_id, match_id,
addr.to_string().parse()?, username.clone(),
SERVER_PLAYER_ADDR.to_string().parse()?, SERVER_PLAYER_USERNAME.to_string(),
is_demo_mode, is_demo_mode,
))); )));
self.matches.write().await.insert(match_id, new_match.clone()); self.matches.write().await.insert(match_id, new_match.clone());
client.ready = false; client.ready = false;
client.current_match = Some(match_id); client.current_match = Some(match_id);
client.color = if new_match.read().await.player1 == addr { client.color = if new_match.read().await.player1 == username {
let _ = send(&tx, "GAME:START:1"); let _ = send(&tx, "GAME:START:1");
Color::Red Color::Red
} else { } else {
let _ = send(&tx, "GAME:START:0"); let _ = send(&tx, "GAME:START:0");
Color::Yellow Color::Yellow
}; };
if client.color == Color::Yellow {
let default_waiting_time = *self.waiting_timeout.read().await;
let demo_move = {
let mut the_match = new_match.write().await;
let opening_move = random_move(&the_match.board);
the_match.ledger.push((Color::Red, opening_move, Instant::now()));
the_match.place_token(Color::Red, opening_move);
opening_move
};
let observers = self.observers.clone();
let client_tx = tx.clone();
let wait_match_id = match_id;
new_match.write().await.wait_thread = Some(tokio::spawn(async move {
tokio::time::sleep(tokio::time::Duration::from_millis(default_waiting_time)).await;
let _ = send(&client_tx, &format!("OPPONENT:{}", demo_move));
let observers_guard = observers.read().await;
let msg = format!(
"GAME:{}:MOVE:{}:{}",
wait_match_id, SERVER_PLAYER_USERNAME, demo_move
);
for (_, tx) in observers_guard.iter() {
let _ = send(tx, &msg);
}
}));
}
} }
Ok(()) Ok(())
@@ -345,13 +367,20 @@ impl Server {
column: usize, column: usize,
) -> Result<(), anyhow::Error> { ) -> Result<(), anyhow::Error> {
let clients_guard = self.clients.read().await; let clients_guard = self.clients.read().await;
let client_opt = clients_guard.get(&addr); let usernames_guard = self.usernames.read().await;
let username = usernames_guard.get(&addr).cloned();
// Check if client is valid if username.is_none() {
if client_opt.is_none() || client_opt.unwrap().read().await.current_match.is_none() { return Err(anyhow::anyhow!("ERROR:INVALID:MOVE"));
}
let username = username.unwrap();
let client = clients_guard.get(&username).unwrap().read().await;
// Check if client is valid
if client.current_match.is_none() {
return Err(anyhow::anyhow!("ERROR:INVALID:MOVE")); return Err(anyhow::anyhow!("ERROR:INVALID:MOVE"));
} }
let client = client_opt.unwrap().read().await;
let matches_guard = self.matches.read().await; let matches_guard = self.matches.read().await;
let current_match = matches_guard.get(&client.current_match.unwrap()).unwrap().read().await; let current_match = matches_guard.get(&client.current_match.unwrap()).unwrap().read().await;
@@ -360,13 +389,13 @@ impl Server {
let mut result = None; let mut result = None;
if !current_match.demo_mode { if !current_match.demo_mode {
let opponent_addr = if addr == current_match.player1 { let opponent_username = if username == current_match.player1 {
current_match.player2 current_match.player2.clone()
} else { } else {
current_match.player1 current_match.player1.clone()
}; };
result = Some(clients_guard.get(&opponent_addr).cloned().unwrap()); result = Some(clients_guard.get(&opponent_username).cloned().unwrap());
} }
result result
@@ -374,7 +403,7 @@ impl Server {
// Check if it's their move // Check if it's their move
let mut invalid = false; let mut invalid = false;
if (current_match.ledger.is_empty() && current_match.player1 != addr) if (current_match.ledger.is_empty() && current_match.player1 != username)
|| (current_match.ledger.last().is_some() || (current_match.ledger.last().is_some()
&& current_match.ledger.last().unwrap().0 == client.color) && current_match.ledger.last().unwrap().0 == client.color)
{ {
@@ -404,7 +433,6 @@ impl Server {
if invalid { if invalid {
let current_match_id = current_match.id; let current_match_id = current_match.id;
let is_demo_mode = current_match.demo_mode; let is_demo_mode = current_match.demo_mode;
let viewers = current_match.viewers.clone();
drop(current_match); drop(current_match);
drop(matches_guard); drop(matches_guard);
@@ -420,22 +448,27 @@ impl Server {
let _ = send(&tx, "GAME:LOSS"); let _ = send(&tx, "GAME:LOSS");
let _ = send(&opponent.connection, "GAME:WINS"); let _ = send(&opponent.connection, "GAME:WINS");
self.broadcast_message(&viewers, &format!("GAME:WIN:{}", opponent.username)).await; self
.broadcast(&format!(
"GAME:{}:WIN:{}",
current_match_id, opponent.username
))
.await;
opponent.current_match = None; opponent.current_match = None;
opponent.color = Color::None; opponent.color = Color::None;
let opponent_addr = opponent.addr; let opponent_username = opponent.username.clone();
drop(opponent); drop(opponent);
let mut clients_guard = self.clients.write().await; let mut clients_guard = self.clients.write().await;
let mut client = clients_guard.get_mut(&addr).unwrap().write().await; let mut client = clients_guard.get_mut(&username).unwrap().write().await;
client.current_match = None; client.current_match = None;
client.color = Color::None; client.color = Color::None;
drop(client); drop(client);
let mut tournament_guard = self.tournament.write().await; let mut tournament_guard = self.tournament.write().await;
let tourney = tournament_guard.as_mut().unwrap(); let tourney = tournament_guard.as_mut().unwrap();
tourney.write().await.inform_winner(opponent_addr, false); tourney.write().await.inform_winner(opponent_username, false);
drop(tournament_guard); drop(tournament_guard);
self.matches.write().await.remove(&current_match_id).unwrap(); self.matches.write().await.remove(&current_match_id).unwrap();
@@ -449,10 +482,11 @@ impl Server {
timeout_thread.abort(); timeout_thread.abort();
} }
let mut viewer_messages = Vec::new(); let mut observer_messages = Vec::new();
let viewers = current_match.viewers.clone(); observer_messages.push(format!(
"GAME:{}:MOVE:{}:{}",
viewer_messages.push(format!("GAME:MOVE:{}:{}", client.username, column)); current_match.id, client.username, column
));
// Check game end conditions // Check game end conditions
let (winner, filled) = current_match.end_game_check(); let (winner, filled) = current_match.end_game_check();
@@ -465,7 +499,7 @@ impl Server {
let opponent = opponent.read().await; let opponent = opponent.read().await;
let _ = send(&opponent.connection, "GAME:LOSS"); let _ = send(&opponent.connection, "GAME:LOSS");
} }
viewer_messages.push(format!("GAME:WIN:{}", client.username)); observer_messages.push(format!("GAME:{}:WIN:{}", current_match.id, client.username));
} else if filled { } else if filled {
let _ = send(&tx, "GAME:DRAW"); let _ = send(&tx, "GAME:DRAW");
if !current_match.demo_mode { if !current_match.demo_mode {
@@ -473,11 +507,15 @@ impl Server {
let opponent = opponent.read().await; let opponent = opponent.read().await;
let _ = send(&opponent.connection, "GAME:DRAW"); let _ = send(&opponent.connection, "GAME:DRAW");
} }
viewer_messages.push("GAME:DRAW".to_string()); observer_messages.push(format!("GAME:{}:DRAW", current_match.id));
} }
// remove match from matchmaker // remove match from matchmaker
if winner != Color::None || filled { if winner != Color::None || filled {
for msg in observer_messages {
self.broadcast(&msg).await;
}
let current_match_id = current_match.id; let current_match_id = current_match.id;
let is_demo_mode = current_match.demo_mode; let is_demo_mode = current_match.demo_mode;
@@ -486,7 +524,7 @@ impl Server {
drop(clients_guard); drop(clients_guard);
let clients_guard = self.clients.read().await; let clients_guard = self.clients.read().await;
let mut client = clients_guard.get(&addr).unwrap().write().await; let mut client = clients_guard.get(&username).unwrap().write().await;
client.current_match = None; client.current_match = None;
client.color = Color::None; client.color = Color::None;
drop(client); drop(client);
@@ -507,7 +545,7 @@ impl Server {
let mut tournament_guard = self.tournament.write().await; let mut tournament_guard = self.tournament.write().await;
let tourney = tournament_guard.as_mut().unwrap(); let tourney = tournament_guard.as_mut().unwrap();
tourney.write().await.inform_winner(addr, filled); tourney.write().await.inform_winner(username.clone(), filled);
tourney.write().await.next(&self).await; tourney.write().await.next(&self).await;
if tourney.read().await.is_completed() { if tourney.read().await.is_completed() {
*tournament_guard = None; *tournament_guard = None;
@@ -548,6 +586,7 @@ impl Server {
let observers = self.observers.clone(); let observers = self.observers.clone();
let opponent_move = opponent.clone(); let opponent_move = opponent.clone();
let client_tx = tx.clone(); let client_tx = tx.clone();
let wait_match_id = current_match.id;
if current_match.demo_mode { if current_match.demo_mode {
current_match.ledger.push((!client.color, demo_move, Instant::now())); current_match.ledger.push((!client.color, demo_move, Instant::now()));
current_match.place_token(!client.color, demo_move); current_match.place_token(!client.color, demo_move);
@@ -565,19 +604,21 @@ impl Server {
); );
} }
for msg in viewer_messages { for msg in observer_messages {
broadcast_message(&observers, &viewers, &msg).await; broadcast_message(&observers, &msg).await;
} }
if demo_mode && no_winner { if demo_mode && no_winner {
tokio::time::sleep(tokio::time::Duration::from_millis(default_waiting_time)).await; tokio::time::sleep(tokio::time::Duration::from_millis(default_waiting_time)).await;
let _ = send(&client_tx, &format!("OPPONENT:{}", demo_move)); let _ = send(&client_tx, &format!("OPPONENT:{}", demo_move));
broadcast_message( let observers_guard = observers.read().await;
&observers, let msg = format!(
&viewers, "GAME:{}:MOVE:{}:{}",
&format!("GAME:MOVE:{}:{}", SERVER_PLAYER_USERNAME, demo_move), wait_match_id, SERVER_PLAYER_USERNAME, demo_move
) );
.await; for (_, tx) in observers_guard.iter() {
let _ = send(tx, &msg);
}
} }
})); }));
@@ -589,9 +630,7 @@ impl Server {
let ledger_size = current_match.ledger.len(); let ledger_size = current_match.ledger.len();
let client_username = client.username.clone(); let client_username = client.username.clone();
let client_tx = tx.clone(); let client_tx = tx.clone();
let client_addr = addr.clone();
let observers = self.observers.clone(); let observers = self.observers.clone();
let viewers = current_match.viewers.clone();
let opponent_move = opponent.clone(); let opponent_move = opponent.clone();
current_match.timeout_thread = Some(tokio::spawn(async move { current_match.timeout_thread = Some(tokio::spawn(async move {
if demo_mode { if demo_mode {
@@ -611,15 +650,14 @@ impl Server {
let opponent = opponent.read().await; let opponent = opponent.read().await;
let _ = send(&opponent.connection, "GAME:LOSS"); let _ = send(&opponent.connection, "GAME:LOSS");
drop(opponent); drop(opponent);
broadcast_message( let observers_guard = observers.read().await;
&observers, let msg = format!("GAME:{}:WIN:{}", match_id, client_username);
&viewers, for (_, tx) in observers_guard.iter() {
&format!("GAME:WIN:{}", client_username), let _ = send(tx, &msg);
) }
.await;
let mut clients_guard = clients.write().await; let mut clients_guard = clients.write().await;
let mut client = clients_guard.get_mut(&client_addr).unwrap().write().await; let mut client = clients_guard.get_mut(&client_username).unwrap().write().await;
client.current_match = None; client.current_match = None;
client.color = Color::None; client.color = Color::None;
drop(client); drop(client);
@@ -632,7 +670,7 @@ impl Server {
let mut tournament_guard = tournament.write().await; let mut tournament_guard = tournament.write().await;
let tourney = tournament_guard.as_mut().unwrap(); let tourney = tournament_guard.as_mut().unwrap();
tourney.write().await.inform_winner(client_addr, false); tourney.write().await.inform_winner(client_username, false);
drop(tournament_guard); drop(tournament_guard);
matches.write().await.remove(&match_id).unwrap(); matches.write().await.remove(&match_id).unwrap();
@@ -672,26 +710,15 @@ impl Server {
} }
pub async fn handle_game_list(&self, tx: UnboundedSender<Message>) -> Result<(), anyhow::Error> { pub async fn handle_game_list(&self, tx: UnboundedSender<Message>) -> Result<(), anyhow::Error> {
let clients_guard = self.clients.read().await;
let matches_guard = self.matches.read().await; let matches_guard = self.matches.read().await;
let mut to_send = "GAME:LIST:".to_string(); let mut to_send = "GAME:LIST:".to_string();
for match_guard in matches_guard.values() { for match_guard in matches_guard.values() {
let a_match = match_guard.read().await; let a_match = match_guard.read().await;
let player1 = if a_match.player1.to_string() == SERVER_PLAYER_ADDR {
SERVER_PLAYER_USERNAME.to_string()
} else {
clients_guard.get(&a_match.player1).unwrap().read().await.username.clone()
};
let player2 = if a_match.player2.to_string() == SERVER_PLAYER_ADDR {
SERVER_PLAYER_USERNAME.to_string()
} else {
clients_guard.get(&a_match.player2).unwrap().read().await.username.clone()
};
to_send += a_match.id.to_string().as_str(); to_send += a_match.id.to_string().as_str();
to_send += ","; to_send += ",";
to_send += player1.as_str(); to_send += a_match.player1.as_str();
to_send += ","; to_send += ",";
to_send += player2.as_str(); to_send += a_match.player2.as_str();
to_send += "|"; to_send += "|";
} }
@@ -707,32 +734,16 @@ impl Server {
&self, &self,
tx: UnboundedSender<Message>, tx: UnboundedSender<Message>,
match_id: u32, match_id: u32,
addr: SocketAddr, _addr: SocketAddr,
) -> Result<(), anyhow::Error> { ) -> Result<(), anyhow::Error> {
let result = self.watch(match_id, addr).await;
if result.is_err() {
return Err(anyhow::anyhow!("ERROR:INVALID:WATCH"));
}
let clients_guard = self.clients.read().await;
let matches_guard = self.matches.read().await; let matches_guard = self.matches.read().await;
let the_match = matches_guard.get(&match_id).unwrap().read().await; let the_match = matches_guard.get(&match_id).unwrap().read().await;
let player1 = if !the_match.player1.to_string().eq(SERVER_PLAYER_ADDR) { let player1 = the_match.player1.clone();
clients_guard.get(&the_match.player1).unwrap().read().await.username.clone() let player2 = the_match.player2.clone();
} else {
SERVER_PLAYER_USERNAME.to_string()
};
let player2 = if !the_match.player2.to_string().eq(SERVER_PLAYER_ADDR) {
clients_guard.get(&the_match.player2).unwrap().read().await.username.clone()
} else {
SERVER_PLAYER_USERNAME.to_string()
};
let ledger = the_match.ledger.clone(); let ledger = the_match.ledger.clone();
drop(clients_guard);
drop(the_match); drop(the_match);
drop(matches_guard); drop(matches_guard);
@@ -781,17 +792,15 @@ impl Server {
return Err(anyhow::anyhow!("ERROR:INVALID:AUTH")); return Err(anyhow::anyhow!("ERROR:INVALID:AUTH"));
} }
let usernames_guard = self.usernames.read().await;
let clients_guard = self.clients.read().await; let clients_guard = self.clients.read().await;
let kick_addr_result = usernames_guard.get(&kick_username); let kick_client = clients_guard.get(&kick_username).cloned();
match kick_addr_result { if let Some(client) = kick_client {
Some(kick_addr) => { client.read().await.connection.send(Message::Close(None))?;
let kick_client = clients_guard.get(kick_addr).unwrap().read().await; } else {
kick_client.connection.send(Message::Close(None))?; return Err(anyhow::anyhow!("ERROR:INVALID:KICK"));
}
None => return Err(anyhow::anyhow!("ERROR:INVALID:KICK")),
} }
Ok(()) Ok(())
} }
@@ -862,7 +871,7 @@ impl Server {
timeout_thread.abort(); timeout_thread.abort();
} }
self.broadcast_message(&the_match.viewers, &format!("GAME:WIN:{}", winner_username)).await; self.broadcast(&format!("GAME:{}:WIN:{}", match_id, winner_username)).await;
let clients_guard = self.clients.read().await; let clients_guard = self.clients.read().await;
if the_match.demo_mode { if the_match.demo_mode {
@@ -871,7 +880,7 @@ impl Server {
} else { } else {
"LOSS" "LOSS"
}; };
let mut the_player = if the_match.player1 != SERVER_PLAYER_ADDR.parse()? { let mut the_player = if the_match.player1 != SERVER_PLAYER_USERNAME {
clients_guard.get(&the_match.player1).unwrap().write().await clients_guard.get(&the_match.player1).unwrap().write().await
} else { } else {
clients_guard.get(&the_match.player2).unwrap().write().await clients_guard.get(&the_match.player2).unwrap().write().await
@@ -907,12 +916,6 @@ impl Server {
player2.connection.clone() player2.connection.clone()
}; };
let winner_addr = if player1.username == winner_username {
player1.addr.clone()
} else {
player2.addr.clone()
};
drop(player1); drop(player1);
drop(player2); drop(player2);
drop(clients_guard); drop(clients_guard);
@@ -923,7 +926,7 @@ impl Server {
if self.tournament.read().await.is_some() { if self.tournament.read().await.is_some() {
let mut tournament_guard = self.tournament.write().await; let mut tournament_guard = self.tournament.write().await;
let tourney = tournament_guard.as_mut().unwrap(); let tourney = tournament_guard.as_mut().unwrap();
tourney.write().await.inform_winner(winner_addr, false); tourney.write().await.inform_winner(winner_username, false);
if self.matches.read().await.is_empty() { if self.matches.read().await.is_empty() {
tourney.write().await.next(&self).await; tourney.write().await.next(&self).await;
if tourney.read().await.is_completed() { if tourney.read().await.is_completed() {
@@ -953,9 +956,9 @@ impl Server {
let mut clients_guard = self.clients.write().await; let mut clients_guard = self.clients.write().await;
let mut ready_players = Vec::new(); let mut ready_players = Vec::new();
for (client_addr, client_guard) in clients_guard.iter_mut() { for (username, client_guard) in clients_guard.iter_mut() {
if client_guard.read().await.ready { if client_guard.read().await.ready {
ready_players.push(*client_addr); ready_players.push(username.clone());
} }
} }
@@ -977,7 +980,7 @@ impl Server {
// Clear any pending reservations when a tournament starts // Clear any pending reservations when a tournament starts
self.reservations.write().await.clear(); self.reservations.write().await.clear();
self.broadcast_message_all_observers(&format!("TOURNAMENT:START:{}", tournament_type)).await; self.broadcast(&format!("TOURNAMENT:START:{}", tournament_type)).await;
Ok(()) Ok(())
} }
@@ -995,7 +998,7 @@ impl Server {
tourney.write().await.cancel(&self).await; tourney.write().await.cancel(&self).await;
*tournament_guard = None; *tournament_guard = None;
self.broadcast_message_all_observers("TOURNAMENT:CANCEL").await; self.broadcast("TOURNAMENT:CANCEL").await;
Ok(()) Ok(())
} }
@@ -1091,27 +1094,29 @@ impl Server {
&format!("RESERVATION:ADD:{},{}", player1_username, player2_username), &format!("RESERVATION:ADD:{},{}", player1_username, player2_username),
); );
let player1_addr = self.usernames.read().await.get(&player1_username).cloned();
let player2_addr = self.usernames.read().await.get(&player2_username).cloned();
let clients_guard = self.clients.read().await; let clients_guard = self.clients.read().await;
if player1_addr.is_some() && player2_addr.is_some() { let player1 = clients_guard.get(&player1_username).cloned();
let mut player1 = clients_guard.get(&player1_addr.unwrap()).unwrap().write().await; let player2 = clients_guard.get(&player2_username).cloned();
let mut player2 = clients_guard.get(&player2_addr.unwrap()).unwrap().write().await;
if player1.is_some() && player2.is_some() {
let player1 = player1.unwrap();
let player2 = player2.unwrap();
let mut player1 = player1.write().await;
let mut player2 = player2.write().await;
if player1.ready && player2.ready { if player1.ready && player2.ready {
let match_id: u32 = gen_match_id(&self.matches).await; let match_id: u32 = gen_match_id(&self.matches).await;
let new_match = Arc::new(RwLock::new(Match::new( let new_match = Arc::new(RwLock::new(Match::new(
match_id, match_id,
player1_addr.unwrap(), player1_username.clone(),
player2_addr.unwrap(), player2_username.clone(),
false, false,
))); )));
self.matches.write().await.insert(match_id, new_match.clone()); self.matches.write().await.insert(match_id, new_match.clone());
player1.ready = false; player1.ready = false;
player1.current_match = Some(match_id); player1.current_match = Some(match_id);
player1.color = if new_match.read().await.player1 == player1_addr.unwrap() { player1.color = if new_match.read().await.player1 == player1_username {
let _ = send(&tx, "GAME:START:1"); let _ = send(&tx, "GAME:START:1");
let _ = send(&player2.connection, "GAME:START:0"); let _ = send(&player2.connection, "GAME:START:0");
Color::Red Color::Red
@@ -1186,54 +1191,6 @@ impl Server {
Ok(()) Ok(())
} }
pub async fn watch(&self, new_match_id: u32, addr: SocketAddr) -> Result<(), String> {
let matches_guard = self.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 remove_observer_from_all_matches(&self, addr: SocketAddr) {
let matches_guard = self.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;
}
}
}
pub async fn terminate_match(&self, match_id: u32) { pub async fn terminate_match(&self, match_id: u32) {
let matches_guard = self.matches.read().await; let matches_guard = self.matches.read().await;
let the_match = matches_guard.get(&match_id); let the_match = matches_guard.get(&match_id);
@@ -1253,17 +1210,17 @@ impl Server {
timeout_thread.abort(); timeout_thread.abort();
} }
self.broadcast_message(&the_match.viewers, "GAME:TERMINATED").await; self.broadcast(&format!("GAME:{}:TERMINATED", the_match.id)).await;
let clients_guard = self.clients.read().await; let clients_guard = self.clients.read().await;
if the_match.player1 != SERVER_PLAYER_ADDR.to_string().parse().unwrap() { if the_match.player1 != SERVER_PLAYER_USERNAME.to_string() {
let mut player1 = clients_guard.get(&the_match.player1).unwrap().write().await; let mut player1 = clients_guard.get(&the_match.player1).unwrap().write().await;
let _ = send(&player1.connection, "GAME:TERMINATED"); let _ = send(&player1.connection, "GAME:TERMINATED");
player1.current_match = None; player1.current_match = None;
player1.color = Color::None; player1.color = Color::None;
} }
if the_match.player2 != SERVER_PLAYER_ADDR.to_string().parse().unwrap() { if the_match.player2 != SERVER_PLAYER_USERNAME.to_string() {
let mut player2 = clients_guard.get(&the_match.player2).unwrap().write().await; let mut player2 = clients_guard.get(&the_match.player2).unwrap().write().await;
let _ = send(&player2.connection, "GAME:TERMINATED"); let _ = send(&player2.connection, "GAME:TERMINATED");
player2.current_match = None; player2.current_match = None;
@@ -1277,20 +1234,9 @@ impl Server {
self.matches.write().await.remove(&match_id); self.matches.write().await.remove(&match_id);
} }
pub async fn broadcast_message(&self, addrs: &Vec<SocketAddr>, msg: &str) { pub async fn broadcast(&self, msg: &str) {
for addr in addrs {
let observers_guard = self.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(&self, msg: &str) {
let observers_guard = self.observers.read().await; let observers_guard = self.observers.read().await;
for (_, tx) in observers_guard.iter() { for tx in observers_guard.values() {
let _ = send(tx, msg); let _ = send(tx, msg);
} }
} }
@@ -1302,24 +1248,24 @@ impl Server {
true true
} }
pub async fn find_reservation_opponent(&self, username: String) -> Option<SocketAddr> { pub async fn find_reservation_opponent(&self, username: &String) -> Option<String> {
let reservations_guard = self.reservations.read().await; let reservations_guard = self.reservations.read().await;
for (player1, player2) in reservations_guard.iter() { for (player1, player2) in reservations_guard.iter() {
if player1 == &username || player2 == &username { if player1 == username || player2 == username {
let opponent_username = if player1 == &username { let opponent_username = if player1 == username {
player2 player2
} else { } else {
player1 player1
}; };
let usernames_guard = self.usernames.read().await; let usernames_guard = self.usernames.read().await;
if let Some(opponent_addr) = usernames_guard.get(opponent_username) { return usernames_guard.iter().find_map(|(_, client_username)| {
let clients_guard = self.clients.read().await; if client_username == opponent_username {
let opponent = clients_guard.get(opponent_addr).unwrap().read().await; Some(opponent_username.clone())
if opponent.ready { } else {
return Some(*opponent_addr); None
} }
} });
} }
} }

View File

@@ -1,5 +1,3 @@
use std::net::SocketAddr;
use async_trait::async_trait; use async_trait::async_trait;
use crate::server::Server; use crate::server::Server;
@@ -9,15 +7,14 @@ pub use round_robin::RoundRobin;
#[async_trait] #[async_trait]
pub trait Tournament { pub trait Tournament {
fn new(ready_players: &[SocketAddr]) -> Self fn new(ready_players: &[String]) -> Self
where where
Self: Sized; Self: Sized;
async fn next(&mut self, server: &Server); async fn next(&mut self, server: &Server);
async fn start(&mut self, server: &Server); async fn start(&mut self, server: &Server);
async fn cancel(&mut self, server: &Server); async fn cancel(&mut self, server: &Server);
fn inform_winner(&mut self, winner: SocketAddr, is_tie: bool); fn inform_winner(&mut self, winner: String, is_tie: bool);
fn inform_reconnect(&mut self, old_addr: SocketAddr, new_addr: SocketAddr); fn contains_player(&self, username: String) -> bool;
fn contains_player(&self, addr: SocketAddr) -> bool;
fn is_completed(&self) -> bool; fn is_completed(&self) -> bool;
fn get_type(&self) -> String; fn get_type(&self) -> String;
} }

View File

@@ -1,4 +1,4 @@
use std::{collections::HashMap, net::SocketAddr}; use std::collections::HashMap;
use async_trait::async_trait; use async_trait::async_trait;
@@ -9,7 +9,7 @@ type ID = u32;
#[derive(Clone)] #[derive(Clone)]
pub struct RoundRobin { pub struct RoundRobin {
pub players: HashMap<ID, (SocketAddr, Score)>, pub players: HashMap<ID, (String, Score)>,
pub top_half: Vec<ID>, pub top_half: Vec<ID>,
pub bottom_half: Vec<ID>, pub bottom_half: Vec<ID>,
pub is_completed: bool, pub is_completed: bool,
@@ -19,29 +19,29 @@ impl RoundRobin {
async fn create_matches(&self, clients: &Clients, matches: &Matches) { async fn create_matches(&self, clients: &Clients, matches: &Matches) {
let clients_guard = clients.read().await; let clients_guard = clients.read().await;
for (i, id) in self.top_half.iter().enumerate() { for (i, id) in self.top_half.iter().enumerate() {
let player1_addr = self.players.get(id).unwrap(); let player1_username = self.players.get(id).unwrap();
let player2_addr = self.players.get(self.bottom_half.get(i).unwrap()); let player2_username = self.players.get(self.bottom_half.get(i).unwrap());
if player2_addr.is_none() { if player2_username.is_none() {
continue; continue;
} }
let player2_addr = player2_addr.unwrap(); let player2_addr = player2_username.unwrap();
let match_id: u32 = gen_match_id(matches).await; let match_id: u32 = gen_match_id(matches).await;
let new_match = Arc::new(RwLock::new(Match::new( let new_match = Arc::new(RwLock::new(Match::new(
match_id, match_id,
player1_addr.0, player1_username.0.clone(),
player2_addr.0, player2_addr.0.clone(),
false, false,
))); )));
let match_guard = new_match.read().await; let match_guard = new_match.read().await;
let mut player1 = clients_guard.get(&player1_addr.0).unwrap().write().await; let mut player1 = clients_guard.get(&player1_username.0).unwrap().write().await;
player1.current_match = Some(match_id); player1.current_match = Some(match_id);
player1.ready = false; player1.ready = false;
if match_guard.player1 == player1_addr.0 { if match_guard.player1 == player1_username.0 {
player1.color = Color::Red; player1.color = Color::Red;
let _ = send(&player1.connection, "GAME:START:1"); let _ = send(&player1.connection, "GAME:START:1");
} else { } else {
@@ -73,7 +73,7 @@ impl RoundRobin {
#[async_trait] #[async_trait]
impl Tournament for RoundRobin { impl Tournament for RoundRobin {
fn new(ready_players: &[SocketAddr]) -> RoundRobin { fn new(ready_players: &[String]) -> RoundRobin {
let mut result = RoundRobin { let mut result = RoundRobin {
players: HashMap::new(), players: HashMap::new(),
top_half: Vec::new(), top_half: Vec::new(),
@@ -84,7 +84,7 @@ impl Tournament for RoundRobin {
let size = ready_players.len(); let size = ready_players.len();
for (id, player) in ready_players.iter().enumerate() { for (id, player) in ready_players.iter().enumerate() {
result.players.insert(id as u32, (*player, 0)); result.players.insert(id as u32, (player.clone(), 0));
} }
for i in 0..size / 2 { for i in 0..size / 2 {
@@ -98,31 +98,22 @@ impl Tournament for RoundRobin {
result result
} }
fn inform_winner(&mut self, winner: SocketAddr, is_tie: bool) { fn inform_winner(&mut self, winner: String, is_tie: bool) {
if is_tie { if is_tie {
return; return;
} }
for (_, player_addr) in self.players.iter_mut() { for (_, username) in self.players.iter_mut() {
if player_addr.0 == winner { if username.0 == winner {
player_addr.1 += 1; username.1 += 1;
break; break;
} }
} }
} }
fn inform_reconnect(&mut self, old_addr: SocketAddr, new_addr: SocketAddr) { fn contains_player(&self, username: String) -> bool {
for (_, (player_addr, _)) in self.players.iter_mut() { for (_, (player_username, _)) in self.players.iter() {
if *player_addr == old_addr { if *player_username == username {
*player_addr = new_addr;
break;
}
}
}
fn contains_player(&self, addr: SocketAddr) -> bool {
for (_, (player_addr, _)) in self.players.iter() {
if *player_addr == addr {
return true; return true;
} }
} }
@@ -167,7 +158,7 @@ impl Tournament for RoundRobin {
} }
message.pop(); message.pop();
server.broadcast_message_all_observers(&message).await; server.broadcast(&message).await;
if self.is_completed() { if self.is_completed() {
// Send scores // Send scores

View File

@@ -61,32 +61,30 @@ pub struct Match {
pub id: u32, pub id: u32,
pub demo_mode: bool, pub demo_mode: bool,
pub board: Vec<Vec<Color>>, pub board: Vec<Vec<Color>>,
pub viewers: Vec<SocketAddr>,
pub ledger: Vec<(Color, usize, Instant)>, pub ledger: Vec<(Color, usize, Instant)>,
pub wait_thread: Option<tokio::task::JoinHandle<()>>, pub wait_thread: Option<tokio::task::JoinHandle<()>>,
pub timeout_thread: Option<tokio::task::JoinHandle<()>>, pub timeout_thread: Option<tokio::task::JoinHandle<()>>,
pub player1: SocketAddr, pub player1: String,
pub player2: SocketAddr, pub player2: String,
} }
impl Match { impl Match {
pub fn new(id: u32, player1: SocketAddr, player2: SocketAddr, demo_mode: bool) -> Match { pub fn new(id: u32, player1: String, player2: String, demo_mode: bool) -> Match {
let first = if rand::rng().random_range(0..=1) == 0 { let (first_player, second_player) = if rand::rng().random_range(0..=1) == 0 {
player1.to_string().parse().unwrap() (player1, player2)
} else { } else {
player2.to_string().parse().unwrap() (player2, player1)
}; };
Match { Match {
id, id,
demo_mode, demo_mode,
board: vec![vec![Color::None; 6]; 7], board: vec![vec![Color::None; 6]; 7],
viewers: Vec::new(),
ledger: Vec::new(), ledger: Vec::new(),
wait_thread: None, wait_thread: None,
timeout_thread: None, timeout_thread: None,
player1: if player1 == first { player1 } else { player2 }, player1: first_player,
player2: if player1 == first { player2 } else { player1 }, player2: second_player,
} }
} }