73 lines
1.9 KiB
Python
73 lines
1.9 KiB
Python
from unicodedata import lookup
|
|
|
|
def cross(A, B):
|
|
return tuple(a+b for a in A for b in B)
|
|
|
|
ranks = "12345678"
|
|
files = "abcdefgh"
|
|
squares = cross(files, ranks)
|
|
|
|
pawn_ranks = "27"
|
|
home_ranks = "18"
|
|
init_positions = {"pawn" : cross(files, pawn_ranks),
|
|
"rook" : cross("ah", home_ranks),
|
|
"knight" : cross("bg", home_ranks),
|
|
"bishop" : cross("cf", home_ranks),
|
|
"queen" : cross("d", home_ranks),
|
|
"king" : cross("e", home_ranks)
|
|
}
|
|
|
|
|
|
class Piece:
|
|
def __init__(self, color=None, piece=None):
|
|
self.color = color
|
|
self.piece = piece
|
|
|
|
def __repr__(self):
|
|
if None in (self.piece, self.color):
|
|
return None
|
|
name = self.color.upper() + " CHESS " + self.piece.upper()
|
|
return lookup(name)
|
|
|
|
class Game:
|
|
def __init__(self):
|
|
self.make_board()
|
|
|
|
def __repr__(self):
|
|
# Unicode board representation
|
|
r = ""
|
|
for rank in ranks:
|
|
r += rank + " |"
|
|
for file in files:
|
|
piece = self.board[file+rank]
|
|
if piece.piece == None:
|
|
r += " "
|
|
else:
|
|
r += " " + repr(piece)
|
|
r += "\n"
|
|
r += " +" + "-"*16 + "\n"
|
|
r += " "*4 + " ".join(list(files))
|
|
return r
|
|
|
|
def make_board(self):
|
|
self.board = dict((sq, Piece()) for sq in squares)
|
|
# Add pieces
|
|
for piece, positions in init_positions.items():
|
|
for sq in positions:
|
|
self.board[sq].piece = piece
|
|
# Add colors
|
|
for sq in cross(files, "12"):
|
|
self.board[sq].color = "white"
|
|
for sq in cross(files, "78"):
|
|
self.board[sq].color = "black"
|
|
|
|
|
|
|
|
def test():
|
|
game = Game()
|
|
assert len(squares) == 8**2
|
|
assert sum(map(len, init_positions.values())) == 8*4
|
|
print(game)
|
|
|
|
test()
|