Skip to content

A chess game, forked and added some design patterns; A project for the university course

Notifications You must be signed in to change notification settings

meysam81/chess-python

 
 

Repository files navigation

chess

snapshot

Prerequisites

In order to run the game you need to install some dependencies:

sudo pip3 install virtualenv pillow

Quickstart

First

To start the game, first create a virtual environment and activate it:

virtualenv venv
source ./venv/bin/activate

And then run the following command in the virtual environement:

pip install -r requirements.txt

Second

Then you are able to run the game using the following command:

python main.py

Patterns Explanation

For each pattern (mentioned below) there is a module of the same name, that corresponds to that of the Gang of four published book:

In this pattern, the purpose was to have a single board item, representing the whole Board object; and it is used in the main module:

from singleton import Singleton
chess = Singleton().chess

This module's purpose was to have all the pieces initialized and have it used on demand like so in the board module:

from flyweight import PieceCreator
abbr2piece = PieceCreator()
piece = abbr2piece(letter)

This one's pretty obvious, it is implementing factory pattern to create a new instance of each piece when the flyweight requires it in it's module like so:

from factory import PieceFactory
# alias for convenience
factory = PieceFactory.factory
self.white_pawns = [factory('pawn', 'white') for _ in range(8)]
self.white_rooks = [factory('rook', 'white') for _ in range(2)]
self.white_knights = [factory('knight', 'white') for _ in range(2)]
self.white_bishops = [factory('bishop', 'white') for _ in range(2)]
self.white_queen = factory('queen', 'white')
self.white_king = factory('king', 'white')

This module is responsible for keeping the history and also it's undo process and it's used in the chess module:

def undo(self):
    last_memento = self._care_taker.pop()
    self.set_memento(last_memento)

def set_memento(self, memento):
    previous_state = pickle.loads(memento).get_state()
    vars(self).clear()
    vars(self).update(previous_state)

def create_memento(self):
    memento = Memento(vars(self))
    return pickle.dumps(memento)

Finally this module is responsible for invoking the right receiver (only used for undo process); and it's used in the gui module:

command = ConcreteCommand(self.chess.undo)
self._invoker.store_command(command)
self._invoker.execute_commands()

About

A chess game, forked and added some design patterns; A project for the university course

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Python 100.0%