Position

Struct Position 

Source
pub struct Position {
    pub position: u64,
    pub mask: u64,
    /* private fields */
}
Expand description

Represents a Connect Four position compactly as a bitboard.

The standard, 6x7 Connect Four board can be represented unambiguously using 49 bits in the following bit order:

  6 13 20 27 34 41 48
 ---------------------
| 5 12 19 26 33 40 47 |
| 4 11 18 25 32 39 46 |
| 3 10 17 24 31 38 45 |
| 2  9 16 23 30 37 44 |
| 1  8 15 22 29 36 43 |
| 0  7 14 21 28 35 42 |
 ---------------------

The extra row of bits at the top identifies full columns and prevents bits from overflowing into the next column. For computational efficiency, positions are stored in practice using two u64 numbers: one to store a mask of all occupied tiles, and the other to store a mask of the current player’s tiles.

Fields§

§position: u64

A mask of the current player’s tiles.

§mask: u64

A mask of all occupied tiles.

Implementations§

Source§

impl Position

Source

pub const WIDTH: usize = 7usize

Source

pub const HEIGHT: usize = 6usize

Source

pub const BOARD_SIZE: usize = 42usize

Source

pub const CENTRE: usize = 3usize

Source

pub const MIN_SCORE: i8 = -18i8

Source

pub const MAX_SCORE: i8 = 18i8

Source

pub fn new() -> Position

Creates a new Position instance for the initial state of the game.

Source

pub fn from_board_string( board_string: &str, ) -> Result<Position, PositionParsingError>

Parses a Position from a string representation of the Connect Four board.

The input string should contain exactly 42 characters from the set ['.', 'o', 'x'], representing the board row by row from the top-left to the bottom-right. All other characters are ignored. ‘x’ is treated as the current player, and ‘o’ as the opponent. This method assumes that a correctly formatted board string is a valid game position. Invalid game positions will lead to undefined behaviour.

§Arguments
  • board_string: A string slice representing the board state.
§Returns

On success, returns a Result containing the parsed Position.

§Errors

Returns a PositionParsingError if the input string is invalid.

§Example
 use connect_four_ai::Position;

 // A typical board state, represented as a string
 let board_string = "\
    .......
    ...o...
    ..xx...
    ..ox...
    ..oox..
    ..oxxo.
 ";

 // Parses the string as a `Position` instance
 let pos = Position::from_board_string(board_string).unwrap();
 assert_eq!(pos.get_moves(), 12)
Source

pub fn from_moves(move_sequence: &str) -> Result<Position, PositionParsingError>

Parses a Position from a string of 1-indexed moves.

The input string should contain a sequence of columns played, indexed from 1.

§Arguments
  • moves: A string slice containing the move sequence.
§Returns

On success, returns a Result containing the parsed Position.

§Errors

Returns a PositionParsingError if the move sequence is invalid.

§Example
 use connect_four_ai::Position;

 // A typical board state, represented as a sequence of moves
 let moves = "444343533654";

 // Parses the sequence as a `Position` instance
 let pos = Position::from_moves(moves).unwrap();
 assert_eq!(pos.get_moves(), 12)
Source

pub fn get_moves(&self) -> usize

Returns the number of moves played to reach the current position.

Source

pub fn get_key(&self) -> u64

Returns the unique key for the current position.

This key is unique to each pair of horizontally symmetrical positions, as these positions will always have the same solution.

Source

pub fn is_playable(&self, col: usize) -> bool

Indicates whether a given column is playable.

§Arguments
  • col: 0-based index of a column.
§Returns

True if the column is playable, false if the column is already full.

Source

pub fn is_winning_move(&self, col: usize) -> bool

Indicates whether the current player wins by playing a given column.

§Arguments
  • col: 0-based index of a playable column.
§Returns

True if the current player makes a 4-alignment by playing the column, false otherwise.

Source

pub fn can_win_next(&self) -> bool

Indicates whether the current player can win with their next move.

Source

pub fn play(&mut self, col: usize)

Plays a move in the given column.

§Arguments
  • col: 0-based index of a playable column.
Source

pub fn possible(&self) -> u64

Returns a mask for the possible moves the current player can make.

Source

pub fn possible_non_losing_moves(&self) -> u64

Returns a mask for the possible non-losing moves the current player can make.

Source

pub fn score_move(&self, move_bit: u64) -> u8

Scores a possible move by counting the number of winning spots the player has after playing it.

§Arguments
  • move_bit: A possible move, given as a bitmask with a single one in the position of the new piece.
§Returns

The move’s score.

Source

pub fn is_won_position(&self) -> bool

Indicates whether the current position has been won by either player.

Source

pub const fn column_mask(col: usize) -> u64

Returns a mask for the entirety of the given column.

§Arguments
  • col: 0-based index of a column.
§Returns

A bitmask with a one in all cells of the column.

Trait Implementations§

Source§

impl Clone for Position

Source§

fn clone(&self) -> Position

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Position

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Position

Default constructor for the Position struct.

Source§

fn default() -> Position

Returns the “default value” for a type. Read more
Source§

impl Copy for Position

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V