Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add method to get side to move as number #33

Closed
UlisseMini opened this issue May 14, 2020 · 4 comments
Closed

Add method to get side to move as number #33

UlisseMini opened this issue May 14, 2020 · 4 comments

Comments

@UlisseMini
Copy link

UlisseMini commented May 14, 2020

A common idiom in engines is something like this

fn eval(board: chess::Board) {
  // ... do stuff ...

  let color = if board.side_to_move() == Color::White { 1 } else { -1 };
  return evaluation * color;
}

It would be convenient if there was a method to get the number version of the side to move, perhaps a method on Color, such as

fn to_num(self) -> i32 {
  match self {
    Color::White => 1,
    Color::Black => -1,
  }
}

(name is debatable, but this is the idea)

@jordanbray
Copy link
Owner

there is already to_indexwhich converts it into a 0 or 1, but not a -1, 1 as you are requesting.

However, the most common case for this is to move a square forward. As a result, there are functions Square::forward(&self, color: Color) and Square::uforward(&self, color: Color) which moves the square in the correct direction.

@UlisseMini
Copy link
Author

I know its niche, but IMO having to write

  let color = if board.side_to_move() == Color::White {
    1
  } else {
    -1
  };

(rustfmt forces it to be this way) Distracts from the business logic. I understand a reluctance to add such a small niche feature though, I can always extract the else-if to a helper function.

@jordanbray
Copy link
Owner

Can you give me an example of where this may be used?

A more ergonomic (and branchless) way to write this would be board.side_to_move().to_index() * 2 - 1, which converts Color::White to -1 and Color::Black to 1. You could put a ! on the color to inverse that as shown in your example.

@UlisseMini
Copy link
Author

Oh yeah I'm an idiot, I'll use to_index() * 2 - 1, Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants