From e93d09f939c63e1814eae8e4c95859f8ed0c0296 Mon Sep 17 00:00:00 2001 From: Tibor Bizjak Date: Tue, 3 Sep 2019 23:33:24 +0200 Subject: [PATCH] Added possible moves for king and pawn --- chess.py | 42 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/chess.py b/chess.py index 13f4296..df9ef53 100644 --- a/chess.py +++ b/chess.py @@ -84,6 +84,9 @@ class Game: def occupying(self, piece): return [sq for sq in squares if self.board[sq] == piece] + def is_attacked(self, sq): + return False + def possible_moves(self, sq): def is_possible(target): return target in squares and \ @@ -111,10 +114,37 @@ class Game: vecs = [ldvecs, rdvecs, negatevs(ldvecs), negatevs(rdvecs)] return sum(map(are_possible, vecs), []) - piece = self.board[sq].piece + board = self.board + piece = board[sq].piece + color = board[sq].color if piece == "pawn": - pass + r = [] + direction = (0,1) + if color == "black": + direction = (0, -1) + frwd = addv(sq, direction) + jump = addv(frwd, direction) + eatl = addv(frwd, (-1, 0)) + eatr = addv(frwd, (1, 0)) + + if is_possible(frwd) and self.is_empty(frwd): + r.append(frwd) + checklr = lambda x: is_possible(x) \ + and \ + not self.is_empty(x) \ + and \ + board[x].color != color + if checklr(eatl): + r.append(eatl) + if checklr(eatr): + r.append(eatr) + is_on_pawn_rank = (color == "black" and sq[1]=='7') \ + or \ + (color == "white" and sq[1]=='2') + if is_possible(jump) and frwd in r and self.is_empty(jump) and is_on_pawn_rank: + r.append(jump) + return r elif piece == "knight": vecs = list(product((1,-1), (2,-2))) vecs += list(product((2,-2), (1,-1))) @@ -125,6 +155,10 @@ class Game: return possible_bishop() elif piece == "queen": return possible_bishop() + possible_rook() + elif piece == "king": + 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)] @@ -132,8 +166,8 @@ def test(): game = Game() assert len(squares) == 8**2 assert sum(map(len, init_positions.values())) == 8*4 - game.board["d4"] = Piece("black", "bishop") + game.board["d3"] = Piece("black", "queen") print(game) - print (game.possible_moves("d4")) + print (game.possible_moves("d2")) test()