Single_Player_Chess/chess.py

65 lines
1.7 KiB
Python
Raw Normal View History

2019-09-01 21:29:25 +02:00
from unicodedata import lookup
2019-09-01 16:52:51 +02:00
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)
}
2019-09-01 21:29:25 +02:00
def unicode_repr(color, piece):
return lookup(color.upper() + " CHESS " + piece.upper())
2019-09-01 16:52:51 +02:00
class Game:
def __init__(self):
self.make_board()
2019-09-01 21:29:25 +02:00
def __repr__(self):
# Unicode board representation
r = ""
for rank in ranks:
r += rank + " |"
for file in files:
piece = self.board[file+rank]
if piece == None:
r += " "
else:
r += " " + unicode_repr(*piece)
r += "\n"
r += " +" + "-"*16 + "\n"
r += " "*4 + " ".join(list(files))
return r
2019-09-01 16:52:51 +02:00
def make_board(self):
self.board = dict((sq, None) for sq in squares)
# Add pieces
for piece, positions in init_positions.items():
for sq in positions:
self.board[sq] = piece
# Add colors
for sq in cross(files, "12"):
self.board[sq] = ("white", self.board[sq])
for sq in cross(files, "78"):
self.board[sq] = ("black", self.board[sq])
2019-09-01 21:29:25 +02:00
2019-09-01 16:52:51 +02:00
def test():
game = Game()
assert len(squares) == 8**2
assert sum(map(len, init_positions.values())) == 8*4
2019-09-01 21:29:25 +02:00
print(game)
2019-09-01 16:52:51 +02:00
test()