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 types;
use crate::random_ai::random_move;
use crate::types::{Color, Match};
use futures_util::{SinkExt, StreamExt};
use rand::Rng;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use rand::Rng;
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::mpsc::error::SendError;
use tokio::sync::mpsc::UnboundedSender;
@@ -14,13 +15,11 @@ use tokio::sync::RwLock;
use tokio_tungstenite::{accept_async, tungstenite::Message};
use tracing::{error, info, warn};
use types::Client;
use crate::random_ai::random_move;
type Clients = Arc<RwLock<HashMap<SocketAddr, Arc<RwLock<Client>>>>>;
type Observers = Arc<RwLock<HashMap<SocketAddr, UnboundedSender<Message>>>>;
type Matches = Arc<RwLock<HashMap<u32, Arc<RwLock<Match>>>>>;
#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
// Initialize logging
@@ -46,7 +45,7 @@ async fn main() -> Result<(), anyhow::Error> {
observers.clone(),
matches.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
observers.write().await.remove(&addr);
clients
.write().await
.insert(
clients.write().await.insert(
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");
@@ -129,21 +132,21 @@ async fn handle_connection(
clients.write().await.get_mut(&addr).unwrap().write().await.ready = true;
let _ = send(&tx,"READY:ACK");
let _ = send(&tx, "READY:ACK");
if demo_mode {
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());
clients.write().await.get_mut(&addr).unwrap().write().await.ready = false;
clients
.write().await
.get_mut(&addr).unwrap()
.write().await.current_match = Some(match_id);
clients
.write().await
.get_mut(&addr).unwrap()
.write().await.color = Color::Red;
clients.write().await.get_mut(&addr).unwrap().write().await.current_match =
Some(match_id);
clients.write().await.get_mut(&addr).unwrap().write().await.color =
Color::Red;
let _ = send(&tx, "GAME:START:1");
}
}
@@ -152,7 +155,9 @@ async fn handle_connection(
let client_option = clients_guard.get(&addr);
// 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");
continue;
}
@@ -160,22 +165,23 @@ async fn handle_connection(
let client = client_option.unwrap().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 result =
if addr == current_match.player1
{ clients_guard.get(&current_match.player2).unwrap().read().await }
else
{ clients_guard.get(&current_match.player1).unwrap().read().await };
let result = if addr == current_match.player1 {
clients_guard.get(&current_match.player2).unwrap().read().await
} else {
clients_guard.get(&current_match.player1).unwrap().read().await
};
result
};
// Check if it's their move
if (current_match.ledger.is_empty() &&
current_match.first != addr) ||
(current_match.ledger.last().is_some() && current_match.ledger.last().unwrap().0 == client.color)
if (current_match.ledger.is_empty() && current_match.first != addr)
|| (current_match.ledger.last().is_some()
&& current_match.ledger.last().unwrap().0 == client.color)
{
let _ = send(&tx, "ERROR:INVALID:MOVE");
continue;
@@ -187,7 +193,11 @@ async fn handle_connection(
drop(matches_guard);
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
if let Ok(column) = column_parse {
@@ -212,7 +222,8 @@ async fn handle_connection(
broadcast_message(
&current_match.viewers,
&observers,
&format!("GAME:MOVE:{}:{}", client.username, column_parse.clone()?))
&format!("GAME:MOVE:{}:{}", client.username, column_parse.clone()?),
)
.await;
// Check game end conditions
@@ -232,25 +243,40 @@ async fn handle_connection(
}
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;
}
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;
}
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;
}
}
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
};
@@ -261,16 +287,25 @@ async fn handle_connection(
if !demo_mode {
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 {
let _ = send(&tx, "GAME:LOSS");
if !demo_mode {
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");
if !demo_mode {
let _ = send(&opponent.connection, "GAME:DRAW");
@@ -278,7 +313,6 @@ async fn handle_connection(
broadcast_message(&current_match.viewers, &observers, "GAME:DRAW").await;
}
// remove match from matchmaker
if winner != Color::None || filled {
let opponent_addr = opponent.addr;
@@ -294,7 +328,8 @@ async fn handle_connection(
client.current_match = None;
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 {
opponent.current_match = None;
@@ -303,24 +338,24 @@ async fn handle_connection(
continue;
}
if !demo_mode{
if !demo_mode {
// TODO: delay/autoplay/continue behavior
let _ = send(&opponent.connection, &format!("OPPONENT:{}", column_parse.clone()?));
let _ = send(
&opponent.connection,
&format!("OPPONENT:{}", column_parse.clone()?),
);
} else {
let random_move = random_move(&current_match.board);
current_match.place_token(Color::Blue, random_move);
let _ = send(&tx, &format!("OPPONENT:{}", random_move));
}
}
else if text == "GAME:LIST" {
todo!()
}
else if text.starts_with("GAME:WATCH:") {
todo!()
}
else if text.starts_with("ADMIN:AUTH:") {
todo!()
}
@@ -336,7 +371,6 @@ async fn handle_connection(
else if text == "GAME:CONTINUE" {
todo!()
}
else {
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
.write().await
.get_mut(&new_match_id).unwrap()
.write().await
.viewers.push(addr);
matches.write().await.get_mut(&new_match_id).unwrap().write().await.viewers.push(addr);
}
fn send(tx: &UnboundedSender<Message>, text: &str) -> Result<(), SendError<Message>> {

View File

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

View File

@@ -1,6 +1,6 @@
use rand::Rng;
use std::net::SocketAddr;
use std::vec;
use rand::Rng;
use tokio::sync::mpsc::error::SendError;
use tokio::sync::mpsc::UnboundedSender;
use tokio_tungstenite::tungstenite::Message;
@@ -53,8 +53,21 @@ pub struct Match {
impl 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() };
Match { id, board: vec![vec![Color::None; 5]; 6], viewers: Vec::new(), ledger: Vec::new(), first, player1, player2 }
let first = if rand::rng().random_range(0..=1) == 0 {
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) {