Skip to content

Instantly share code, notes, and snippets.

@dionyziz
Created July 2, 2020 21:59
Show Gist options
  • Save dionyziz/2929c020219900a72ad1c98760d325da to your computer and use it in GitHub Desktop.
Save dionyziz/2929c020219900a72ad1c98760d325da to your computer and use it in GitHub Desktop.
import pprint, math
pp = pprint.PrettyPrinter()
class Piece:
def __init__(self, color):
self.color = color
def __repr__(self):
color_str_from_bool = {
False: 'w',
True: 'b'
}
return self.letter + ' (' + color_str_from_bool[self.color] + ')'
class Pawn(Piece):
letter = '-'
class King(Piece):
letter = 'K'
class Queen(Piece):
letter = 'Q'
class Rook(Piece):
letter = 'R'
class Knight(Piece):
letter = 'N'
class Bishop(Piece):
letter = 'B'
piece_classes = [Pawn, King, Queen, Rook, Knight, Bishop]
piece_from_letter = {}
for piece_class in piece_classes:
piece_from_letter[piece_class.letter] = piece_class
class Board:
N = 8
initial_chessboard = \
"""R]N]B]Q]K]B]N]R]
-]-]-]-]-]-]-]-]
-[-[-[-[-[-[-[-[
R[N[B[Q[K[B[N[R["""
def __init__(self):
self.chessboard = []
for _ in range(Board.N):
row = []
for _ in range(Board.N):
row.append(None)
self.chessboard.append(row)
def initialize_positions(self):
lines = Board.initial_chessboard.splitlines()
stripped_lines = []
for line in lines:
stripped_lines.append(line.strip())
for row, line in enumerate(stripped_lines):
for i in range(0, len(line), 2):
piece_type = line[i]
piece_color = line[i + 1]
piece_class = piece_from_letter[piece_type]
assert(piece_color in ('[', ']'))
color = piece_color == ']'
piece = piece_class(color)
self.chessboard[row][i//2] = piece
def available_moves(self, row, col):
moves = []
piece = self.chessboard[row][col]
if piece is None:
return []
print(piece.letter)
for candidate_row, line in enumerate(self.chessboard):
for candidate_col, current_piece in enumerate(line):
if self.chessboard[candidate_row][candidate_col] is None:
if abs(candidate_row - row) == abs(candidate_col - col):
moves.append((candidate_row, candidate_col))
return moves
board = Board()
board.initialize_positions()
moves = board.available_moves(7, 5)
print(moves)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment