Added move method and supporting methods
parent
e93d09f939
commit
6d1f9d06dc
27
chess.py
27
chess.py
|
@ -48,6 +48,8 @@ class Piece:
|
||||||
class Game:
|
class Game:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.make_board()
|
self.make_board()
|
||||||
|
self.moves = []
|
||||||
|
self.stack = []
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
# Unicode board representation
|
# Unicode board representation
|
||||||
|
@ -84,6 +86,23 @@ class Game:
|
||||||
def occupying(self, piece):
|
def occupying(self, piece):
|
||||||
return [sq for sq in squares if self.board[sq] == 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):
|
def is_attacked(self, sq):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
@ -159,6 +178,7 @@ class Game:
|
||||||
vecs = product([-1, 0, 1], [-1, 0, 1])
|
vecs = product([-1, 0, 1], [-1, 0, 1])
|
||||||
return [sq for sq in addvs(sq, vecs)
|
return [sq for sq in addvs(sq, vecs)
|
||||||
if is_possible(sq) and not self.is_attacked(sq)]
|
if is_possible(sq) and not self.is_attacked(sq)]
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -166,8 +186,9 @@ def test():
|
||||||
game = Game()
|
game = Game()
|
||||||
assert len(squares) == 8**2
|
assert len(squares) == 8**2
|
||||||
assert sum(map(len, init_positions.values())) == 8*4
|
assert sum(map(len, init_positions.values())) == 8*4
|
||||||
game.board["d3"] = Piece("black", "queen")
|
moves = [("a2", "a3"), ("b1", "c3"), ("d1", "d2")]
|
||||||
print(game)
|
for m in moves:
|
||||||
print (game.possible_moves("d2"))
|
game.move(*m)
|
||||||
|
print (game)
|
||||||
|
|
||||||
test()
|
test()
|
||||||
|
|
Loading…
Reference in New Issue