<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import signal
import re
from string import ascii_uppercase
from time import time
from random import randint
import argparse
import select

''' Helper Functions '''
def x(code = 0):
  sys.exit(code)
''' ############### '''

class Piece(object):
  '''
  Object model of a chess piece
  
  We keep information on what kind of movements the piece is able to make (straight, diagonal, gamma),
  how many squares it can cross in a single move, its type (of course) and the color (white or black).     
  '''
  DirectionDiagonal = False
  DirectionStraight = False
  DirectionGamma = False
  LeapOverPiece = False
  MaxSquares = 0
  Color = None
  Type = None
  AvailableTypes = [ 'Rook', 'Knight', 'Pawn', 'King', 'Queen', 'Bishop' ]
  Types_Direction_Map = {
      'Rook'   : [ 'straight' ],
      'Knight' : [ 'gamma' ],
      'Pawn'   : [ 'straight' ],
      'King'   : [ 'straight', 'diagonal' ],
      'Queen'  : [ 'straight', 'diagonal' ],
      'Bishop' : [ 'diagonal' ]
    }
  Types_MaxSquares_Map = {
    'Rook'   : 0,
    'Pawn'   : 1,
    'King'   : 1,
    'Queen'  : 0,
    'Bishop' : 0,
    'Knight' : -1,
  }

  def __init__(self, **kwargs):
    ''' Constructor for a new chess piece '''
    self.Type = kwargs['Type']
    ''' Perform a basic check for the type '''
    if not self.Type in self.AvailableTypes:
      raise Exception('Unknown Piece Type')
      x(1)
    self.Color = kwargs['Color']
    directions = self.Types_Direction_Map[self.Type]
    ''' Check allowed directions for movement '''
    self.DirectionDiagonal = 'diagonal' in directions
    self.DirectionGamma = 'gamma' in directions
    self.DirectionStraight = 'straight' in directions
    ''' Determine if there is a limitation on the number of squares per move '''
    self.MaxSquares = self.Types_MaxSquares_Map[self.Type]
    ''' Only Knights can move over other pieces '''
    if self.Type == 'Knight':
      self.LeapOverPiece = True

  def __str__(self):
    ''' Returns the piece's string representation: color and type '''
    return self.Color[0].lower() + self.Type[0].upper()
        
class Square(object):
  '''
  Object model of a board square

  Requires zero-based row & column indexes.
  The Piece variable holds an instance of Piece class,
  representing a piece occupying the square.
  '''
  Row = 0
  Column = 0
  Occupied = False
  Piece = None

  def __init__(self, row, column):
    ''' Square constructor requires zero-based row & column indexes '''
    self.Row = row
    self.Column = column

  def is_occupied(self):
    ''' Returns True if the square has a piece attached to it, False otherwise '''
    return self.Occupied

  def set_piece(self, piece):
    ''' Sets the piece for a square and resets the Occupied variable accordingly '''
    if piece is None:
      self.Occupied = False
    else:
      self.Occupied = True
    self.Piece = piece

  def get_piece(self):
    ''' Getter method to return the piece attached to this square instance '''
    return self.Piece

  @staticmethod
  def row_index(row):
    ''' static method that returns the zero-based row index '''
    return int(row) - 1
  
  @staticmethod
  def column_index(col):
    ''' static method that returns the zero-based column index '''
    try:
      col = int(col) - 1
    except:
      col = ascii_uppercase.index(col)
    return col

  @staticmethod
  def index_column(col):
    ''' static method that returns the column letter from zero-based column index '''
    return ascii_uppercase[col]

  @staticmethod
  def position(row, col):
    ''' 
    static method to convert zero-indexed integer coordinates to board notation 
    e.g. (0,1) -> "B1"
    '''
    return ascii_uppercase[int(col)] + str(int(row) + 1)
        
  def __str__(self):
    ''' 
    Return a string representation of the square.
    If it is occupied then return the piece info as well.
    '''
    if self.Piece is None:
      piece = ""
    else:
      piece = str(self.Piece)
    properties = {
        'piece'  : piece,
        'row'    : self.Row + 1,
        'column' : ascii_uppercase[self.Column],
      }
    return '%(piece)s(%(column)s%(row)d)' % properties

class Board(object):
  '''
  Object model of the board

  Described by a dictionary (Squares) which keys are square positions 
  in their string representations (e.g. A1),
  and values the corresponding Square instances.
  '''
  Squares = {}
  ''' 
  The initial setup of the board. 
  The way that the setup is given makes it easier to 
  implement "Save Game" & "Load Game" features.
  '''
  Setup = {
      'Pawn'   : 'A2:H2|A7:H7',
      'Rook'   : 'A1,H1|A8,H8',
      'Bishop' : 'C1,F1|C8,F8',
      'Knight' : 'B1,G1|B8,G8',
      'King'   : 'E1|E8',
      'Queen'  : 'D1|D8',
    }  

  def __init__(self):
    ''' Simply construct the 64 squares '''
    for i in range(8):
      for j in range(8):
        self.Squares[Square.position(i, j)] = Square(i, j)

  def setup(self):
    ''' 
    Setup our board by assigning pieces to the squares!
    A separate method makes it easier to implement
    "Save" & "Load" features
    '''
    for piece_type, piece_range in self.Setup.iteritems():
      white, black = piece_range.split('|')
      for p in self.parse_range(white):
        self.add_piece('white', piece_type, p[0], p[1])
      for p in self.parse_range(black):
        self.add_piece('black', piece_type, p[0], p[1])
 
  def parse_range(self, r):
    '''
    Parse setup ranges (from the Setup dictionary) 
    and return a list of tuples with the square coordinates 
    to be assigned to the piece type.
    '''
    distinct = not ( ':' in r )
    separator = None
    if ':' in r:
      separator = ':'
    elif ',' in r:
      separator = ','
    if separator is None:
      r = [ r ]
    else:
      r = r.split(separator)
    if distinct:
      return [ ( Square.row_index(p[1]), Square.column_index(p[0]), ) for p in r ]
    else:
      start_column = Square.column_index(r[0][0])
      stop_column = Square.column_index(r[1][0])
      start_row = Square.row_index(r[0][1])
      stop_row = Square.row_index(r[1][1])
      r = []
      for column in range(start_column, stop_column - start_column + 1):
        r.append( ( start_row, column, ) )
      return r
  
  def add_piece(self, color, piece_type, row, column):    
    ''' Add a piece to a square in the board '''
    self.Squares[Square.position(row, column)].set_piece(Piece(Type=piece_type, Color=color))<commit_msg>Board.parse_range became private method<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import signal
import re
from string import ascii_uppercase
from time import time
from random import randint
import argparse
import select

''' Helper Functions '''
def x(code = 0):
  sys.exit(code)
''' ############### '''

class Piece(object):
  '''
  Object model of a chess piece
  
  We keep information on what kind of movements the piece is able to make (straight, diagonal, gamma),
  how many squares it can cross in a single move, its type (of course) and the color (white or black).     
  '''
  DirectionDiagonal = False
  DirectionStraight = False
  DirectionGamma = False
  LeapOverPiece = False
  MaxSquares = 0
  Color = None
  Type = None
  AvailableTypes = [ 'Rook', 'Knight', 'Pawn', 'King', 'Queen', 'Bishop' ]
  Types_Direction_Map = {
      'Rook'   : [ 'straight' ],
      'Knight' : [ 'gamma' ],
      'Pawn'   : [ 'straight' ],
      'King'   : [ 'straight', 'diagonal' ],
      'Queen'  : [ 'straight', 'diagonal' ],
      'Bishop' : [ 'diagonal' ]
    }
  Types_MaxSquares_Map = {
    'Rook'   : 0,
    'Pawn'   : 1,
    'King'   : 1,
    'Queen'  : 0,
    'Bishop' : 0,
    'Knight' : -1,
  }

  def __init__(self, **kwargs):
    ''' Constructor for a new chess piece '''
    self.Type = kwargs['Type']
    ''' Perform a basic check for the type '''
    if not self.Type in self.AvailableTypes:
      raise Exception('Unknown Piece Type')
      x(1)
    self.Color = kwargs['Color']
    directions = self.Types_Direction_Map[self.Type]
    ''' Check allowed directions for movement '''
    self.DirectionDiagonal = 'diagonal' in directions
    self.DirectionGamma = 'gamma' in directions
    self.DirectionStraight = 'straight' in directions
    ''' Determine if there is a limitation on the number of squares per move '''
    self.MaxSquares = self.Types_MaxSquares_Map[self.Type]
    ''' Only Knights can move over other pieces '''
    if self.Type == 'Knight':
      self.LeapOverPiece = True

  def __str__(self):
    ''' Returns the piece's string representation: color and type '''
    return self.Color[0].lower() + self.Type[0].upper()
        
class Square(object):
  '''
  Object model of a board square

  Requires zero-based row & column indexes.
  The Piece variable holds an instance of Piece class,
  representing a piece occupying the square.
  '''
  Row = 0
  Column = 0
  Occupied = False
  Piece = None

  def __init__(self, row, column):
    ''' Square constructor requires zero-based row & column indexes '''
    self.Row = row
    self.Column = column

  def is_occupied(self):
    ''' Returns True if the square has a piece attached to it, False otherwise '''
    return self.Occupied

  def set_piece(self, piece):
    ''' Sets the piece for a square and resets the Occupied variable accordingly '''
    if piece is None:
      self.Occupied = False
    else:
      self.Occupied = True
    self.Piece = piece

  def get_piece(self):
    ''' Getter method to return the piece attached to this square instance '''
    return self.Piece

  @staticmethod
  def row_index(row):
    ''' static method that returns the zero-based row index '''
    return int(row) - 1
  
  @staticmethod
  def column_index(col):
    ''' static method that returns the zero-based column index '''
    try:
      col = int(col) - 1
    except:
      col = ascii_uppercase.index(col)
    return col

  @staticmethod
  def index_column(col):
    ''' static method that returns the column letter from zero-based column index '''
    return ascii_uppercase[col]

  @staticmethod
  def position(row, col):
    ''' 
    static method to convert zero-indexed integer coordinates to board notation 
    e.g. (0,1) -> "B1"
    '''
    return ascii_uppercase[int(col)] + str(int(row) + 1)
        
  def __str__(self):
    ''' 
    Return a string representation of the square.
    If it is occupied then return the piece info as well.
    '''
    if self.Piece is None:
      piece = ""
    else:
      piece = str(self.Piece)
    properties = {
        'piece'  : piece,
        'row'    : self.Row + 1,
        'column' : ascii_uppercase[self.Column],
      }
    return '%(piece)s(%(column)s%(row)d)' % properties

class Board(object):
  '''
  Object model of the board

  Described by a dictionary (Squares) which keys are square positions 
  in their string representations (e.g. A1),
  and values the corresponding Square instances.
  '''
  Squares = {}
  ''' 
  The initial setup of the board. 
  The way that the setup is given makes it easier to 
  implement "Save Game" & "Load Game" features.
  '''
  Setup = {
      'Pawn'   : 'A2:H2|A7:H7',
      'Rook'   : 'A1,H1|A8,H8',
      'Bishop' : 'C1,F1|C8,F8',
      'Knight' : 'B1,G1|B8,G8',
      'King'   : 'E1|E8',
      'Queen'  : 'D1|D8',
    }  

  def __init__(self):
    ''' Simply construct the 64 squares '''
    for i in range(8):
      for j in range(8):
        self.Squares[Square.position(i, j)] = Square(i, j)

  def setup(self):
    ''' 
    Setup our board by assigning pieces to the squares!
    A separate method makes it easier to implement
    "Save" & "Load" features
    '''
    for piece_type, piece_range in self.Setup.iteritems():
      white, black = piece_range.split('|')
      for p in self.__parse_range(white):
        self.add_piece('white', piece_type, p[0], p[1])
      for p in self.__parse_range(black):
        self.add_piece('black', piece_type, p[0], p[1])
 
  def __parse_range(self, r):
    '''
    Parse setup ranges (from the Setup dictionary) 
    and return a list of tuples with the square coordinates 
    to be assigned to the piece type.
    '''
    distinct = not ( ':' in r )
    separator = None
    if ':' in r:
      separator = ':'
    elif ',' in r:
      separator = ','
    if separator is None:
      r = [ r ]
    else:
      r = r.split(separator)
    if distinct:
      return [ ( Square.row_index(p[1]), Square.column_index(p[0]), ) for p in r ]
    else:
      start_column = Square.column_index(r[0][0])
      stop_column = Square.column_index(r[1][0])
      start_row = Square.row_index(r[0][1])
      stop_row = Square.row_index(r[1][1])
      r = []
      for column in range(start_column, stop_column - start_column + 1):
        r.append( ( start_row, column, ) )
      return r
  
  def add_piece(self, color, piece_type, row, column):    
    ''' Add a piece to a square in the board '''
    self.Squares[Square.position(row, column)].set_piece(Piece(Type=piece_type, Color=color))
{'fraction_non_alphanumeric': 0.1247702205882353, 'fraction_numerical': 0.009344362745098039, 'mean_word_length': 2.757410071942446, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5779661', 'n_tokens_mistral': 4309, 'n_tokens_neox': 4138, 'n_words': 1332}