def testAttackedAndNotProtected(self): """ Testing what recognize the algorithm """ board = Board(setup=True) dsa = DecisionSupportAlgorithm() dsa.set_foe_as_bot() dsa.enableDisableAlgo(True) moves = ((cordDic["e2"], cordDic["e4"]), (cordDic["d7"], cordDic["d5"])) for cord0, cord1 in moves: board = board.move(Move(Cord(cord0), Cord(cord1), board)) coordinate_attacked = dsa._DecisionSupportAlgorithm__apply_algorithm( board, WHITE, dsa._DecisionSupportAlgorithm__attacked_and_not_protected) # Not protected self.assertEqual([Cord("e4", color="R")], coordinate_attacked) coordinate_attacked = dsa._DecisionSupportAlgorithm__apply_algorithm( board, BLACK, dsa._DecisionSupportAlgorithm__attacked_and_not_protected) # protected by Queen self.assertEqual([], coordinate_attacked) board = board.move(Move(Cord(E4), Cord(E5), board)) coordinate_attacked = dsa._DecisionSupportAlgorithm__apply_algorithm( board, WHITE, dsa._DecisionSupportAlgorithm__attacked_and_not_protected) self.assertEqual([], coordinate_attacked)
def on_response(self, widget, response): if response in (HINT, MOVE): if self.gamemodel.hint: if self.boardview.arrows: self.boardview.arrows.clear() if self.boardview.circles: self.boardview.circles.clear() hint = self.gamemodel.hint cord0 = Cord(hint[0], int(hint[1]), "G") cord1 = Cord(hint[2], int(hint[3]), "G") if response == HINT: self.boardview.circles.add(cord0) self.boardview.redrawCanvas() else: self.boardview.arrows.add((cord0, cord1)) self.boardview.redrawCanvas() else: print("No hint available!") elif response == RETRY: if self.gamemodel.practice_game: self.gamemodel.undoMoves(2) elif self.gamemodel.lesson_game: self.boardview.setShownBoard(self.shown_board) self.your_turn() elif response == NEXT: if self.gamemodel.practice_game: if self.gamemodel.practice[0] == "puzzle": start_puzzle_from(self.gamemodel.practice[1]) elif self.gamemodel.practice[0] == "endgame": start_endgame_from(self.gamemodel.practice[1]) else: print("Next clicked!")
def __init__(self, cord0, cord1=None, board=None, promotion=None): """ Inits a new highlevel Move object. The object can be initialized in the follow ways: Move(cord0, cord1, board, [promotionPiece]) Move(lovLevelMoveInt) """ if not cord1: self.move = cord0 self.flag = self.move >> 12 self.cord0 = None if self.flag == DROP else Cord( lmove.FCORD(self.move)) self.cord1 = Cord(lmove.TCORD(self.move)) else: assert cord0 != None and cord1 != None, "cord0=%s, cord1=%s, board=%s" % ( cord0, cord1, board) assert board[cord0] != None, "cord0=%s, cord1=%s, board=%s" % ( cord0, cord1, board) self.cord0 = cord0 self.cord1 = cord1 if not board: raise ValueError( "Move needs a Board object in order to investigate flags") self.flag = NORMAL_MOVE if board[self.cord0].piece == PAWN and self.cord1.y in (0, 7): if promotion == None: promotion = QUEEN self.flag = lmove.FLAG_PIECE(promotion) elif board[self.cord0].piece == KING: if self.cord0 == self.cord1: self.flag = NULL_MOVE elif board.variant == FISCHERRANDOMCHESS: if (abs(self.cord0.x - self.cord1.x) > 1 and self.cord1.x==C1) or \ \ (board.board.ini_rooks[board.color][0] == self.cord1.cord and \ ((board.board.color == WHITE and board.board.castling & W_OOO) or \ (board.board.color == BLACK and board.board.castling & B_OOO))): self.flag = QUEEN_CASTLE elif (abs(self.cord0.x - self.cord1.x) > 1 and self.cord1.x==G1) or \ \ (board.board.ini_rooks[board.color][1] == self.cord1.cord and \ ((board.board.color == WHITE and board.board.castling & W_OO) or \ (board.board.color == BLACK and board.board.castling & B_OO))): self.flag = KING_CASTLE else: if self.cord0.x - self.cord1.x == 2: self.flag = QUEEN_CASTLE if self.cord0.x == 4 else KING_CASTLE elif self.cord0.x - self.cord1.x == -2: self.flag = KING_CASTLE if self.cord0.x == 4 else QUEEN_CASTLE elif board[self.cord0].piece == PAWN and \ board[self.cord1] == None and \ self.cord0.x != self.cord1.x and \ self.cord0.y != self.cord1.y: self.flag = ENPASSANT self.move = newMove(self.cord0.cord, self.cord1.cord, self.flag)
def __setBoard(self, board): if self.features["setboard"]: self.__tellEngineToStopPlayingCurrentColor() fen = board.asFen(enable_bfen=False) if self.mode == INVERSE_ANALYZING: fen_arr = fen.split() if not self.board.board.opIsChecked(): if fen_arr[1] == "b": fen_arr[1] = "w" else: fen_arr[1] = "b" fen = " ".join(fen_arr) print("setboard %s" % fen, file=self.engine) else: # Kludge to set black to move, avoiding the troublesome and now # deprecated "black" command. - Equal to the one xboard uses self.__tellEngineToStopPlayingCurrentColor() if board.color == BLACK: print("a2a3", file=self.engine) print("edit", file=self.engine) print("#", file=self.engine) for color in WHITE, BLACK: for y, row in enumerate(board.data): for x, piece in enumerate(row): if not piece or piece.color != color: continue sign = reprSign[piece.sign] cord = repr(Cord(x, y)) print(sign + cord, file=self.engine) print("c", file=self.engine) print(".", file=self.engine)
def point2Cord (self, x, y): if not self.view.square: return None point = self.transPoint(x, y) x = floor(point[0]) if self.view.fromWhite: y = floor(point[1]) else: y = floor(point[1]) if not (0 <= x <= 7 and 0 <= y <= 7): return None return Cord(x, y)
def point2Cord (self, x, y): point = self.transPoint(x, y) p0, p1 = point[0], point[1] if self.parent.variant.variant in DROP_VARIANTS: if not -3 <= int(p0) <= self.FILES+2 or not 0 <= int(p1) <= self.RANKS-1: return None else: if not 0 <= int(p0) <= self.FILES-1 or not 0 <= int(p1) <= self.RANKS-1: return None return Cord(int(p0) if p0>= 0 else int(p0)-1, int(p1))
def simulateMove (self, board1, move): moved = [] new = [] dead = [] cord0, cord1 = move.cords moved.append( (self[cord0], cord0) ) if self[cord1]: if not move.flag in (QUEEN_CASTLE, KING_CASTLE): dead.append( self[cord1] ) if move.flag == QUEEN_CASTLE: if self.color == WHITE: r1 = self.board.ini_rooks[0][0] moved.append( (self[Cord(r1)], Cord(r1)) ) else: r8 = self.board.ini_rooks[1][0] moved.append( (self[Cord(r8)], Cord(r8)) ) elif move.flag == KING_CASTLE: if self.color == WHITE: r1 = self.board.ini_rooks[0][1] moved.append( (self[Cord(r1)], Cord(r1)) ) else: r8 = self.board.ini_rooks[1][1] moved.append( (self[Cord(r8)], Cord(r8)) ) elif move.flag in PROMOTIONS: newPiece = board1[cord1] moved.append( (newPiece, cord0) ) new.append( newPiece ) newPiece.opacity=1 dead.append( self[cord0] ) elif move.flag == ENPASSANT: if self.color == WHITE: dead.append( self[Cord(cord1.x, cord1.y-1)] ) else: dead.append( self[Cord(cord1.x, cord1.y+1)] ) return moved, new, dead
def point2Cord(self, x_loc, y_loc): point = self.transPoint(x_loc, y_loc) p0_loc, p1_loc = point[0], point[1] if self.parent.variant.variant in DROP_VARIANTS: if not-3 <= int(p0_loc) <= self.FILES + 2 or not 0 <= int( p1_loc) <= self.RANKS - 1: return None else: if not 0 <= int(p0_loc) <= self.FILES - 1 or not 0 <= int( p1_loc) <= self.RANKS - 1: return None return Cord(int(p0_loc) if p0_loc >= 0 else int(p0_loc) - 1, int(p1_loc))
def point2Cord(self, x_loc, y_loc): if not self.view.square: return None point = self.transPoint(x_loc, y_loc) x_loc = floor(point[0]) if self.view.fromWhite: y_loc = floor(point[1]) else: y_loc = floor(point[1]) if not (0 <= x_loc <= 7 and 0 <= y_loc <= 7): return None return Cord(x_loc, y_loc)
def loadToModel (self, gameno, position, model=None): if not model: model = GameModel() board = model.variant.board() for y,row in enumerate(self.games[gameno]): for x,letter in enumerate(reg2.findall(row)): if letter in entitydefs: letter = entitydefs[letter] if letter not in piecesDia: raise LoadingError (_("Couldn't load the diagram '%s'")%repr(letter)) col, pie = piecesDia[letter] if pie != EMPTY: board.addPiece(Cord(x,7-y), Piece(col,pie)) model.boards = [board] if model.status == WAITING_TO_START: model.status, model.reason = getStatus(model.boards[-1]) return model
def test1(self): """ Testing Board.move() on frc castling in non frc game """ board = Board(setup=True) moves = ((D2, D4), (G8, F6), (C2, C4), (G7, G6), (G2, G3), (F8, G7), (F1, G2), (E8, H8)) for cord0, cord1 in moves: print(cord0, cord1) board = board.move(Move(Cord(cord0), Cord(cord1), board)) board.printPieces() self.assertIsNone(board[Cord(E8)]) self.assertIsNone(board[Cord(H8)]) self.assertEqual(board[Cord(G8)].piece, Piece(BLACK, KING).piece) self.assertEqual(board[Cord(F8)].piece, Piece(BLACK, ROOK).piece)
def on_add_clicked(self, button): """ Create sub-fen from current FEN removing pieces not marked with circles """ self.board = self.gamemodel.boards[self.boardview.shown].board board = self.board.clone() fen = board.asFen() for cord in range(64): kord = Cord(cord) if kord not in self.boardview.circles: board.arBoard[cord] = EMPTY sub_fen = board.asFen().split()[0] # If all pieces removed (no circles at all) use the original FEN if sub_fen == "8/8/8/8/8/8/8/8": if fen == FEN_START: return else: sub_fen = fen.split()[0] self.persp.filter_panel.add_sub_fen(sub_fen)
def paintBoxAround(self, move): paintBox = self.cord2RectRelative(move.cord0) paintBox = join(paintBox, self.cord2RectRelative(move.cord1)) if move.flag in (KING_CASTLE, QUEEN_CASTLE): y = move.cord0.cy color = (y == 1) rsqs = self.model.boards[-1].board.ini_rooks[color] if move.flag == KING_CASTLE: paintBox = join(paintBox, self.cord2RectRelative(Cord(rsqs[1]))) paintBox = join(paintBox, self.cord2RectRelative(Cord("f" + y))) paintBox = join(paintBox, self.cord2RectRelative(Cord("g" + y))) else: paintBox = join(paintBox, self.cord2RectRelative(Cord(rsqs[0]))) paintBox = join(paintBox, self.cord2RectRelative(Cord("c" + y))) paintBox = join(paintBox, self.cord2RectRelative(Cord("d" + y))) return paintBox
def move (self, move): assert self[move.cord0], "%s %s" % (move, self.asFen()) newBoard = self.clone() newBoard.board.applyMove (move.move) cord0, cord1 = move.cords flag = FLAG(move.move) # in frc there are unusual castling positions where # king will move on top of the castling rook, so... if flag in (KING_CASTLE, QUEEN_CASTLE): # don't put on the castling king yet king = newBoard[cord0] else: newBoard[cord1] = newBoard[cord0] newBoard[cord0] = None # move castling rook if self.color == WHITE: if flag == QUEEN_CASTLE: if self.board.ini_rooks[0][0] != D1: newBoard[Cord(D1)] = newBoard[Cord(self.board.ini_rooks[0][0])] newBoard[Cord(self.board.ini_rooks[0][0])] = None elif flag == KING_CASTLE: if self.board.ini_rooks[0][1] != F1: newBoard[Cord(F1)] = newBoard[Cord(self.board.ini_rooks[0][1])] newBoard[Cord(self.board.ini_rooks[0][1])] = None else: if flag == QUEEN_CASTLE: if self.board.ini_rooks[1][0] != D8: newBoard[Cord(D8)] = newBoard[Cord(self.board.ini_rooks[1][0])] newBoard[Cord(self.board.ini_rooks[1][0])] = None elif flag == KING_CASTLE: if self.board.ini_rooks[1][1] != F8: newBoard[Cord(F8)] = newBoard[Cord(self.board.ini_rooks[1][1])] newBoard[Cord(self.board.ini_rooks[1][1])] = None # put the castling king now if flag in (KING_CASTLE, QUEEN_CASTLE): if self.color == WHITE: if flag == QUEEN_CASTLE: newBoard[Cord(C1)] = king elif flag == KING_CASTLE: newBoard[Cord(G1)] = king else: if flag == QUEEN_CASTLE: newBoard[Cord(C8)] = king elif flag == KING_CASTLE: newBoard[Cord(G8)] = king if flag in PROMOTIONS: newBoard[cord1] = Piece(self.color, PROMOTE_PIECE(flag)) elif flag == ENPASSANT: newBoard[Cord(cord1.x, cord0.y)] = None return newBoard
def __init__(self, cord0, cord1=None, board=None, promotion=None): """ Inits a new highlevel Move object. The object can be initialized in the follow ways: Move(cord0, cord1, board, [promotionPiece]) Move(lovLevelMoveInt) """ if not cord1: self.move = cord0 self.flag = self.move >> 12 self.cord0 = None if self.flag == DROP else Cord(lmove.FCORD( self.move)) self.cord1 = Cord(lmove.TCORD(self.move)) else: assert cord0 is not None and cord1 is not None, "cord0=%s, cord1=%s, board=%s" % ( cord0, cord1, board) assert board[cord0] is not None, "cord0=%s, cord1=%s, board=%s" % ( cord0, cord1, board) self.cord0 = cord0 self.cord1 = cord1 if not board: raise ValueError( "Move needs a Board object in order to investigate flags") self.flag = NORMAL_MOVE if board[self.cord0].piece == PAWN and \ self.cord1.cord in board.PROMOTION_ZONE[board.board.color] and \ board.variant != SITTUYINCHESS: if promotion is None: self.flag = lmove.FLAG_PIECE(QUEEN) else: self.flag = lmove.FLAG_PIECE(promotion) elif board[self.cord0].piece == PAWN and board.variant == SITTUYINCHESS: if cord0 == cord1: # in place promotion self.flag = lmove.FLAG_PIECE(QUEEN) elif board[self.cord1] is None and \ (self.cord0.cord + self.cord1.cord) % 2 == 1 and \ (self.cord0.cord in board.PROMOTION_ZONE[board.board.color] or board.board.pieceCount[board.color][PAWN] == 1): # queen move promotion self.flag = lmove.FLAG_PIECE(QUEEN) elif board[self.cord0].piece == KING: if self.cord0 == self.cord1: self.flag = NULL_MOVE if self.cord0.x - self.cord1.x == 2 and board.variant not in (CAMBODIANCHESS, FISCHERRANDOMCHESS): self.flag = QUEEN_CASTLE if self.cord0.x == 4 else KING_CASTLE elif self.cord0.x - self.cord1.x == -2 and board.variant not in (CAMBODIANCHESS, FISCHERRANDOMCHESS): self.flag = KING_CASTLE if self.cord0.x == 4 else QUEEN_CASTLE else: if (abs(self.cord0.x - self.cord1.x) > 1 and self.cord1.x == C1) or ( board.board.ini_rooks[board.color][0] == self.cord1.cord and ( (board.board.color == WHITE and board.board.castling & W_OOO) or ( board.board.color == BLACK and board.board.castling & B_OOO))): self.flag = QUEEN_CASTLE elif (abs(self.cord0.x - self.cord1.x) > 1 and self.cord1.x == G1) or ( board.board.ini_rooks[board.color][1] == self.cord1.cord and ( (board.board.color == WHITE and board.board.castling & W_OO) or ( board.board.color == BLACK and board.board.castling & B_OO))): self.flag = KING_CASTLE elif board[self.cord0].piece == PAWN and \ board[self.cord1] is None and \ self.cord0.x != self.cord1.x and \ self.cord0.y != self.cord1.y: self.flag = ENPASSANT self.move = newMove(self.cord0.cord, self.cord1.cord, self.flag)
def simulateUnmove (self, board1, move): moved = [] new = [] dead = [] cord0, cord1 = move.cords if not move.flag in (QUEEN_CASTLE, KING_CASTLE): moved.append( (self[cord1], cord1) ) if board1[cord1]: if not move.flag in (QUEEN_CASTLE, KING_CASTLE): dead.append( board1[cord1] ) if move.flag == QUEEN_CASTLE: if board1.color == WHITE: moved.append( (self[Cord(C1)], Cord(C1)) ) moved.append( (self[Cord(D1)], Cord(D1)) ) else: moved.append( (self[Cord(C8)], Cord(C8)) ) moved.append( (self[Cord(D8)], Cord(D8)) ) elif move.flag == KING_CASTLE: if board1.color == WHITE: moved.append( (self[Cord(F1)], Cord(F1)) ) moved.append( (self[Cord(G1)], Cord(G1)) ) else: moved.append( (self[Cord(F8)], Cord(F8)) ) moved.append( (self[Cord(G8)], Cord(G8)) ) elif move.flag in PROMOTIONS: newPiece = board1[cord0] moved.append( (newPiece, cord1) ) new.append( newPiece ) newPiece.opacity=1 dead.append( self[cord1] ) elif move.flag == ENPASSANT: if board1.color == WHITE: new.append( board1[Cord(cord1.x, cord1.y-1)] ) else: new.append( board1[Cord(cord1.x, cord1.y+1)] ) return moved, new, dead
def on_response(self, widget, response): if response in (HINT, MOVE): if self.gamemodel.lesson_game: next_move = self.gamemodel.getMoveAtPly( self.boardview.shown, self.boardview.shown_variation_idx) hints = {self.boardview.shown: ((next_move.as_uci(), ), )} else: hints = self.gamemodel.hints if self.boardview.shown in hints: if self.boardview.arrows: self.boardview.arrows.clear() if self.boardview.circles: self.boardview.circles.clear() hint = hints[self.boardview.shown][0][0] cord0 = Cord(hint[0], int(hint[1]), "G") cord1 = Cord(hint[2], int(hint[3]), "G") if response == HINT: self.boardview.circles.add(cord0) self.boardview.redrawCanvas() else: self.boardview.arrows.add((cord0, cord1)) self.boardview.redrawCanvas() else: # TODO: print("No hint available yet!", self.gamemodel.ply, self.boardview.shown) elif response == RETRY: self.your_turn() if self.gamemodel.practice_game: me_played_last_move = self.gamemodel.boards[ -1].color != self.gamemodel.boards[0].color moves = 1 if self.gamemodel.status in UNDOABLE_STATES and me_played_last_move else 2 self.gamemodel.undoMoves(moves) elif self.gamemodel.lesson_game: prev_board = self.gamemodel.getBoardAtPly( self.boardview.shown - 1, variation=self.boardview.shown_variation_idx) self.annotation_panel.choices_enabled = False self.boardview.setShownBoard(prev_board) # We have to fix show_variation_index here, unless # after removing the variation it will be invalid! for vari in self.gamemodel.variations: if prev_board in vari: break self.boardview.shown_variation_idx = self.gamemodel.variations.index( vari) self.annotation_panel.choices_enabled = True self.boardcontrol.game_preview = False elif response == CONTINUE: self.your_turn() self.boardview.showNext() self.boardcontrol.game_preview = False elif response == BACK_TO_MAINLINE: self.opp_turn() self.boardview.backToMainLine() self.boardcontrol.game_preview = False elif response == NEXT: if self.gamemodel.puzzle_game: if self.gamemodel.from_lesson: start_lesson_from(self.gamemodel.source, self.gamemodel.current_index + 1) else: start_puzzle_from(self.gamemodel.source, self.gamemodel.current_index + 1) elif self.gamemodel.end_game: start_endgame_from(self.gamemodel.source) elif self.gamemodel.lesson_game: start_lesson_from(self.gamemodel.source, self.gamemodel.current_index + 1) else: print(self.gamemodel.__dir__())
def drawLastMove(self, context, redrawn): if not self.lastMove: return if self.shown <= self.model.lowply: return show_board = self.model.getBoardAtPly(self.shown) last_board = self.model.getBoardAtPly(self.shown - 1) capture = self.lastMove.is_capture(last_board) wh = 0.27 # Width of marker p0 = 0.155 # Padding on last cord p1 = 0.085 # Padding on current cord sw = 0.02 # Stroke width xc, yc, square, s = self.square context.save() context.set_line_width(sw * s) d0 = {-1: 1 - p0, 1: p0} d1 = {-1: 1 - p1, 1: p1} ms = ((1, 1), (-1, 1), (-1, -1), (1, -1)) light_yellow = (.929, .831, 0, 0.8) dark_yellow = (.769, .627, 0, 0.5) light_orange = (.961, .475, 0, 0.8) dark_orange = (.808, .361, 0, 0.5) if self.lastMove.flag in (KING_CASTLE, QUEEN_CASTLE): ksq0 = last_board.board.kings[last_board.color] ksq1 = show_board.board.kings[last_board.color] if self.lastMove.flag == KING_CASTLE: rsq0 = show_board.board.ini_rooks[last_board.color][1] rsq1 = ksq1 - 1 else: rsq0 = show_board.board.ini_rooks[last_board.color][0] rsq1 = ksq1 + 1 cord_pairs = [[Cord(ksq0), Cord(ksq1)], [Cord(rsq0), Cord(rsq1)]] else: cord_pairs = [[self.lastMove.cord0, self.lastMove.cord1]] for [cord0, cord1] in cord_pairs: rel = self.cord2RectRelative(cord0) if intersects(rect(rel), redrawn): r = self.cord2Rect(cord0) for m in ms: context.move_to(r[0] + (d0[m[0]] + wh * m[0]) * r[2], r[1] + (d0[m[1]] + wh * m[1]) * r[2]) context.rel_line_to(0, -wh * r[2] * m[1]) context.rel_curve_to(0, wh * r[2] * m[1] / 2.0, -wh * r[2] * m[0] / 2.0, wh * r[2] * m[1], -wh * r[2] * m[0], wh * r[2] * m[1]) context.close_path() context.set_source_rgba(*light_yellow) context.fill_preserve() context.set_source_rgba(*dark_yellow) context.stroke() rel = self.cord2RectRelative(cord1) if intersects(rect(rel), redrawn): r = self.cord2Rect(cord1) for m in ms: context.move_to(r[0] + d1[m[0]] * r[2], r[1] + d1[m[1]] * r[2]) context.rel_line_to(wh * r[2] * m[0], 0) context.rel_curve_to(-wh * r[2] * m[0] / 2.0, 0, -wh * r[2] * m[0], wh * r[2] * m[1] / 2.0, -wh * r[2] * m[0], wh * r[2] * m[1]) context.close_path() if capture: context.set_source_rgba(*light_orange) context.fill_preserve() context.set_source_rgba(*dark_orange) context.stroke() else: context.set_source_rgba(*light_yellow) context.fill_preserve() context.set_source_rgba(*dark_yellow) context.stroke()
def drawPieces(self, context, r): pieces = self.model.getBoardAtPly(self.shown) xc, yc, square, s = self.square parseC = lambda c: (c.red / 65535., c.green / 65535., c.blue / 65535.) fgN = parseC(self.get_style().fg[gtk.STATE_NORMAL]) fgS = fgN fgA = parseC(self.get_style().fg[gtk.STATE_ACTIVE]) fgP = parseC(self.get_style().fg[gtk.STATE_PRELIGHT]) # As default we use normal foreground for selected cords, as it looks # less confusing. However for some themes, the normal foreground is so # similar to the selected background, that we have to use the selected # foreground. bgSl = parseC(self.get_style().bg[gtk.STATE_SELECTED]) bgSd = parseC(self.get_style().dark[gtk.STATE_SELECTED]) if min((fgN[0] - bgSl[0])**2 + (fgN[1] - bgSl[1])**2 + (fgN[2] - bgSl[2])**2, (fgN[0] - bgSd[0])**2 + (fgN[1] - bgSd[1])**2 + (fgN[2] - bgSd[2])**2) < 0.2: fgS = parseC(self.get_style().fg[gtk.STATE_SELECTED]) # Draw dying pieces (Found in self.deadlist) for piece, x, y in self.deadlist: context.set_source_rgba(fgN[0], fgN[1], fgN[2], piece.opacity) self.__drawPiece(context, piece, x, y) # Draw pieces reincarnating (With opacity < 1) for y, row in enumerate(pieces.data): for x, piece in enumerate(row): if not piece or piece.opacity == 1: continue if piece.x: x, y = piece.x, piece.y context.set_source_rgba(fgN[0], fgN[1], fgN[2], piece.opacity) self.__drawPiece(context, piece, x, y) # Draw standing pieces (Only those who intersect drawn area) for y, row in enumerate(pieces.data): for x, piece in enumerate(row): if not piece or piece.x != None or piece.opacity < 1: continue if not intersects(rect(self.cord2RectRelative(x, y)), r): continue if Cord(x, y) == self.selected: context.set_source_rgb(*fgS) elif Cord(x, y) == self.active: context.set_source_rgb(*fgA) elif Cord(x, y) == self.hover: context.set_source_rgb(*fgP) else: context.set_source_rgb(*fgN) self.__drawPiece(context, piece, x, y) context.set_source_rgb(*fgP) # Draw moving or dragged pieces (Those with piece.x and piece.y != None) for y, row in enumerate(pieces.data): for x, piece in enumerate(row): if not piece or piece.x == None or piece.opacity < 1: continue self.__drawPiece(context, piece, piece.x, piece.y)
def testNotProtected(self): board = Board(setup=True) dsa = DecisionSupportAlgorithm() dsa.set_foe_as_bot() dsa.enableDisableAlgo(True) # at the start of the game, only the two towers are not protected by other pieces coordinate_not_protected = dsa._DecisionSupportAlgorithm__apply_algorithm( board, WHITE, dsa._DecisionSupportAlgorithm__not_protected) self.assertEqual(set([Cord("a1", color="Y"), Cord("h1", color="Y")]), set(coordinate_not_protected)) board = board.move( Move(Cord(cordDic["e2"]), Cord(cordDic["e4"]), board)) coordinate_not_protected = dsa._DecisionSupportAlgorithm__apply_algorithm( board, WHITE, dsa._DecisionSupportAlgorithm__not_protected) # the pawn moved to e4 is now not protected self.assertEqual( set([ Cord("a1", color="Y"), Cord("h1", color="Y"), Cord("e4", color="Y") ]), set(coordinate_not_protected)) board = board.move( Move(Cord(cordDic["d7"]), Cord(cordDic["d5"]), board)) # the black pawn attack the white pawn, it is not notProtected that will detect this case, # only the two towers are not protected coordinate_not_protected = dsa._DecisionSupportAlgorithm__apply_algorithm( board, WHITE, dsa._DecisionSupportAlgorithm__not_protected) self.assertEqual(set([Cord("a1", color="Y"), Cord("h1", color="Y")]), set(coordinate_not_protected))
def cordsAround(cord): kingMoves = moveArray[KING] for c in iterBits(kingMoves[cord.cord]): yield Cord(c)
def read_games(self, handle): """ We don't return games if stipulation is not 'mate in #' """ games = [] rec = None rec_id = 1 contains_fairy_pieces = False # authors is a more line list (each line starts with "-") in_authors = False # piece list are usually in one line list inside [] # but sometimes given in more line lists in_white = False in_black = False for line in handle: line = line.rstrip() if in_authors and ":" in line: in_authors = False elif in_white and ":" in line: in_white = False elif in_black and ":" in line: in_black = False rec["FEN"] = self.lboard.asFen() # New record start if line == "---": if rec is not None and rec["Black"].startswith("Mate in ") and not contains_fairy_pieces: games.append(rec) rec_id += 1 contains_fairy_pieces = False self.lboard = LBoard() self.lboard.applyFen("8/8/8/8/8/8/8/8 w - - 0 1") rec = collections.defaultdict(str) rec["Id"] = rec_id rec["Offset"] = 0 elif line.startswith("authors:"): in_authors = True elif line.startswith("source:"): rec["Event"] = line[8:] elif line.startswith("source-id:"): rec["Event"] = "%s (%s)" % (rec["Event"], line[12:]) elif line.startswith("date:"): parts = line[6:].split("-") parts_len = len(parts) if parts_len >= 3: rec["Day"] = parts[2] if parts_len >= 2: rec["Month"] = parts[1] if parts_len >= 1: rec["Year"] = parts[0] elif line.startswith("distinction:"): rec["Site"] = line[12:] elif line.startswith("algebraic:"): pass elif line.startswith(" white:"): parts = line.split("[") if len(parts) > 1: pieces = parts[1][:-1] for piece in pieces.split(", "): if piece.startswith("Royal") or piece[0] not in chr2piece: contains_fairy_pieces = True else: cord = Cord(piece[1:3]).cord piece = chr2piece[piece[0]] self.lboard._addPiece(cord, piece, WHITE) else: in_white = True elif line.startswith(" black:"): parts = line.split("[") if len(parts) > 1: pieces = parts[1][:-1] for piece in pieces.split(", "): if piece.startswith("Royal") or piece[0] not in chr2piece: contains_fairy_pieces = True else: cord = Cord(piece[1:3]).cord piece = chr2piece[piece[0]] self.lboard._addPiece(cord, piece, BLACK) rec["FEN"] = self.lboard.asFen() else: in_black = True elif line.startswith("stipulation:"): if line.endswith("Black to move"): line = line[:-14] rec["FEN"] = rec["FEN"].replace("w", "b") line = line.split(": ")[1] if "+" in line: rec["Result"] = WHITEWON rec["Black"] = "Win" elif "-" in line: rec["Result"] = BLACKWON rec["Black"] = "Win" elif "=" in line: rec["Result"] = DRAW rec["Black"] = "Draw" elif line.startswith('"#'): rec["Result"] = WHITEWON rec["Black"] = "Mate in %s" % line[2:-1] rec["Termination"] = "mate in %s" % line[2:-1] elif line.startswith("solution:"): # TODO: solutions can be in several (sometimes rather unusual) form pass else: if in_authors: author = line[line.find("-") + 1:].lstrip() if rec["White"]: rec["White"] = "%s - %s" % (rec["White"], author) else: rec["White"] = author elif in_white: piece = line[line.find("-") + 1:].lstrip() cord = Cord(piece[1:3]).cord piece = chr2piece[piece[0]] self.lboard._addPiece(cord, piece, WHITE) elif in_black: piece = line[line.find("-") + 1:].lstrip() cord = Cord(piece[1:3]).cord piece = chr2piece[piece[0]] self.lboard._addPiece(cord, piece, BLACK) # Append the latest record if rec is not None and rec["Black"].startswith("Mate in ") and not contains_fairy_pieces: games.append(rec) return games
def point2Cord(self, x, y): if not self.view.square: return None point = self.transPoint(x, y) if not 0 <= int(point[0]) <= 7 or not 0 <= int(point[1]) <= 7: return None return Cord(int(point[0]), int(point[1]))
def testAll(self): board = Board(setup=True) dsa = DecisionSupportAlgorithm() dsa.set_foe_as_bot() dsa.enableDisableAlgo(True) moves = ((cordDic["e2"], cordDic["e4"]), (cordDic["d7"], cordDic["d5"])) for cord0, cord1 in moves: board = board.move(Move(Cord(cord0), Cord(cord1), board)) board.printPieces() # Not protected self.assertEqual( set([ Cord("a1", color="Y"), Cord("h1", color="Y"), Cord("e4", color="R") ]), set(dsa.calculate_coordinate_in_danger(board, WHITE))) # protected by Queen, so no danger self.assertEqual(set([Cord("a8", color="Y"), Cord("h8", color="Y")]), set(dsa.calculate_coordinate_in_danger(board, BLACK))) # pawn go forward, no danger board = board.move(Move(Cord(E4), Cord(E5), board)) self.assertEqual( set([ Cord("a1", color="Y"), Cord("h1", color="Y"), Cord("e5", color="Y") ]), set(dsa.calculate_coordinate_in_danger(board, WHITE))) # Should not recognize king board_king = Board(setup=True) dsa_king = DecisionSupportAlgorithm() dsa_king.set_foe_as_bot() dsa_king.enableDisableAlgo(True) moves = ((cordDic["e2"], cordDic["e4"]), (cordDic["f7"], cordDic["f5"]), (cordDic["d1"], cordDic["h5"])) for cord0, cord1 in moves: board_king = board_king.move( Move(Cord(cord0), Cord(cord1), board_king)) # board_king.printPieces() self.assertEqual( set([ Cord("a8", color="Y"), Cord("h8", color="Y"), Cord("f5", color="Y") ]), set(dsa.calculate_coordinate_in_danger(board_king, BLACK)))