fix: clippy warnings

This commit is contained in:
Ashhhleyyy 2022-10-31 13:30:34 +00:00
parent 2fd10446b6
commit d9572be9bc
Signed by: ash
GPG key ID: 83B789081A0878FB
7 changed files with 57 additions and 34 deletions

View file

@ -28,7 +28,7 @@ impl Coordinate {
pub fn from_index(index: usize) -> Self { pub fn from_index(index: usize) -> Self {
let rank = (index / 8) as isize; let rank = (index / 8) as isize;
let file = (index % 8) as isize; let file = (index % 8) as isize;
return Self { rank, file }; Self { rank, file }
} }
pub fn parse_algebraic(s: &str) -> Result<Self, NotationError> { pub fn parse_algebraic(s: &str) -> Result<Self, NotationError> {
@ -49,8 +49,7 @@ impl Coordinate {
let rank = s let rank = s
.chars() .chars()
.skip(1) .nth(1)
.next()
.unwrap() .unwrap()
.to_digit(9) .to_digit(9)
.map(|v| v - 1) .map(|v| v - 1)
@ -317,7 +316,7 @@ impl Board {
let white_checked = black_moves.into_iter().any(|m| { let white_checked = black_moves.into_iter().any(|m| {
self.board[m.to.to_index()] == Some(Side::White | PieceType::King) self.board[m.to.to_index()] == Some(Side::White | PieceType::King)
}); });
return BySide { BySide {
black: black_checked, black: black_checked,
white: white_checked, white: white_checked,
} }

View file

@ -204,7 +204,7 @@ fn generate_castling_moves(board: &Board, moves: &mut Vec<Move>) {
if board.get(mid).is_some() { if board.get(mid).is_some() {
return None; return None;
} }
let test_state = Move::new(king_from, mid).make(&board); let test_state = Move::new(king_from, mid).make(board);
if *test_state.calc_check_state().get(board.to_move) { if *test_state.calc_check_state().get(board.to_move) {
return None; return None;
} }
@ -294,15 +294,13 @@ fn generate_pawn_moves(board: &Board, moves: &mut Vec<Move>) {
None None
}; };
let mv = Move { Move {
from, from,
to, to,
other: None, other: None,
promotions, promotions,
set_en_passant, set_en_passant,
}; }
mv
} }
let (start_rank, direction) = match board.to_move { let (start_rank, direction) = match board.to_move {

View file

@ -9,7 +9,7 @@ fn perft_board(board: &Board, depth: u64, start_depth: u64) -> u64 {
let mut moves = vec![]; let mut moves = vec![];
crate::chess::mv::generate_pseudolegal(board, &mut moves); crate::chess::mv::generate_pseudolegal(board, &mut moves);
let count = moves.into_par_iter().map(|mv| { moves.into_par_iter().map(|mv| {
let mut count = 0; let mut count = 0;
if let Some(promotions) = mv.promotions { if let Some(promotions) = mv.promotions {
for promotion in promotions { for promotion in promotions {
@ -44,9 +44,7 @@ fn perft_board(board: &Board, depth: u64, start_depth: u64) -> u64 {
} }
} }
count count
}).sum(); }).sum()
count
} }
pub fn run_perft(fen: &str, depth: u64, expected_positions: u64) -> bool { pub fn run_perft(fen: &str, depth: u64, expected_positions: u64) -> bool {

View file

@ -3,18 +3,16 @@ use std::collections::HashMap;
use uuid::Uuid; use uuid::Uuid;
use xtra::{prelude::*, WeakAddress}; use xtra::{prelude::*, WeakAddress};
use crate::{prelude::{Board, Move}, constants::START_FEN, chess::{Side, mv::generate_legal}, player::{Player, OutgoingPlayerEvent, IncomingPlayerEvent}}; use crate::{prelude::Board, constants::START_FEN, chess::{Side, mv::generate_legal}, player::{Player, OutgoingPlayerEvent, IncomingPlayerEvent}};
#[derive(Actor)] #[derive(Actor, Default)]
pub struct GameManager { pub struct GameManager {
games: HashMap<Uuid, Address<ChessGame>>, games: HashMap<Uuid, Address<ChessGame>>,
} }
impl GameManager { impl GameManager {
pub fn new() -> Self { pub fn new() -> Self {
Self { Default::default()
games: HashMap::new(),
}
} }
} }

View file

@ -1,5 +1,5 @@
use axum::Extension; use axum::Extension;
use chs::{prelude::*, game::GameManager}; use chs::game::GameManager;
use tower_http::trace::TraceLayer; use tower_http::trace::TraceLayer;
use tracing_subscriber::prelude::*; use tracing_subscriber::prelude::*;
use xtra::Mailbox; use xtra::Mailbox;
@ -22,7 +22,11 @@ async fn main() {
.layer(Extension(game_manager)) .layer(Extension(game_manager))
.layer(TraceLayer::new_for_http()); .layer(TraceLayer::new_for_http());
axum::Server::bind(&format!("0.0.0.0:3000").parse().unwrap()) let port: u16 = std::env::var("PORT")
.map(|s| s.parse().unwrap())
.unwrap_or(3000);
axum::Server::bind(&format!("0.0.0.0:{port}").parse().unwrap())
.serve(app.into_make_service()) .serve(app.into_make_service())
.await .await
.unwrap(); .unwrap();

View file

@ -1,7 +1,6 @@
use axum::{Router, extract::{WebSocketUpgrade, Path, ws::{Message, WebSocket}}, response::IntoResponse, routing::{get, get_service}, http::{StatusCode, Uri}, Extension}; use axum::{Router, extract::{WebSocketUpgrade, Path, ws::{Message, WebSocket}}, response::IntoResponse, routing::get, Extension};
use futures::{StreamExt, SinkExt, stream::{SplitStream, SplitSink}, channel::mpsc::{self, UnboundedSender}}; use futures::{StreamExt, SinkExt, stream::{SplitStream, SplitSink}, channel::mpsc::{self, UnboundedSender}};
use tokio::task::JoinHandle; use tokio::task::JoinHandle;
use tower_http::services::ServeDir;
use uuid::Uuid; use uuid::Uuid;
use xtra::{Mailbox, Address}; use xtra::{Mailbox, Address};
@ -9,6 +8,7 @@ use crate::{player::{Player, IncomingPlayerEvent, OutgoingPlayerEvent, GameInfo}
#[cfg(not(debug_assertions))] #[cfg(not(debug_assertions))]
use crate::assets::StaticFile; use crate::assets::StaticFile;
#[allow(clippy::let_and_return)]
pub fn routes() -> Router { pub fn routes() -> Router {
let router = Router::new() let router = Router::new()
.route("/ws/:id", get(ws_handler)); .route("/ws/:id", get(ws_handler));
@ -50,15 +50,13 @@ async fn handle_socket(socket: WebSocket, id: Uuid, game_manager: Address<GameMa
let res = game_manager.send(JoinGame { game_id: id, player: player.downgrade() }).await let res = game_manager.send(JoinGame { game_id: id, player: player.downgrade() }).await
.expect("game manager disconnected"); .expect("game manager disconnected");
if let Some(res) = res { if let Some(JoinGameResponse::Success { side, game }) = res {
if let JoinGameResponse::Success { side, game } = res { player.send(GameInfo { side, game }).await.expect("player disconnected");
player.send(GameInfo { side, game }).await.expect("player disconnected"); let rx_task = socket_recv(rx, player);
let rx_task = socket_recv(rx, player);
tokio::select! { tokio::select! {
_ = rx_task => {}, _ = rx_task => {},
_ = tx_task => {}, _ = tx_task => {},
}
} }
} }
} }
@ -85,7 +83,7 @@ fn socket_send(mut tx: SplitSink<WebSocket, Message>) -> (UnboundedSender<Outgoi
} }
fn socket_recv(mut rx: SplitStream<WebSocket>, player: Address<Player>) -> JoinHandle<()> { fn socket_recv(mut rx: SplitStream<WebSocket>, player: Address<Player>) -> JoinHandle<()> {
let task = tokio::spawn(async move { tokio::spawn(async move {
while let Some(msg) = rx.next().await { while let Some(msg) = rx.next().await {
if let Ok(msg) = msg { if let Ok(msg) = msg {
match msg { match msg {
@ -115,7 +113,5 @@ fn socket_recv(mut rx: SplitStream<WebSocket>, player: Address<Player>) -> JoinH
return; return;
} }
} }
}); })
task
} }

30
static/test.html Normal file
View file

@ -0,0 +1,30 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function wsRoute(id) {
const loc = window.location;
let newUri = loc.protocol === "https:" ? "wss://" : "ws://";
newUri += loc.host + '/ws/' + id;
return newUri;
}
// Random UUID
const ws = new WebSocket(wsRoute('7d3a9dac-71db-4ade-af46-f080777969a4'));
ws.onopen = function () {
ws.send('hello, world!');
ws.send('hello, world!');
ws.send('hello, world!');
}
ws.onmessage = function (data) {
console.log(data);
}
</script>
</body>
</html>