misc: rustfmt

This commit is contained in:
2025-11-18 14:33:42 -05:00
Unverified
parent 22ffb96271
commit be7aabbe5f
4 changed files with 358 additions and 311 deletions

2
.rustfmt.toml Normal file
View File

@@ -0,0 +1,2 @@
combine_control_expr = false
chain_width = 100

View File

@@ -1,12 +1,13 @@
mod types;
mod random_ai; mod random_ai;
mod types;
use crate::random_ai::random_move;
use crate::types::{Color, Match}; use crate::types::{Color, Match};
use futures_util::{SinkExt, StreamExt}; use futures_util::{SinkExt, StreamExt};
use rand::Rng;
use std::collections::HashMap; use std::collections::HashMap;
use std::net::SocketAddr; use std::net::SocketAddr;
use std::sync::Arc; use std::sync::Arc;
use rand::Rng;
use tokio::net::{TcpListener, TcpStream}; use tokio::net::{TcpListener, TcpStream};
use tokio::sync::mpsc::error::SendError; use tokio::sync::mpsc::error::SendError;
use tokio::sync::mpsc::UnboundedSender; use tokio::sync::mpsc::UnboundedSender;
@@ -14,13 +15,11 @@ use tokio::sync::RwLock;
use tokio_tungstenite::{accept_async, tungstenite::Message}; use tokio_tungstenite::{accept_async, tungstenite::Message};
use tracing::{error, info, warn}; use tracing::{error, info, warn};
use types::Client; use types::Client;
use crate::random_ai::random_move;
type Clients = Arc<RwLock<HashMap<SocketAddr, Arc<RwLock<Client>>>>>; type Clients = Arc<RwLock<HashMap<SocketAddr, Arc<RwLock<Client>>>>>;
type Observers = Arc<RwLock<HashMap<SocketAddr, UnboundedSender<Message>>>>; type Observers = Arc<RwLock<HashMap<SocketAddr, UnboundedSender<Message>>>>;
type Matches = Arc<RwLock<HashMap<u32, Arc<RwLock<Match>>>>>; type Matches = Arc<RwLock<HashMap<u32, Arc<RwLock<Match>>>>>;
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), anyhow::Error> { async fn main() -> Result<(), anyhow::Error> {
// Initialize logging // Initialize logging
@@ -46,7 +45,7 @@ async fn main() -> Result<(), anyhow::Error> {
observers.clone(), observers.clone(),
matches.clone(), matches.clone(),
admin.clone(), admin.clone(),
demo_mode demo_mode,
)); ));
} }
@@ -103,15 +102,19 @@ async fn handle_connection(
} }
} }
if is_taken { continue; } if is_taken {
continue;
}
// not taken // not taken
observers.write().await.remove(&addr); observers.write().await.remove(&addr);
clients clients.write().await.insert(
.write().await
.insert(
addr.to_string().parse()?, addr.to_string().parse()?,
Arc::new(RwLock::new(Client::new(requested_username, tx.clone(), addr.to_string().parse()?))) Arc::new(RwLock::new(Client::new(
requested_username,
tx.clone(),
addr.to_string().parse()?,
))),
); );
let _ = send(&tx, "CONNECT:ACK"); let _ = send(&tx, "CONNECT:ACK");
@@ -133,17 +136,17 @@ async fn handle_connection(
if demo_mode { if demo_mode {
let match_id: u32 = rand::rng().random_range(100000..=999999); let match_id: u32 = rand::rng().random_range(100000..=999999);
let new_match = Arc::new(RwLock::new(Match::new(match_id, addr.to_string().parse()?, addr.to_string().parse()?))); let new_match = Arc::new(RwLock::new(Match::new(
match_id,
addr.to_string().parse()?,
addr.to_string().parse()?,
)));
matches.write().await.insert(match_id, new_match.clone()); matches.write().await.insert(match_id, new_match.clone());
clients.write().await.get_mut(&addr).unwrap().write().await.ready = false; clients.write().await.get_mut(&addr).unwrap().write().await.ready = false;
clients clients.write().await.get_mut(&addr).unwrap().write().await.current_match =
.write().await Some(match_id);
.get_mut(&addr).unwrap() clients.write().await.get_mut(&addr).unwrap().write().await.color =
.write().await.current_match = Some(match_id); Color::Red;
clients
.write().await
.get_mut(&addr).unwrap()
.write().await.color = Color::Red;
let _ = send(&tx, "GAME:START:1"); let _ = send(&tx, "GAME:START:1");
} }
} }
@@ -152,7 +155,9 @@ async fn handle_connection(
let client_option = clients_guard.get(&addr); let client_option = clients_guard.get(&addr);
// Check if client is valid // Check if client is valid
if client_option.is_none() || client_option.unwrap().read().await.current_match.is_none() { if client_option.is_none()
|| client_option.unwrap().read().await.current_match.is_none()
{
let _ = send(&tx, "ERROR:INVALID:MOVE"); let _ = send(&tx, "ERROR:INVALID:MOVE");
continue; continue;
} }
@@ -160,22 +165,23 @@ async fn handle_connection(
let client = client_option.unwrap().read().await; let client = client_option.unwrap().read().await;
let matches_guard = matches.read().await; let matches_guard = 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;
let opponent = { let opponent = {
let result = let result = if addr == current_match.player1 {
if addr == current_match.player1 clients_guard.get(&current_match.player2).unwrap().read().await
{ clients_guard.get(&current_match.player2).unwrap().read().await } } else {
else clients_guard.get(&current_match.player1).unwrap().read().await
{ clients_guard.get(&current_match.player1).unwrap().read().await }; };
result result
}; };
// Check if it's their move // Check if it's their move
if (current_match.ledger.is_empty() && if (current_match.ledger.is_empty() && current_match.first != addr)
current_match.first != addr) || || (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)
{ {
let _ = send(&tx, "ERROR:INVALID:MOVE"); let _ = send(&tx, "ERROR:INVALID:MOVE");
continue; continue;
@@ -187,7 +193,11 @@ async fn handle_connection(
drop(matches_guard); drop(matches_guard);
let mut matches_guard = matches.write().await; let mut matches_guard = matches.write().await;
let mut current_match = matches_guard.get_mut(&client.current_match.unwrap()).unwrap().write().await; let mut current_match = matches_guard
.get_mut(&client.current_match.unwrap())
.unwrap()
.write()
.await;
// Check if valid move // Check if valid move
if let Ok(column) = column_parse { if let Ok(column) = column_parse {
@@ -212,7 +222,8 @@ async fn handle_connection(
broadcast_message( broadcast_message(
&current_match.viewers, &current_match.viewers,
&observers, &observers,
&format!("GAME:MOVE:{}:{}", client.username, column_parse.clone()?)) &format!("GAME:MOVE:{}:{}", client.username, column_parse.clone()?),
)
.await; .await;
// Check game end conditions // Check game end conditions
@@ -232,25 +243,40 @@ async fn handle_connection(
} }
for i in 0..4 { for i in 0..4 {
if x + i >= 6 || current_match.board[x + i][y] != color && horizontal_end { if x + i >= 6
|| current_match.board[x + i][y] != color && horizontal_end
{
horizontal_end = false; horizontal_end = false;
} }
if y + i >= 5 || current_match.board[x][y + i] != color && vertical_end { if y + i >= 5
|| current_match.board[x][y + i] != color && vertical_end
{
vertical_end = false; vertical_end = false;
} }
if x + i >= 6 || y + i >= 5 || current_match.board[x + i][y + i] != color && diagonal_end { if x + i >= 6
|| y + i >= 5
|| current_match.board[x + i][y + i] != color
&& diagonal_end
{
diagonal_end = false; diagonal_end = false;
} }
} }
if horizontal_end || vertical_end || diagonal_end { result = (color.clone(), false); break; } if horizontal_end || vertical_end || diagonal_end {
result = (color.clone(), false);
break;
}
}
if result.0 != Color::None {
break;
} }
if result.0 != Color::None { break; }
} }
if any_empty && result.0 == Color::None { result.1 = true; } if any_empty && result.0 == Color::None {
result.1 = true;
}
result result
}; };
@@ -261,16 +287,25 @@ async fn handle_connection(
if !demo_mode { if !demo_mode {
let _ = send(&opponent.connection, "GAME:LOSS"); let _ = send(&opponent.connection, "GAME:LOSS");
} }
broadcast_message(&current_match.viewers, &observers, &format!("GAME:WIN:{}", client.username)).await; broadcast_message(
&current_match.viewers,
&observers,
&format!("GAME:WIN:{}", client.username),
)
.await;
} else { } else {
let _ = send(&tx, "GAME:LOSS"); let _ = send(&tx, "GAME:LOSS");
if !demo_mode { if !demo_mode {
let _ = send(&opponent.connection, "GAME:WINS"); let _ = send(&opponent.connection, "GAME:WINS");
} }
broadcast_message(&current_match.viewers, &observers, &format!("GAME:WIN:{}", opponent.username)).await; broadcast_message(
&current_match.viewers,
&observers,
&format!("GAME:WIN:{}", opponent.username),
)
.await;
} }
} } else if filled {
else if filled {
let _ = send(&tx, "GAME:DRAW"); let _ = send(&tx, "GAME:DRAW");
if !demo_mode { if !demo_mode {
let _ = send(&opponent.connection, "GAME:DRAW"); let _ = send(&opponent.connection, "GAME:DRAW");
@@ -278,7 +313,6 @@ async fn handle_connection(
broadcast_message(&current_match.viewers, &observers, "GAME:DRAW").await; broadcast_message(&current_match.viewers, &observers, "GAME:DRAW").await;
} }
// remove match from matchmaker // remove match from matchmaker
if winner != Color::None || filled { if winner != Color::None || filled {
let opponent_addr = opponent.addr; let opponent_addr = opponent.addr;
@@ -294,7 +328,8 @@ async fn handle_connection(
client.current_match = None; client.current_match = None;
drop(client); drop(client);
let mut opponent = clients_guard.get_mut(&opponent_addr).unwrap().write().await; let mut opponent =
clients_guard.get_mut(&opponent_addr).unwrap().write().await;
if !demo_mode { if !demo_mode {
opponent.current_match = None; opponent.current_match = None;
@@ -305,22 +340,22 @@ async fn handle_connection(
if !demo_mode { if !demo_mode {
// TODO: delay/autoplay/continue behavior // TODO: delay/autoplay/continue behavior
let _ = send(&opponent.connection, &format!("OPPONENT:{}", column_parse.clone()?)); let _ = send(
&opponent.connection,
&format!("OPPONENT:{}", column_parse.clone()?),
);
} else { } else {
let random_move = random_move(&current_match.board); let random_move = random_move(&current_match.board);
current_match.place_token(Color::Blue, random_move); current_match.place_token(Color::Blue, random_move);
let _ = send(&tx, &format!("OPPONENT:{}", random_move)); let _ = send(&tx, &format!("OPPONENT:{}", random_move));
} }
} }
else if text == "GAME:LIST" { else if text == "GAME:LIST" {
todo!() todo!()
} }
else if text.starts_with("GAME:WATCH:") { else if text.starts_with("GAME:WATCH:") {
todo!() todo!()
} }
else if text.starts_with("ADMIN:AUTH:") { else if text.starts_with("ADMIN:AUTH:") {
todo!() todo!()
} }
@@ -336,7 +371,6 @@ async fn handle_connection(
else if text == "GAME:CONTINUE" { else if text == "GAME:CONTINUE" {
todo!() todo!()
} }
else { else {
let _ = send(&tx, "ERROR:UNKNOWN"); let _ = send(&tx, "ERROR:UNKNOWN");
} }
@@ -414,14 +448,12 @@ async fn watch(matches: &Matches, new_match_id: u32, addr: SocketAddr) {
} }
} }
if found { break; } if found {
break;
}
} }
matches matches.write().await.get_mut(&new_match_id).unwrap().write().await.viewers.push(addr);
.write().await
.get_mut(&new_match_id).unwrap()
.write().await
.viewers.push(addr);
} }
fn send(tx: &UnboundedSender<Message>, text: &str) -> Result<(), SendError<Message>> { fn send(tx: &UnboundedSender<Message>, text: &str) -> Result<(), SendError<Message>> {

View File

@@ -1,5 +1,5 @@
use crate::types::Color;
use rand::Rng; use rand::Rng;
use crate::types::{Client, Color};
pub fn random_move(board: &[Vec<Color>]) -> usize { pub fn random_move(board: &[Vec<Color>]) -> usize {
let mut random = rand::rng().random_range(0..6); let mut random = rand::rng().random_range(0..6);

View File

@@ -1,6 +1,6 @@
use rand::Rng;
use std::net::SocketAddr; use std::net::SocketAddr;
use std::vec; use std::vec;
use rand::Rng;
use tokio::sync::mpsc::error::SendError; use tokio::sync::mpsc::error::SendError;
use tokio::sync::mpsc::UnboundedSender; use tokio::sync::mpsc::UnboundedSender;
use tokio_tungstenite::tungstenite::Message; use tokio_tungstenite::tungstenite::Message;
@@ -53,8 +53,21 @@ pub struct Match {
impl Match { impl Match {
pub fn new(id: u32, player1: SocketAddr, player2: SocketAddr) -> Match { pub fn new(id: u32, player1: SocketAddr, player2: SocketAddr) -> Match {
let first = if rand::rng().random_range(0..=1) == 0 { player1.clone() } else { player2.clone() }; let first = if rand::rng().random_range(0..=1) == 0 {
Match { id, board: vec![vec![Color::None; 5]; 6], viewers: Vec::new(), ledger: Vec::new(), first, player1, player2 } player1.to_string().parse().unwrap()
} else {
player2.to_string().parse().unwrap()
};
// TODO: make player1 in Match always first
Match {
id,
board: vec![vec![Color::None; 5]; 6],
viewers: Vec::new(),
ledger: Vec::new(),
first,
player1,
player2,
}
} }
pub fn place_token(&mut self, color: Color, column: usize) { pub fn place_token(&mut self, color: Color, column: usize) {