home *** CD-ROM | disk | FTP | other *** search
- # Source Generated with Decompyle++
- # File: in.pyc (Python 2.6)
-
- '''
- '''
- __author__ = 'Robert Ancell <bob27@users.sourceforge.net>'
- __license__ = 'GNU General Public License Version 2'
- __copyright__ = 'Copyright 2005-2006 Robert Ancell'
- import chess.board as chess
- import chess.san as chess
- RESULT_IN_PROGRESS = '*'
- RESULT_WHITE_WINS = '1-0'
- RESULT_BLACK_WINS = '0-1'
- RESULT_DRAW = '1/2-1/2'
- RULE_CHECKMATE = 'CHECKMATE'
- RULE_STALEMATE = 'STALEMATE'
- RULE_TIMEOUT = 'TIMEOUT'
- RULE_FIFTY_MOVES = 'FIFTY_MOVES'
- RULE_THREE_FOLD_REPETITION = 'THREE_FOLD_REPETITION'
- RULE_INSUFFICIENT_MATERIAL = 'INSUFFICIENT_MATERIAL'
- RULE_RESIGN = 'RESIGN'
- RULE_DEATH = 'DEATH'
- RULE_AGREEMENT = 'AGREEMENT'
- RULE_ABANDONMENT = 'ABANDONMENT'
-
- class ChessMove:
- '''
- '''
- number = 0
- player = None
- piece = None
- promotion = None
- victim = None
- start = None
- end = None
- canMove = ''
- sanMove = ''
- opponentInCheck = False
- opponentCanMove = False
- fiftyMoveRule = False
- threeFoldRepetition = False
- comment = ''
- nag = ''
-
-
- class ChessPlayer:
- '''
- '''
- __name = None
- __game = None
- __readyToMove = False
-
- def __init__(self, name):
- """Constructor for a chess player.
-
- 'name' is the name of the player.
- """
- self._ChessPlayer__name = str(name)
- self.isAlive = True
-
-
- def onPieceMoved(self, piece, start, end, delete):
- """Called when a chess piece is moved.
-
- 'piece' is the piece that has been moved (chess.board.ChessPiece).
- 'start' is the location the piece in LAN format (string) or None if the piece has been created.
- 'end' is the location the piece has moved to in LAN format (string).
- 'delete' is a flag to show if the piece should be deleted when it arrives there (boolean).
- """
- pass
-
-
- def onPlayerMoved(self, player, move):
- """Called when a player has moved.
-
- 'player' is the player that has moved (ChessPlayer).
- 'move' is the record for this move (ChessMove).
- """
- pass
-
-
- def onUndoMove(self):
- pass
-
-
- def onPlayerStartTurn(self, player):
- pass
-
-
- def onGameEnded(self, game):
- """Called when a chess game has ended.
-
- 'game' is the game that has ended (Game).
- """
- pass
-
-
- def readyToMove(self):
- '''FIXME
- '''
- pass
-
-
- def getName(self):
- '''Get the name of this player.
-
- Returns the player name (string).
- '''
- return self._ChessPlayer__name
-
-
- def getGame(self):
- '''Get the game this player is in.
-
- Returns the game (Game) or None if not in a game.
- '''
- return self._ChessPlayer__game
-
-
- def getRemainingTime(self):
- '''Get the amount of time this player has remaining.
-
- Returns the amount of time in milliseconds.
- '''
- if self is self._ChessPlayer__game.getWhite():
- timer = self._ChessPlayer__game.whiteTimer
- elif self is self._ChessPlayer__game.getBlack():
- timer = self._ChessPlayer__game.blackTimer
- else:
- return 0
- if self is self._ChessPlayer__game.getWhite() is None:
- return 0
- return timer.controller.getRemaining()
-
-
- def isReadyToMove(self):
- '''
- '''
- return self._ChessPlayer__readyToMove
-
-
- def canMove(self, start, end, promotionType = chess.board.QUEEN):
- '''
- '''
- return self._ChessPlayer__game.canMove(self, start, end, promotionType)
-
-
- def move(self, move):
- """Move a piece.
-
- 'move' is the move to make in Normal/Long/Standard Algebraic format (string).
- """
- self._ChessPlayer__game.move(self, move)
-
-
- def undo(self):
- '''Undo moves until it is this players turn'''
- self._ChessPlayer__game.undo(self)
-
-
- def endMove(self):
- '''Complete this players turn'''
- self._ChessPlayer__game.endMove(self)
-
-
- def resign(self):
- '''Resign from the game'''
- self._ChessPlayer__game.resign(self)
-
-
- def claimDraw(self):
- '''Claim a draw'''
- return self._ChessPlayer__game.claimDraw()
-
-
- def outOfTime(self):
- '''Report this players timer has expired'''
- self._ChessPlayer__game.outOfTime(self)
-
-
- def die(self):
- '''Report this player has died'''
- self.isAlive = False
- if self._ChessPlayer__game is not None:
- self._ChessPlayer__game.killPlayer(self)
-
-
-
- def _setGame(self, game):
- '''
- '''
- self._ChessPlayer__game = game
-
-
- def _setReadyToMove(self, readyToMove):
- if self._ChessPlayer__readyToMove == readyToMove:
- return None
- self._ChessPlayer__readyToMove = readyToMove
- if readyToMove is True:
- self.readyToMove()
-
-
-
-
- class ChessGameBoard(chess.board.ChessBoard):
- '''
- '''
- __game = None
-
- def __init__(self, game):
- '''
- '''
- self._ChessGameBoard__game = game
- chess.board.ChessBoard.__init__(self)
-
-
- def onPieceMoved(self, piece, start, end, delete):
- '''Called by chess.board.ChessBoard'''
- self._ChessGameBoard__game._onPieceMoved(piece, start, end, delete)
-
-
-
- class ChessGameSANConverter(chess.san.SANConverter):
- '''
- '''
- __colourToSAN = {
- chess.board.WHITE: chess.san.SANConverter.WHITE,
- chess.board.BLACK: chess.san.SANConverter.BLACK }
- __sanToColour = { }
- for a, b in __colourToSAN.iteritems():
- __sanToColour[b] = a
-
- __typeToSAN = {
- chess.board.PAWN: chess.san.SANConverter.PAWN,
- chess.board.KNIGHT: chess.san.SANConverter.KNIGHT,
- chess.board.BISHOP: chess.san.SANConverter.BISHOP,
- chess.board.ROOK: chess.san.SANConverter.ROOK,
- chess.board.QUEEN: chess.san.SANConverter.QUEEN,
- chess.board.KING: chess.san.SANConverter.KING }
- __sanToType = { }
- for a, b in __typeToSAN.iteritems():
- __sanToType[b] = a
-
-
- def __init__(self, board, moveNumber):
- self.board = board
- self.moveNumber = moveNumber
- chess.san.SANConverter.__init__(self)
-
-
- def decode(self, colour, move):
- (start, end, result, promotionType) = chess.san.SANConverter.decode(self, self._ChessGameSANConverter__colourToSAN[colour], move)
- return (start, end, self._ChessGameSANConverter__sanToType[promotionType])
-
-
- def encode(self, start, end, isTake, promotionType):
- if promotionType is None:
- promotion = self.QUEEN
- else:
- promotion = self._ChessGameSANConverter__typeToSAN[promotionType]
- return chess.san.SANConverter.encode(self, start, end, isTake, promotion)
-
-
- def getPiece(self, location):
- '''Called by chess.san.SANConverter'''
- piece = self.board.getPiece(location, self.moveNumber)
- if piece is None:
- return None
- return (self._ChessGameSANConverter__colourToSAN[piece.getColour()], self._ChessGameSANConverter__typeToSAN[piece.getType()])
-
-
- def testMove(self, colour, start, end, promotionType, allowSuicide = False):
- '''Called by chess.san.SANConverter'''
- move = self.board.testMove(self._ChessGameSANConverter__sanToColour[colour], start, end, self._ChessGameSANConverter__sanToType[promotionType], allowSuicide, self.moveNumber)
- if move is None:
- return False
- if move.opponentInCheck:
- if not move.opponentCanMove:
- return chess.san.SANConverter.CHECKMATE
- return chess.san.SANConverter.CHECK
- return True
-
-
-
- class ChessGame:
- '''
- '''
- __players = None
- __whitePlayer = None
- __blackPlayer = None
- __spectators = None
- board = None
- __started = False
- __currentPlayer = None
- __moves = None
- __inCallback = False
- __queuedCalls = None
- result = RESULT_IN_PROGRESS
- rule = None
- whiteTimer = None
- blackTimer = None
-
- def __init__(self):
- '''Game constructor'''
- self._ChessGame__players = []
- self._ChessGame__spectators = []
- self.board = ChessGameBoard(self)
- self._ChessGame__moves = []
- self._ChessGame__queuedCalls = []
-
-
- def getAlivePieces(self, moveNumber = -1):
- """Get the alive pieces on the board.
-
- 'moveNumber' is the move to get the pieces from (integer).
-
- Returns a dictionary of the alive pieces (board.ChessPiece) keyed by location.
- Raises an IndexError exception if moveNumber is invalid.
- """
- return self.board.getAlivePieces(moveNumber)
-
-
- def getDeadPieces(self, moveNumber = -1):
- """Get the dead pieces from the game.
-
- 'moveNumber' is the move to get the pieces from (integer).
-
- Returns a list of the pieces (board.ChessPiece) in the order they were killed.
- Raises an IndexError exception if moveNumber is invalid.
- """
- return self.board.getDeadPieces(moveNumber)
-
-
- def setTimers(self, whiteTimer, blackTimer):
- '''
- '''
- self.whiteTimer = whiteTimer
- self.blackTimer = blackTimer
-
-
- def setWhite(self, player):
- """Set the white player in the game.
-
- 'player' is the player to use as white.
-
- If the game has started or there is a white player an exception is thrown.
- """
- if not self._ChessGame__started is False:
- raise AssertionError
- if not self._ChessGame__whitePlayer is None:
- raise AssertionError
- self._ChessGame__whitePlayer = player
- self._ChessGame__connectPlayer(player)
-
-
- def getWhite(self):
- '''Returns the current white player (player.Player)'''
- return self._ChessGame__whitePlayer
-
-
- def setBlack(self, player):
- """Set the black player in the game.
-
- 'player' is the player to use as black.
-
- If the game has started or there is a black player an exception is thrown.
- """
- if not self._ChessGame__started is False:
- raise AssertionError
- if not self._ChessGame__blackPlayer is None:
- raise AssertionError
- self._ChessGame__blackPlayer = player
- self._ChessGame__connectPlayer(player)
-
-
- def getBlack(self):
- '''Returns the current white player (player.Player)'''
- return self._ChessGame__blackPlayer
-
-
- def getCurrentPlayer(self):
- '''Get the player to move'''
- return self._ChessGame__currentPlayer
-
-
- def addSpectator(self, player):
- """Add a spectator to the game.
-
- 'player' is the player spectating.
-
- This can be called after the game has started.
- """
- self._ChessGame__spectators.append(player)
- self._ChessGame__connectPlayer(player)
-
-
- def isStarted(self):
- '''Returns True if the game has been started'''
- return self._ChessGame__started
-
-
- def start(self, moves = []):
- """Start the game.
-
- 'moves' is a list of moves to start with.
-
- If there is no white or black player then an exception is raised.
- """
- if not self._ChessGame__whitePlayer is not None or self._ChessGame__blackPlayer is not None:
- raise AssertionError
- self._ChessGame__currentPlayer = self._ChessGame__whitePlayer
- for move in moves:
- self.move(self._ChessGame__currentPlayer, move)
- if self._ChessGame__currentPlayer is self._ChessGame__whitePlayer:
- self._ChessGame__currentPlayer = self._ChessGame__blackPlayer
- continue
- self._ChessGame__blackPlayer is not None
- self._ChessGame__currentPlayer = self._ChessGame__whitePlayer
-
- self._ChessGame__started = True
- if not self._ChessGame__whitePlayer.isAlive:
- self.killPlayer(self._ChessGame__whitePlayer)
- return None
- if not self._ChessGame__blackPlayer.isAlive:
- self.killPlayer(self._ChessGame__blackPlayer)
- return None
- if self.result != RESULT_IN_PROGRESS:
- self._notifyEndGame()
- return None
- self.startLock()
- for player in self._ChessGame__players:
- player.onPlayerStartTurn(self._ChessGame__currentPlayer)
-
- self._ChessGame__currentPlayer._setReadyToMove(True)
- self.endLock()
-
-
- def getSquareOwner(self, coord):
- '''TODO
- '''
- piece = self.board.getPiece(coord)
- if piece is None:
- return None
- colour = piece.getColour()
- if colour is chess.board.WHITE:
- return self._ChessGame__whitePlayer
- if colour is chess.board.BLACK:
- return self._ChessGame__blackPlayer
- return None
-
-
- def canMove(self, player, start, end, promotionType):
- """Test if a player can move.
-
- 'player' is the player making the move.
- 'start' is the location to move from in LAN format (string).
- 'end' is the location to move from in LAN format (string).
- 'promotionType' is the piece type to promote pawns to. FIXME: Make this a property of the player
-
- Return True if can move, otherwise False.
- """
- if player is not self._ChessGame__currentPlayer:
- return False
- if player is self._ChessGame__whitePlayer:
- colour = chess.board.WHITE
- elif player is self._ChessGame__blackPlayer:
- colour = chess.board.BLACK
- elif not False:
- raise AssertionError
- move = self.board.testMove(colour, start, end, promotionType = promotionType)
- return move is not None
-
-
- def move(self, player, move):
- """Get a player to make a move.
-
- 'player' is the player making the move.
- 'move' is the move to make in SAN or LAN format (string).
- """
- if self._ChessGame__inCallback:
- self._ChessGame__queuedCalls.append((self.move, (player, move)))
- return None
- self.startLock()
- self.endLock()
-
-
- def undo(self, player):
- if self._ChessGame__inCallback:
- self._ChessGame__queuedCalls.append((self.undo, (player,)))
- return None
- self.startLock()
- self._ChessGame__whitePlayer._setReadyToMove(False)
- self._ChessGame__blackPlayer._setReadyToMove(False)
- if player is self._ChessGame__whitePlayer:
- self._ChessGame__currentPlayer = self._ChessGame__blackPlayer
- else:
- self._ChessGame__currentPlayer = self._ChessGame__whitePlayer
- if len(self._ChessGame__moves) > 0 and self._ChessGame__moves[-1].player is not player:
- count = 2
- else:
- count = 1
- for i in xrange(count):
- if len(self._ChessGame__moves) != 0:
- self.board.undo()
- self._ChessGame__moves = self._ChessGame__moves[:-1]
- for p in self._ChessGame__players:
- p.onUndoMove()
-
-
- self.endLock()
-
-
- def startLock(self):
- if not self._ChessGame__inCallback is False:
- raise AssertionError
- self._ChessGame__inCallback = True
-
-
- def endLock(self):
- self._ChessGame__inCallback = False
- while len(self._ChessGame__queuedCalls) > 0:
- (call, args) = self._ChessGame__queuedCalls[0]
- self._ChessGame__queuedCalls = self._ChessGame__queuedCalls[1:]
- call(*args)
-
-
- def _move(self, player, move):
- '''
- '''
- if self.result != RESULT_IN_PROGRESS:
- print 'Game completed'
- return None
- if self._ChessGame__currentPlayer is self._ChessGame__whitePlayer:
- colour = chess.board.WHITE
- else:
- colour = chess.board.BLACK
-
- try:
- (start, end, _, _, promotionType, _) = chess.lan.decode(colour, move)
- except chess.lan.DecodeError:
- e = None
- converter = ChessGameSANConverter(self.board, len(self._ChessGame__moves))
-
- try:
- (start, end, promotionType) = converter.decode(colour, move)
- except chess.san.Error:
- e = None
- print 'Invalid move: ' + move
- return None
-
-
- None<EXCEPTION MATCH>chess.san.Error
-
- piece = self.board.getPiece(start)
- promotion = None
- if piece is not None and piece.getType() is chess.board.PAWN:
- if colour is chess.board.WHITE:
- if end[1] == '8':
- promotion = promotionType
-
- elif end[1] == '1':
- promotion = promotionType
-
-
- moveResult = self.board.movePiece(colour, start, end, promotionType)
- if moveResult is None:
- print 'Illegal move: ' + str(move)
- return None
- canMove = chess.lan.encode(colour, start, end, promotionType = promotion)
- converter = ChessGameSANConverter(self.board, len(self._ChessGame__moves))
-
- try:
- sanMove = converter.encode(start, end, moveResult.victim != None, promotionType)
- except chess.san.Error:
- moveResult is None
- moveResult is None
- sanMove = canMove
- except:
- moveResult is None
-
- m = ChessMove()
- if len(self._ChessGame__moves) == 0:
- m.number = 1
- else:
- m.number = self._ChessGame__moves[-1].number + 1
- m.player = self._ChessGame__currentPlayer
- m.piece = piece
- m.victim = moveResult.victim
- m.start = start
- m.end = end
- m.canMove = canMove
- m.sanMove = sanMove
- m.opponentInCheck = moveResult.opponentInCheck
- m.opponentCanMove = moveResult.opponentCanMove
- m.fiftyMoveRule = moveResult.fiftyMoveRule
- m.threeFoldRepetition = moveResult.threeFoldRepetition
- self._ChessGame__moves.append(m)
- self._ChessGame__currentPlayer._setReadyToMove(False)
- for player in self._ChessGame__players:
- player.onPlayerMoved(self._ChessGame__currentPlayer, m)
-
- result = RESULT_IN_PROGRESS
- if not m.opponentCanMove:
- if self._ChessGame__currentPlayer is self._ChessGame__whitePlayer:
- result = RESULT_WHITE_WINS
- else:
- result = RESULT_BLACK_WINS
- if m.opponentInCheck:
- rule = RULE_CHECKMATE
- else:
- result = RESULT_DRAW
- rule = RULE_STALEMATE
-
- if not self.board.sufficientMaterial():
- result = RESULT_DRAW
- rule = RULE_INSUFFICIENT_MATERIAL
-
- if result is not RESULT_IN_PROGRESS:
- self.endGame(result, rule)
-
-
-
- def endMove(self, player):
- '''
- '''
- if self._ChessGame__inCallback:
- self._ChessGame__queuedCalls.append((self.endMove, (player,)))
- return None
- if player is not self._ChessGame__currentPlayer:
- print 'Player attempted to move out of turn'
- return None
- if player.move is None:
- print "Ending move when haven't made one"
- return None
- self.startLock()
- for player in self._ChessGame__players:
- player.onPlayerStartTurn(self._ChessGame__currentPlayer)
-
- if self._ChessGame__started is True and self.result == RESULT_IN_PROGRESS:
- self._ChessGame__currentPlayer._setReadyToMove(True)
-
- self.endLock()
-
-
- def resign(self, player):
- """Get a player to resign.
-
- 'player' is the player resigning.
- """
- rule = RULE_RESIGN
- if player is self._ChessGame__whitePlayer:
- self.endGame(RESULT_BLACK_WINS, rule)
- else:
- self.endGame(RESULT_WHITE_WINS, rule)
-
-
- def claimDraw(self):
- '''
- '''
-
- try:
- move = self._ChessGame__moves[-1]
- except IndexError:
- return False
-
- if move.fiftyMoveRule:
- rule = RULE_FIFTY_MOVES
- elif move.threeFoldRepetition:
- rule = RULE_THREE_FOLD_REPETITION
- else:
- return False
- move.fiftyMoveRule.endGame(RESULT_DRAW, rule)
- return True
-
-
- def killPlayer(self, player):
- """Report a player has died
-
- 'player' is the player that has died.
- """
- if player is self._ChessGame__whitePlayer:
- result = RESULT_BLACK_WINS
- elif player is self._ChessGame__blackPlayer:
- result = RESULT_WHITE_WINS
-
- self.endGame(result, RULE_DEATH)
-
-
- def outOfTime(self, player):
- """Report a player's timer has expired"""
- if player is self._ChessGame__whitePlayer:
- result = RESULT_BLACK_WINS
- elif player is self._ChessGame__blackPlayer:
- result = RESULT_WHITE_WINS
- elif not False:
- raise AssertionError
- self.endGame(result, RULE_TIMEOUT)
-
-
- def abandon(self):
- self.endGame(RESULT_DRAW, RULE_ABANDONMENT)
-
-
- def endGame(self, result, rule):
- if self.result != RESULT_IN_PROGRESS:
- return None
- self.result = result
- self.rule = rule
- if self.isStarted():
- self._notifyEndGame()
-
-
-
- def _notifyEndGame(self):
- self._ChessGame__currentPlayer._setReadyToMove(False)
- for player in self._ChessGame__players:
- player.onGameEnded(self)
-
-
-
- def getMoves(self):
- '''
- '''
- return self._ChessGame__moves
-
-
- def abort(self):
- '''End the game'''
- for player in self._ChessGame__players:
- player.onGameEnded(self)
-
-
-
- def __connectPlayer(self, player):
- """Add a player into the game.
-
- 'player' is the player to add.
-
- The player will be notified of the current state of the board.
- """
- self._ChessGame__players.append(player)
- player._setGame(self)
- for file in '12345678':
- for rank in 'abcdefgh':
- coord = rank + file
- piece = self.board.getPiece(coord)
- if piece is None:
- continue
-
- player.onPieceMoved(piece, None, coord, False)
-
-
-
-
- def _onPieceMoved(self, piece, start, end, delete):
- '''Called by the chess board'''
- for player in self._ChessGame__players:
- player.onPieceMoved(piece, start, end, delete)
-
-
-
-
- class NetworkChessGame(ChessGame):
- '''
- '''
-
- def move(self, player, move):
- """Get a player to make a move.
-
- 'player' is the player making the move.
- 'move' is the move to make. It can be of the form:
- A coordinate move in the form ((file0, rank0), (file1, rank1), promotionType) ((int, int), (int, int), chess.board.PIECE_TYPE) or
- A SAN move (string).
- """
- pass
-
-
- if __name__ == '__main__':
- game = ChessGame()
- import pgn
- p = pgn.PGN('black.pgn')
- g = p.getGame(0)
-
- class PGNPlayer(ChessPlayer):
- __moveNumber = 1
- __isWhite = True
-
- def __init__(self, isWhite):
- self._PGNPlayer__isWhite = isWhite
-
-
- def readyToMove(self):
- if self._PGNPlayer__isWhite:
- move = g.getWhiteMove(self._PGNPlayer__moveNumber)
- else:
- move = g.getBlackMove(self._PGNPlayer__moveNumber)
- self._PGNPlayer__moveNumber += 1
- self.move(move)
-
-
- white = PGNPlayer(True)
- black = PGNPlayer(False)
- game.setWhite(white)
- game.setBlack(black)
- game.start()
-
-