From 6d1f9d06dc60e4684a84a394ff30ed864c4145c0 Mon Sep 17 00:00:00 2001 From: Tibor Bizjak Date: Tue, 3 Sep 2019 23:43:32 +0200 Subject: [PATCH] Added move method and supporting methods --- chess.py | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/chess.py b/chess.py index df9ef53..452375e 100644 --- a/chess.py +++ b/chess.py @@ -48,6 +48,8 @@ class Piece: class Game: def __init__(self): self.make_board() + self.moves = [] + self.stack = [] def __repr__(self): # Unicode board representation @@ -84,6 +86,23 @@ class Game: def occupying(self, piece): return [sq for sq in squares if self.board[sq] == piece] + def move(self, source, target): + if not self.is_legal(source, target): + return False + board = self.board + moved = board[source] + eaten = board[target] + + self.moves.append((source, target)) + self.stack.append(eaten) + + board[source] = Piece() + board[target] = moved + return True + + def is_legal(self, source, target): + return target in self.possible_moves(source) + def is_attacked(self, sq): return False @@ -159,6 +178,7 @@ class Game: vecs = product([-1, 0, 1], [-1, 0, 1]) return [sq for sq in addvs(sq, vecs) if is_possible(sq) and not self.is_attacked(sq)] + return [] @@ -166,8 +186,9 @@ def test(): game = Game() assert len(squares) == 8**2 assert sum(map(len, init_positions.values())) == 8*4 - game.board["d3"] = Piece("black", "queen") - print(game) - print (game.possible_moves("d2")) + moves = [("a2", "a3"), ("b1", "c3"), ("d1", "d2")] + for m in moves: + game.move(*m) + print (game) test()