Giter VIP home page Giter VIP logo

chessnut's Introduction

Chessnut

Chessnut is a simple chess board model written in Python. Chessnut is not a chess engine -- it has no AI to play games, and it has no GUI. It is a simple package that can import/export games in Forsyth-Edwards Notation (FEN), generate a list of legal moves for the current board position, intelligently validate & apply moves (including en passant, castling, etc.), and keep track of the game with a history of both moves and corresponding FEN representation.

Chessnut is not written for speed, it is written for simplicity (there are only two real classes, and only about 200 lines of code). By adding a custom move evaluation function, Chessnut could be used as a chess engine. The simplicity of the model lends itself well to studying the construction of a chess engine without worrying about implementing a chess model, or to easily find the set of legal moves for either player on a particular chess board for use in conjunction with another chess application.

Installation

Virualenv

Chessnut can be used as a module within your project or it can be installed on your system as a package. If you're going to install it as a package, you should consider using Virtualenv to manage your python environment. With virtualenv installed, creating a new project environment is easy. From your terminal shell:

~$ mkdir ~/project
~/$ cd project
~/project$ virtualenv env
~/project$ source env/bin/activate
(env):~/project$

From here you can use pip or setup.py to install the package and it will be restricted to the copy of python in the env directory. You can leave the virtual environment by typing deactivate in the terminal, and restart the environment with source env/bin/activate.

PIP

pip is the easiest way to install Chessnut. It can be installed directly from the pypi package:

pip install Chessnut

Upgrading to the latest version can be performed with the -U flag:

pip install -U Chessnut

Or from the github repository:

pip install git+https://github.com/cgearhart/Chessnut.git

Setup.py

If you prefer, you can install Chessnut manually with setup.py. After downloading the source files to a local directory (and setting up a virtualenv), switch into the project directory and run setup.py:

python -m setup.py install

(Note: To install the package globally you may have to use the sudo command.)

As a Module

Finally, Chessnut is also a standalone module, so if you place the Chessnut directory within your project folder, you don't need to install the package, you can just import the module as usual. (Using one of the package versions--particularly PIP--is still recommended as a way to create separation between your code and the Chessnut package, so that you don't have to worry about merging your changes into future upgrades of Chessnut.

from Chessnut import Game

...

*<your code>*

Testing

Unit tests can be run with the test.sh shell script which launches the coverage.py framework as configured in .coveragerc, or you can use the standard unittest framework via python -m unittest discover. If you install the pylint package, you can run the checker with default options using pylint --ignore=tests Chessnut.

Using Chessnut

There are only two real classes in the Chessnut package: Board and Game. (There is also a namedtuple, State, which creates a class, and another class, InvalidMove--a subclass of Exception, used to avoid generic try/except statements). Board is only used internally by Game to keep track of pieces and perform string formatting to and from FEN notation, so Game should be the only class you need to import. After installing the Chessnut package, you can import and use it as you would expect:

from Chessnut import Game

chessgame = Game()
print(chessgame)  # 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'

print(chessgame.get_moves())
"""
['a2a3', 'a2a4', 'b2b3', 'b2b4', 'c2c3', 'c2c4', 'd2d3', 'd2d4', 'e2e3', 
 'e2e4', 'f2f3', 'f2f4', 'g2g3', 'g2g4', 'h2h3', 'h2h4', 'b1c3', 'b1a3', 
 'g1h3', 'g1f3']
"""

chessgame.apply_move('e2e4')  # succeeds!
print(chessgame)  # 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1'

chessgame.apply_move('e2e4')  # fails! (raises InvalidMove exception)

chessnut's People

Contributors

cgearhart avatar dai9 avatar zooba avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

chessnut's Issues

Cache Error

The move cache only includes the moves from a single ray, and is not properly updated for moves that are eliminated by the filtering in get_moves(). Since the library doesn't currently support an "undo" mechanism, the easiest solution (for now) is to just eliminate the cache entirely.

Allow short algebraic notation

It would be nice if we could input the moves using the short algebraic notation that is standard in the pgn format, e.g., e4 e5 Nf3, in addition to the long format currently supported.

The public api would get only one additional method, Game.apply_san_move(san_string). I have already implemented this and will open a pull request. I'd like to use Chessnut in a hobby project, but want to be able to read in pgn games.

Valid move missing for self.get_moves()

Hey, I've found a fen string for that you'll not receive the correct list of valid moves. The minimal test:

from Chessnut.game import Game
chessgame = Game()
chessgame.set_fen('r3kb1r/p1p2pp1/2p4p/3Pp3/6b1/2P5/PP1NN2P/R2QK1q1 w Qkq - 0 16')
try:
    assert (chessgame.get_moves() == ['d2f1', 'e2g1'])
    print 'Test passed.'
except AssertionError:
    print 'Test failed.'

The FEN corresponds to this position with white to move. Chessnut only returns the d2f1 move, but fails to return e2g1 knight capturing the queen.
fen

Improper Invalid Move Error

Error trace:

  File "build/bdist.linux-x86_64/egg/Chessnut/game.py", line 128, in apply_move
Chessnut.game.InvalidMove:
Illegal move: e8c8
fen: 1QQ1r3/3k1p1p/4p1p1/8/8/1N2P3/5PPP/2R3K1 b - - 0 40

invalid get_moves() results

get_moves() for fen="2r2rk1/p4p1p/1p6/2qNP1pb/Q1p1nB2/2P1PPP1/PP5P/3R1RK1 w - g6 0 22" does not allow the legal move f3e4.

Possible to check for mate?

Is it possible to somehow detect whether the current position is mate or stalemate? One way to check would be to see if the list of moves is empty (than one or the other would hold), and then to confirm whether or not the king is in check...

If not, that would be a really really helpful feature...

A pawn cannot put a king in check on the last line

A move for a pawn going on the last line is a promotion : departure, arrival, promotion piece.

This special move format make the "in check" test fails when comparing king position to pawn destination.

Proposed fix : #16

IndexError: list index out of range

I tried using the module and get:

File ".../moves.py", line 122, in MOVES['k'][4][1].append(2) IndexError: list index out of range

Same for
MOVES['K'][60][0].append(62)
MOVES['K'][60][4].append(58)
and
MOVES['p'][8 + i][IDX].append(24 + i)
MOVES['P'][55 - i][IDX].append(39 - i)

What is the issue here?

edit
Sorry: Issue was due to python2 -> python3 conversion (i.e. / vs //)
Library works as expected. thx. Can be closed.

Issue with pip installing Chessnut module

There was an issue my team and I had when writing an AI that works alongside Chessnut. For some reason, even after following the installation instructions and pip installing into a virtual environment, we were unable to capture a piece that was putting our king in check. We had checked the list of moves (from Game.get_moves()) and the move was not found.

Here is the fen of the board state:

rnb1kbnr/pppp1ppp/4p3/8/2B1P3/5N2/PPPP1P1P/RNBQK1q1 w Qkq - 0 5

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.