Added algebraic notation move method, fixed some bugs
parent
fbf001a9b2
commit
f9431d8add
56
chess.py
56
chess.py
|
@ -72,7 +72,7 @@ def parse_AN(move):
|
|||
r.move = move
|
||||
r.mate = suffix_in('#') == '#'
|
||||
r.check = suffix_in('+') == '+'
|
||||
r.promotion = suffix_in(AN_names)
|
||||
r.promotion = suffix_in(AN_names, None)
|
||||
if r.promotion:
|
||||
r.promotion = AN_names[r.promotion]
|
||||
_ = suffix_in('=')
|
||||
|
@ -181,6 +181,9 @@ class Game:
|
|||
return False
|
||||
return True
|
||||
|
||||
def endofgame(self):
|
||||
return self.is_stall() or self.is_mate()
|
||||
|
||||
def occupying(self, piece):
|
||||
return [sq for sq in squares if self.board[sq] == piece]
|
||||
|
||||
|
@ -217,6 +220,7 @@ class Game:
|
|||
self.can_castle[color]["queen"] = False
|
||||
self.can_castle[color]["king"] = False
|
||||
self.moves.append(king_move)
|
||||
self.turn = invert(self.turn)
|
||||
return True
|
||||
|
||||
def move(self, source, target, promotion=None):
|
||||
|
@ -375,17 +379,51 @@ class Game:
|
|||
return moves(sq, dirs)
|
||||
return []
|
||||
|
||||
def validate_move(self, source, dest, promotion):
|
||||
new = deepcopy(self)
|
||||
valid = new.move(source, dest, promotion)
|
||||
new.turn = self.turn
|
||||
return valid, new
|
||||
|
||||
def AN_move(self, move):
|
||||
info = parse_AN(move)
|
||||
if info == False:
|
||||
return False
|
||||
if info.queenside:
|
||||
return self.castle("queen")
|
||||
if info.kingside:
|
||||
return self.castle("king")
|
||||
|
||||
piece = info.piece
|
||||
sqrs = self.occupying(Piece(self.turn, piece))
|
||||
promotion = info.promotion
|
||||
dest = info.dest
|
||||
if info.file != None:
|
||||
sqrs = [sq for sq in sqrs if sq[0]==info.file]
|
||||
if info.rank != None:
|
||||
sqrs = [sq for sq in sqrs if sq[1]==info.rank]
|
||||
moves = []
|
||||
for sq in sqrs:
|
||||
valid, new = self.validate_move(sq, dest, promotion)
|
||||
check = new.is_check()==info.check and new.is_mate()==info.mate
|
||||
if valid and check:
|
||||
moves.append((sq, dest, promotion))
|
||||
if len(moves) != 1:
|
||||
return False
|
||||
move = moves[0]
|
||||
self.move(*move)
|
||||
return True
|
||||
|
||||
|
||||
|
||||
def test():
|
||||
game = Game()
|
||||
game.board = {sq : Piece() for sq in squares}
|
||||
game.board['a8'] = Piece("white", "king")
|
||||
game.board['f6'] = Piece("black", "pawn")
|
||||
game.board['f5'] = Piece("white", "pawn")
|
||||
game.board['c7'] = Piece("black", "queen")
|
||||
game.board['h1'] = Piece("black", "king")
|
||||
print(game, game.is_stall())
|
||||
print(game.all_legal_moves())
|
||||
while not game.is_stall():
|
||||
move = input(">> ")
|
||||
v = game.AN_move(move)
|
||||
if not v:
|
||||
print("Invalid")
|
||||
continue
|
||||
print(game)
|
||||
|
||||
test()
|
||||
|
|
Loading…
Reference in New Issue