16 Commits
Author SHA1 Message Date
vova-rs 03c09101fe final predictiv system 2026-10-15 23:13:45 +03:00
vova-rs 27fd785034 move input whitch predikt 2026-10-15 20:51:29 +03:00
vova-rs 2c2ccd6770 fix start posytion; some test 2026-10-13 21:31:11 +03:00
vova-rs 54c458296d add missing pub use in engiens 2026-10-13 21:07:27 +03:00
vova-rs 6c0453cce3 fix: remove todo!() in generate_legal() 2026-10-13 00:15:47 +03:00
vova-rs bda716da90 theoretical end: Breakthrough 2026-10-13 00:05:10 +03:00
vova-rs 651c4713c2 whin zones patch 2026-10-12 22:42:11 +03:00
vova-rs b895eaa265 fn status done 2026-10-12 03:47:14 +03:00
vova-rs d7b9e571f3 fix: MaskPatch 2026-10-10 20:28:00 +03:00
vova-rs 85039bedcf refact apply move 2026-10-10 12:36:12 +03:00
vova-rs a61395ca6a inplement .index() in Color 2026-10-10 12:33:21 +03:00
vova-rs 45e1843fba hot fix 2026-10-10 05:25:02 +03:00
vova-rs e4a570e17b fix: inspections in Board 2026-10-10 05:21:54 +03:00
vova-rs e27482082b start to write Breakthrough 2026-10-10 04:53:30 +03:00
vova-rs 18d6a96b0d small refactor 2026-10-07 23:59:17 +03:00
vova-rs 98a2784de2 start chess api 2026-10-06 00:41:16 +03:00
11 changed files with 457 additions and 47 deletions

No files matched your search

+80
View File
@@ -0,0 +1,80 @@
mod trajectory;
pub use trajectory::*;
mod movement_mask;
pub use movement_mask::mov_mask;
use super::Color;
#[derive(Clone, Copy)]
pub struct Board<const N: usize> {
layers: [[u64; 2]; N],
}
impl<const N: usize> Board<N> {
pub const fn from_layers(layers: [[u64; 2]; N]) -> Self {
Self { layers }
}
pub fn apply_patch(&mut self, patch: &MaskPatch) {
for layer in self.layers.iter_mut() {
layer[0] &= !patch.clear_mask;
layer[1] &= !patch.clear_mask;
}
for (side, y, mask) in patch.iter() {
let x = side.index();
debug_assert!(x < 2 && y < N);
if x >= 2 || y >= N {
eprintln!(
"Board::apply_patch: invalid set_mask coords (side={:?}, layer={}, N={})",
side, y, N
);
panic!("invalid set_mask coordinates");
}
self.layers[y][x] |= mask;
}
}
pub fn get_mask(&self, x: Color, y: usize) -> u64 {
if y >= N || x.index() >= 2 {
return 0;
}
self.layers[y][x.index()]
}
pub fn is_mask_zero(&self, x: Color, y: usize) -> bool {
self.get_mask(x, y) == 0
}
pub fn and_mask_is_zero(&self, x: Color, y: usize, mask: u64) -> bool {
if y >= N || x.index() >= 2 {
return true;
}
(self.layers[y][x.index()] & mask) == 0
}
}
#[derive(Clone, Copy)]
pub struct MaskPatch {
pub clear_mask: u64,
pub set_masks: [Option<(Color, usize, u64)>; 4],
len: u8,
}
impl MaskPatch {
pub fn new(clear_mask: u64) -> Self {
Self { clear_mask, set_masks: [None; 4], len: 0 }
}
pub fn push(&mut self, side: Color, layer: usize, mask: u64) {
debug_assert!((self.len as usize) < 4);
self.set_masks[self.len as usize] = Some((side, layer, mask));
self.len += 1;
}
pub fn iter(&self) -> impl Iterator<Item = (Color, usize, u64)> + '_ {
self.set_masks[..self.len as usize]
.iter()
.map(|o| o.unwrap())
}
}
File renamed without changes.
+141
View File
@@ -0,0 +1,141 @@
use std::collections::HashMap;
use super::*;
pub const WHITE_WON_ZONE: u64 = 0xff << 56;
pub const BLACK_WON_ZONE: u64 = 0xff;
pub const START_BOARD: Board<1> = Board::from_layers([
[0xffff, 0xffff << 48],
]);
pub struct Breakthrough{
board: Board<1>,
side: Color,
legal_moves: Option<HashMap<Move, MaskPatch>>,
}
impl Breakthrough {
pub fn new() -> Self {
let mut p = Breakthrough{
board: START_BOARD,
side: Color::White,
legal_moves: None
};
p.refresh_legal_moves();
p
}
pub fn refresh_legal_moves(&mut self) {
self.legal_moves = Some(self.generate_legal());
}
pub fn get_board(&self) -> Board<1> {
self.board.clone()
}
fn generate_legal(&self) -> HashMap<Move, MaskPatch>{
let mut legal: HashMap<Move, MaskPatch> = HashMap::new();
let white = self.board.get_mask(Color::White, 0);
let black = self.board.get_mask(Color::Black, 0);
let own = match self.side {
Color::White => white,
Color::Black => black,
};
let mut bits = own;
while bits != 0 {
let from = bits.trailing_zeros() as u8;
let from_bit = 1u64 << from;
bits &= bits - 1;
let mut t = self.mov_pattern(from_bit);
while t != 0 {
let to = t.trailing_zeros() as u8;
let to_bit = 1u64 << to;
t &= t - 1;
let mv = Move { from, to, p: Promotion::NoPromotion };
let mut patch = MaskPatch::new(from_bit | to_bit);
patch.push(self.side, 0, to_bit);
legal.insert(mv, patch);
}
}
legal
}
fn mov_pattern(&self, pos: u64) -> u64 {
let white = self.board.get_mask(Color::White, 0);
let black = self.board.get_mask(Color::Black, 0);
let (own, enemy, mvc, mvl, mvr) = match self.side {
Color::White => (
white, black,
(8i8, mov_mask(0)),
(7i8, mov_mask(-1)),
(9i8, mov_mask(1)),
),
Color::Black => (
black, white,
(-8i8, mov_mask(0)),
(-7i8, mov_mask(1)),
(-9i8, mov_mask(-1)),
),
};
let mmvc = trajectory(pos, mvc.1, own | enemy, 0, mvc.0, Some(1));
let mmvl = trajectory(pos, mvl.1, own, enemy, mvl.0, Some(1));
let mmvr = trajectory(pos, mvr.1, own, enemy, mvr.0, Some(1));
mmvc | mmvr | mmvl
}
}
impl ChessEngine for Breakthrough {
fn legal_moves(&self) -> Vec<Move> {
self.legal_moves.clone().unwrap().keys().cloned().collect()/*.expect("cache empty; call refresh first")*/
}
fn apply(&mut self, mv: Move) -> Result<(), MoveErrors> {
if self.status() != GameStatus::Ongoing {
return Err(MoveErrors::GameOver);
}
let patch = self
.legal_moves
.as_ref()
.ok_or(MoveErrors::NoMoveStack)?
.get(&mv)
.ok_or(MoveErrors::InvalidMove)?;
self.board.apply_patch(patch);
self.side = self.side.opposite();
self.refresh_legal_moves();
Ok(())
}
fn status(&self) -> GameStatus {
if self.board.is_mask_zero(Color::White, 0) {
return GameStatus::Won(Color::Black);
}
if self.board.is_mask_zero(Color::Black, 0) {
return GameStatus::Won(Color::White);
}
if !self.board.and_mask_is_zero(Color::Black, 0, BLACK_WON_ZONE) {
return GameStatus::Won(Color::Black);
}
if !self.board.and_mask_is_zero(Color::White, 0, WHITE_WON_ZONE) {
return GameStatus::Won(Color::White);
}
GameStatus::Ongoing
}
fn side_to_move(&self) -> Color{
self.side
}
}
+4
View File
@@ -0,0 +1,4 @@
use super::*;
mod breakthrough;
pub use breakthrough::Breakthrough;
+85
View File
@@ -0,0 +1,85 @@
pub mod board;
pub use board::*;
mod engines;
pub use engines::*;
pub trait ChessEngine {
// fn new() -> Self;
fn legal_moves(&self) -> Vec<Move>;
fn apply(&mut self, mv: Move) -> Result<(), MoveErrors>;
fn side_to_move(&self) -> Color;
fn status(&self) -> GameStatus;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MoveErrors { GameOver, InvalidMove, NoMoveStack }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Move{
pub from: u8,
pub to: u8,
pub p: Promotion,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum Promotion {
NoPromotion = 0,
Knight = 1,
Rook = 2,
Bishop = 3,
Queen = 4,
}
impl From<Promotion> for u8 {
#[inline]
fn from(p: Promotion) -> u8 {
p as u8
}
}
impl TryFrom<u8> for Promotion {
type Error = ();
#[inline]
fn try_from(v: u8) -> Result<Self, ()> {
match v {
0 => Ok(Promotion::NoPromotion),
1 => Ok(Promotion::Knight),
2 => Ok(Promotion::Rook),
3 => Ok(Promotion::Bishop),
4 => Ok(Promotion::Queen),
_ => Err(()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Color {
White,
Black,
}
impl Color {
pub fn opposite(self) -> Color {
match self {
Color::White => Color::Black,
Color::Black => Color::White,
}
}
pub fn index(self) -> usize {
match self {
Color::White => 0,
Color::Black => 1,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GameStatus {
Ongoing,
Won(Color),
Draw,
}
-10
View File
@@ -1,10 +0,0 @@
mod trajectory;
pub use trajectory::*;
mod movement_mask;
pub use movement_mask::mov_mask;
struct Board<const N: usize> {
layers: [[u64; 2]; N],
}
-3
View File
@@ -1,3 +0,0 @@
pub mod board;
use board::*;
+76
View File
@@ -0,0 +1,76 @@
use std::io;
use crate::chess_api::Move;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SquareInput {
File(u8), // столбец 0..8 (a..h)
Rank(u8), // строка 0..8 (1..8)
Cell(u8), // конкретная клетка 0..64
}
impl SquareInput {
pub fn matches(&self, sq: u8) -> bool {
match *self {
SquareInput::File(f) => (sq % 8) == f,
SquareInput::Rank(r) => (sq / 8) == r,
SquareInput::Cell(c) => sq == c,
}
}
}
pub fn read_square() -> SquareInput {
loop {
let mut s = String::new();
io::stdin().read_line(&mut s).unwrap();
let b = s.trim().to_lowercase().into_bytes();
match b.len() {
1 => {
if (b'a'..=b'h').contains(&b[0]) {
return SquareInput::File(b[0] - b'a');
}
if (b'1'..=b'8').contains(&b[0]) {
return SquareInput::Rank(b[0] - b'1');
}
}
2 => {
if (b'a'..=b'h').contains(&b[0]) && (b'1'..=b'8').contains(&b[1]) {
return SquareInput::Cell((b[1] - b'1') * 8 + (b[0] - b'a'));
}
}
_ => {}
}
println!("не подходит, ещё раз:");
}
}
pub fn sq_to_string(sq: u8) -> String {
let file = (sq % 8) as u8 + b'a';
let rank = (sq / 8) as u8 + b'1';
format!("{}{}", file as char, rank as char)
}
pub fn has_unique_from(items: &[Move]) -> bool {
let mut froms: Vec<u8> = items.iter().map(|x| x.from).collect();
froms.sort_unstable();
froms.windows(2).any(|w| w[0] != w[1])
}
pub fn unique_froms(items: &[Move]) -> Vec<u8> {
let mut froms: Vec<u8> = items.iter().map(|x| x.from).collect();
froms.sort_unstable();
let mut result = Vec::new();
let n = froms.len();
let mut i = 0;
while i < n {
let mut j = i + 1;
while j < n && froms[j] == froms[i] { j += 1; }
if j - i == 1 {
result.push(froms[i]);
}
i = j;
}
result
}
+51 -14
View File
@@ -1,28 +1,65 @@
mod chess_engines;
use chess_engines::board::*;
mod chess_api;
use chess_api::*;
mod render_bitmask;
use render_bitmask::*;
mod gaming;
use gaming::*;
fn main() {
let full: u64 = 0xfefefefefefefefe;
let mut game = Breakthrough::new();
let own: u64 = 0xffff002100000000;
loop {
println!("---<>---");
let wr: u64 = 0x000000000004c83b;
let b = game.get_board();
let bish: u64 = 0x0000002100000000;
render_board(
BoardColor::Checkerboard('•', ' '),
&[
(b.get_mask(Color::White, 0), '●'),
(b.get_mask(Color::Black, 0), '○'),
],
);
let ans: u64 = trajectory(bish, full, own, wr, -7, None);
let status = game.status();
println!("side: {:?}", game.side_to_move());
if status != GameStatus::Ongoing {
println!("game over: {:?}", status);
break;
}
render_board(BoardColor::Solid(':'), vec![(ans & wr,'t'), (ans, 'm'), (bish, 'a')]);
let moves = game.legal_moves();
print!("\n");
let to_input = read_square();
let cand: Vec<Move> = moves.iter().filter(|m| to_input.matches(m.to)).copied().collect();
let f_cand = unique_froms(&cand);
render_board(BoardColor::Solid(':'), vec![(wr, 'k'), (own, 'w')]);
print!("\n");
render_board(BoardColor::Solid('`'), vec![(!mov_mask(3), 'a'), (!mov_mask(-2), 'c')]);
match f_cand.clone().as_slice() {
[] => {
println!("incorekt");
}
[f_input] => {
let s: Vec<Move> = moves.iter().filter(|m| to_input.matches(m.to) && m.from == *f_input).copied().collect();
game.apply(s[0]).unwrap();
}
_ => {
for i in &f_cand {
print!("{}, ", sq_to_string(*i));
}
print!("\n");
let f_input = read_square();
let k: Vec<_> = f_cand.iter().filter(|m| f_input.matches(**m)).copied().collect();
if k.len() == 1 {
let s: Vec<Move> = moves.iter().filter(|m| to_input.matches(m.to) && m.from == k[0]).copied().collect();
game.apply(s[0]).unwrap();
} else {
println!("incorekt2");
}
}
}
}
}
+20 -20
View File
@@ -1,4 +1,4 @@
#[derive(Clone, Copy)]
pub enum BoardColor {
Solid(char),
Checkerboard(char, char),
@@ -21,29 +21,29 @@ pub fn render_u64(a: u64) {
pub fn render_board(background: BoardColor, layers: Vec<(u64, char)>){
let mut p: u64 = 1 << 56;
for y in 0..8 {
for x in 0..8 {
if let Some((_, ch)) = layers.iter().find(|(a, _)| (p << x as u64) & a > 0) {
print!("{}", ch)
} else {
match background {
BoardColor::Solid(a) => {
pub fn render_board_row(background: BoardColor, layers: &[(u64, char)], row: u8) {
let p: u64 = 1 << 56 >> (row as u64 * 8);
for x in 0..8 {
if let Some((_, ch)) = layers.iter().find(|(a, _)| (p << x as u64) & a > 0) {
print!("{}", ch)
} else {
match background {
BoardColor::Solid(a) => print!("{}", a),
BoardColor::Checkerboard(a, b) => {
if (x + row as usize) % 2 == 0 {
print!("{}", a)
},
BoardColor::Checkerboard(a, b) => {
if (x + y) % 2 == 0 {
print!("{}", a)
} else {
print!("{}", b)
}
} else {
print!("{}", b)
}
}
}
}
p = p >> 8;
print!("\n")
}
print!("\n");
}
pub fn render_board(background: BoardColor, layers: &[(u64, char)]) {
for row in 0..8 {
render_board_row(background.clone(), layers, row);
}
}