How to use capture method in differencify

Best JavaScript code snippet using differencify

chess.py

Source:chess.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2#Copyright (c) 2012 Walter Bender3#Copyright (c) 2012 Ignacio Rodriguez4# This program is free software; you can redistribute it and/or modify5# it under the terms of the GNU General Public License as published by6# the Free Software Foundation; either version 3 of the License, or7# (at your option) any later version.8#9# You should have received a copy of the GNU General Public License10# along with this library; if not, write to the Free Software11# Foundation, 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA12from gi.repository import Gtk, Gdk, GdkPixbuf, GLib13import os14import subprocess15from gettext import gettext as _16import logging17_logger = logging.getLogger('GNUChessActivity')18from sprites import Sprites, Sprite19from piece import svg_header, svg_footer, svg_king, svg_queen, svg_bishop, \20 svg_knight, svg_rook, svg_pawn21ROBOT_MOVE = 'My move is : '22TOP = 323MID = 224BOT = 125STATUS = 'status'26ROBOT = 'robot'27RESTORE = 'restore'28REMOVE = 'remove'29UNDO = 'undo'30HINT = 'hint'31GAME = 'game'32NEW = 'new'33# Skin indicies34WP = 035BP = 136WR = 237BR = 338WN = 439BN = 540WB = 641BB = 742WQ = 843BQ = 944WK = 1045BK = 1146FILES = 'abcdefgh'47RANKS = '12345678'48BIN = {'i686': 'i686', 'i586': 'i686', 'armv7l': 'armv7l', 'x86_64': 'x86_64'}49PATHS = {WP: 'white-pawn', WR: 'white-rook', WN: 'white-knight',50 WB: 'white-bishop', WQ: 'white-queen', WK: 'white-king',51 BP: 'black-pawn', BR: 'black-rook', BN: 'black-knight',52 BB: 'black-bishop', BQ: 'black-queen', BK: 'black-king'}53TYPES = {WP: 'P', WR: 'R', WN: 'N', WB: 'B', WQ: 'Q', WK: 'K',54 BP: 'p', BR: 'r', BN: 'n', BB: 'b', BQ: 'q', BK: 'k'}55class Gnuchess():56 def __init__(self, canvas, parent=None, path=None,57 colors=['#A0FFA0', '#FF8080']):58 self._activity = parent59 self._bundle_path = path60 self._bin_path = 'bin/i686'61 self._colors = ['#FFFFFF']62 self._colors.append(colors[0])63 self._colors.append(colors[1])64 self._colors.append('#000000')65 self._canvas = canvas66 if parent is not None:67 parent.show_all()68 self._parent = parent69 self._canvas.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)70 self._canvas.add_events(Gdk.EventMask.BUTTON_RELEASE_MASK)71 self._canvas.add_events(Gdk.EventMask.POINTER_MOTION_MASK)72 self._canvas.connect("draw", self.__draw_cb)73 self._canvas.connect("button-press-event", self._button_press_cb)74 self._canvas.connect("button-release-event", self._button_release_cb)75 self._canvas.connect("motion-notify-event", self._mouse_move_cb)76 self._width = Gdk.Screen.width()77 self._height = Gdk.Screen.height()78 self.scale = int((self._height - 55) / 10)79 self.we_are_sharing = False80 self.move_list = []81 self.game = ''82 self._press = None83 self._release = None84 self._dragpos = [0, 0]85 self._total_drag = [0, 0]86 self._last_piece_played = [None, (0, 0)]87 self._thinking = False88 self._flashing = False89 self._defer_flash = [None, 0]90 self._queue_check = False91 self._move = 092 self._counter = 093 self.check = False94 self.checkmate = False95 self.white = []96 self.black = []97 self._board = []98 self._squares = []99 self._output = ''100 self._before = []101 self._after = []102 self.skins = {}103 # Generate the sprites we'll need...104 self._sprites = Sprites(self._canvas)105 self._generate_sprites(colors)106 p = subprocess.Popen(['uname', '-m'], # in my virtual machine, -p returns unknown107 stdin=subprocess.PIPE,108 stdout=subprocess.PIPE,109 stderr=subprocess.STDOUT)110 tmp_p = p.communicate()111 self._bin_path = 'bin/%s' % (BIN[tmp_p[0].decode().replace('\n', '')])112 self._all_clear()113 os.system('chmod -R 755 bin -f')114 def move(self, my_move):115 ''' Send a command to gnuchess. '''116 # Permission to play117 p = subprocess.Popen(['{}/{}/gnuchess'.format(self._bundle_path,118 self._bin_path)],119 stdin=subprocess.PIPE,120 stdout=subprocess.PIPE,121 stderr=subprocess.STDOUT)122 if my_move == HINT:123 level = 'hard\nbook on\n' # may as well get a good hint124 elif self._activity.playing_mode == 'easy':125 level = 'easy\nbook off\ndepth 1\n'126 else:127 level = 'hard\nbook on\n'128 if my_move in [REMOVE, UNDO, RESTORE, HINT, GAME, NEW]:129 hint = False130 if my_move == REMOVE:131 self.move_list = self.move_list[:-2]132 elif my_move == UNDO:133 self.move_list = self.move_list[:-1]134 cmd = 'force manual\n'135 for move in self.move_list:136 cmd += '%s\n' % (move)137 if my_move == HINT:138 cmd += '%sgo\nquit\n' % (level)139 hint = True140 elif my_move == GAME:141 cmd += 'show game\nquit\n'142 else:143 cmd += 'show board\nquit\n'144 output = p.communicate(input=cmd.encode())145 self._process_output(output[0], my_move=None, hint=hint)146 elif my_move == ROBOT: # Ask the computer to play147 cmd = 'force manual\n'148 for move in self.move_list:149 cmd += '%s\n' % (move)150 cmd += '%sgo\nshow board\nquit\n' % (level)151 output = p.communicate(input=cmd.encode())152 self._process_output(output[0], my_move='robot')153 elif my_move == STATUS: # reading board state154 cmd = 'force manual\n'155 for move in self.move_list:156 cmd += '%s\n' % (move)157 cmd += 'show board\nquit\n'158 output = p.communicate(input=cmd.encode())159 self._process_output(output[0], my_move=STATUS)160 elif my_move is not None: # human's move161 cmd = 'force manual\n'162 for move in self.move_list:163 cmd += '%s\n' % (move)164 cmd += '%s\n' % (my_move)165 cmd += 'show board\nquit\n'166 output = p.communicate(input=cmd.encode())167 self._process_output(output[0], my_move=my_move)168 def _process_output(self, output, my_move=None, hint=False):169 ''' process output from gnuchess command '''170 self.check = False171 self.checkmate = False172 self.valid_move = False173 output = output.decode()174 if my_move == STATUS: # Just reading board state175 self._output = output176 return177 elif 'White Black' in output: # processing show game178 target = 'White Black'179 output = output[output.find(target):]180 self.game = output[:output.find('\n\n')]181 return182 elif hint: # What would the robot do?183 output = output[output.find(ROBOT_MOVE):]184 hint = output[len(ROBOT_MOVE):output.find('\n')]185 self._activity.status.set_label(hint)186 self._parse_move(hint)187 self._thinking = False188 self._activity.restore_cursor()189 return190 elif 'Illegal move' in output:191 self._activity.status.set_label(_('Illegal move'))192 if self._last_piece_played[0] is not None:193 self._last_piece_played[0].move(self._last_piece_played[1])194 self._last_piece_played[0] = None195 elif my_move == ROBOT:196 if 'wins' in output or 'loses' in output:197 self.checkmate = True198 output = output[output.find(ROBOT_MOVE):]199 robot_move = output[len(ROBOT_MOVE):output.find('\n')]200 self.move_list.append(robot_move)201 self.valid_move = True202 if '+' in robot_move:203 self.check = True204 if '#' in robot_move or '++' in robot_move:205 self.checkmate = True206 if self._activity.playing_white:207 self._activity.black_entry.set_text(robot_move)208 self._activity.white_entry.set_text('')209 else:210 self._activity.white_entry.set_text(robot_move)211 self._activity.black_entry.set_text('')212 self._thinking = False213 self._activity.restore_cursor()214 elif my_move is not None:215 if 'wins' in output or 'loses' in output:216 self.checkmate = True217 self.move_list.append(my_move)218 self.valid_move = True219 if self._activity.playing_white:220 self._activity.white_entry.set_text(my_move)221 self._activity.black_entry.set_text('')222 else:223 self._activity.black_entry.set_text(my_move)224 self._activity.white_entry.set_text('')225 if len(self.move_list) % 2 == 0:226 target = 'white '227 else:228 target = 'black '229 while output.find(target) > 0:230 output = output[output.find(target):]231 output = output[output.find('\n'):]232 if len(output) < 136 or output[0:3] == 'GNU':233 self._activity.status.set_label('???')234 else:235 self._load_board(output)236 if self.checkmate or self.check:237 self._flash_check()238 else:239 if self._activity.time_interval and \240 (self._activity.time_interval >= 0) and \241 self.valid_move == True:242 self._activity.stopwatch(self._activity.time_interval,243 self._activity.alert_time)244 if len(self.move_list) % 2 == 0:245 self._activity.status.set_label(_("It is White's move."))246 else:247 self._activity.status.set_label(_("It is Black's move."))248 def _all_clear(self):249 ''' Things to reinitialize when starting up a new game. '''250 for i in range(3):251 self.bg[i].set_layer(-1)252 self.bg[i].set_label('')253 self.move_list = []254 self.game = ''255 self.check = False256 self._hide_check()257 self.checkmate = False258 self._hide_checkmate()259 def new_game(self):260 self._all_clear()261 self.move(NEW)262 if self._activity.playing_robot and not self._activity.playing_white:263 self.move(ROBOT)264 if self.we_are_sharing and self._activity.collab.props.leader:265 self._activity.send_new_game()266 def restore_game(self, move_list):267 self.move_list = []268 for move in move_list:269 self.move_list.append(str(move))270 self.move(RESTORE)271 if len(self.move_list) > 0:272 if '#' in self.move_list[-1] or '++' in self.move_list[-1]:273 if len(self.move_list) % 2 == 0:274 self._activity.status.set_label(_('Black wins.'))275 else:276 self._activity.status.set_label(_('White wins.'))277 self._show_checkmate()278 elif '+' in self.move_list[-1]:279 if len(self.move_list) % 2 == 0:280 self._activity.status.set_label(281 _("White's King is in check."))282 else:283 self._activity.status.set_label(284 _("Black's King is in check."))285 self._show_check()286 if self.we_are_sharing and self._activity.collab.props.leader:287 self._activity.send_restore()288 def copy_game(self):289 self.move(GAME)290 return self.game291 def save_game(self):292 return self.move_list293 def show_game_history(self, tag_pairs):294 if not self._activity.showing_game_history:295 for i in range(3):296 self.bg[i].set_layer(TOP)297 self.move(GAME)298 # Split into two columns299 if ' 14.' in self.game:300 i = self.game.index(' 14.')301 self.bg[0].set_label(tag_pairs + self.game[: i - 1])302 if '31.' in self.game:303 j = self.game.index('31.')304 self.bg[1].set_label(self.game[i: j - 1])305 self.bg[2].set_label(self.game[j:])306 else:307 self.bg[1].set_label(self.game[i:])308 else:309 self.bg[0].set_label(self.game)310 self._activity.showing_game_history = True311 else:312 for i in range(3):313 self.bg[i].set_layer(-1)314 self.bg[i].set_label('')315 self._activity.showing_game_history = False316 def play_game_history(self):317 self._counter = 0318 self._copy_of_move_list = self.move_list[:]319 self._all_clear()320 self._stepper()321 def _stepper(self):322 if self._counter < len(self._copy_of_move_list):323 self.move(self._copy_of_move_list[self._counter])324 self._counter += 1325 GLib.timeout_add(2000, self._stepper)326 def _button_press_cb(self, win, event):327 win.grab_focus()328 x, y = list(map(int, event.get_coords()))329 self._dragpos = [x, y]330 self._total_drag = [0, 0]331 spr = self._sprites.find_sprite((x, y))332 if spr is None or spr.type is None:333 return334 if spr.type == 'check':335 self._hide_check()336 return337 elif spr.type == 'checkmate':338 self._hide_checkmate()339 return340 elif self._thinking or self._flashing:341 # Robot is thinking or conjuring up a hint342 self._wait_your_turn()343 return344 elif self.we_are_sharing:345 if not self._activity.playing_white and \346 len(self.move_list) % 2 == 0:347 self._wait_your_turn()348 return349 elif self._activity.playing_white and \350 len(self.move_list) % 2 == 1:351 self._wait_your_turn()352 return353 # Only play your color354 if self._activity.playing_robot or self.we_are_sharing:355 if self._activity.playing_white and spr.type[0] in 'prnbqk':356 self._play_your_color()357 return358 elif not self._activity.playing_white and spr.type[0] in 'PRNBQK':359 self._play_your_color()360 return361 else:362 if len(self.move_list) % 2 == 0 and spr.type[0] in 'prnbqk':363 self._play_your_color()364 return365 elif len(self.move_list) % 2 == 1 and spr.type[0] in 'PRNBQK':366 self._play_your_color()367 return368 self._release = None369 self._press = spr370 self._press.set_layer(TOP)371 self._last_piece_played = [spr, spr.get_xy()]372 return True373 def _wait_your_turn(self):374 if self._activity.playing_white:375 self._activity.status.set_label(376 _('Please wait for your turn.'))377 else:378 self._activity.status.set_label(379 _('Please wait for your turn.'))380 def _play_your_color(self):381 if self._activity.playing_white:382 self._activity.status.set_label(_('Please play White.'))383 else:384 self._activity.status.set_label(_('Please play Black.'))385 def _mouse_move_cb(self, win, event):386 """ Drag a tile with the mouse. """387 spr = self._press388 if spr is None:389 self._dragpos = [0, 0]390 return True391 win.grab_focus()392 x, y = list(map(int, event.get_coords()))393 dx = x - self._dragpos[0]394 dy = y - self._dragpos[1]395 spr.move_relative([dx, dy])396 self._dragpos = [x, y]397 self._total_drag[0] += dx398 self._total_drag[1] += dy399 return True400 def _button_release_cb(self, win, event):401 win.grab_focus()402 self._dragpos = [0, 0]403 if self._press is None:404 return405 x, y = list(map(int, event.get_coords()))406 spr = self._sprites.find_sprite((x, y))407 self._release = spr408 self._release.set_layer(MID)409 self._press = None410 self._release = None411 g1 = self._xy_to_file_and_rank(self._last_piece_played[1])412 g2 = self._xy_to_file_and_rank((x, y))413 # We'll let beginners touch a piece and return it.414 if g1 == g2 or g2 is None:415 spr.move(self._last_piece_played[1])416 return True417 move = '%s%s' % (g1, g2)418 # Queen a pawn (FIXME: really should be able to choose any piece)419 if spr.type == 'p' and g2[1] == '1':420 move += 'Q'421 elif spr.type == 'P' and g2[1] == '8':422 move += 'Q'423 if len(self.move_list) % 2 == 0:424 self._activity.white_entry.set_text(move)425 else:426 self._activity.black_entry.set_text(move)427 self._activity.status.set_label('making a move %s' % (move))428 self.move(move)429 # Get game notation from last move to share and to check for430 # check, checkmate431 self.move(GAME)432 if self.game == '':433 _logger.debug('bad move: reseting')434 return True435 last_move = self.game.split()[-1]436 if self.we_are_sharing:437 self._activity.send_event('m', last_move)438 if '+' in last_move:439 self.check = True440 self._activity.status.set_label(_('Check'))441 if '#' in last_move or '++' in last_move:442 self.checkmate = True443 self._activity.status.set_label(_('Checkmate'))444 if self.checkmate or self.check:445 self._flash_check()446 # Check to see if it is the robot's turn447 if self._activity.playing_robot and \448 self._activity.playing_white and \449 len(self.move_list) % 2 == 0:450 _logger.debug("not the robot's turn")451 return True452 if self._activity.playing_robot and \453 not self._activity.playing_white and \454 len(self.move_list) % 2 == 1:455 _logger.debug("not the robot's turn")456 return True457 if self._activity.playing_robot and not self.checkmate:458 self._activity.set_thinking_cursor()459 self._activity.status.set_label(_('Thinking...'))460 self._thinking = True461 GLib.timeout_add(500, self._robot_move)462 return True463 def _robot_move(self):464 self._get_before()465 self.move(ROBOT)466 # Flash the squares of any piece that robot has moved467 self._get_after()468 if len(self._after) < 64:469 # Game is over470 return471 pieces = [] # Array, since if could be a castling move472 before = []473 after = []474 for i in range(64):475 if self._before[i] != self._after[i]:476 if self._activity.playing_white and \477 self._before[i] in 'prnbqk':478 pieces.append(self._before[i])479 before.append(i)480 elif not self._activity.playing_white and \481 self._before[i] in 'PRNBQK':482 pieces.append(self._before[i])483 before.append(i)484 if self._activity.playing_white and \485 self._after[i] in 'prnbqk':486 pieces.append(self._after[i])487 after.append(i)488 elif not self._activity.playing_white and \489 self._after[i] in 'PRNBQK':490 pieces.append(self._after[i])491 after.append(i)492 tiles = []493 for i in range(len(before)):494 tiles.append(self._index_to_file_and_rank(before[i]))495 tiles.append(self._index_to_file_and_rank(after[i]))496 self._flash_tile(tiles, flash_color=3)497 def _get_before(self):498 self.move(STATUS)499 if self._activity.playing_white:500 tmp = self._output.split('Black')501 else:502 tmp = self._output.split('White')503 self._before = tmp[-2][-137:].split()504 def _get_after(self):505 self.move(STATUS)506 if self._activity.playing_white:507 tmp = self._output.split('White')508 else:509 tmp = self._output.split('Black')510 self._after = tmp[-2][-137:].split()511 def undo(self):512 # TODO: Lock out while robot is playing513 if self._activity.playing_robot and len(self.move_list) > 1:514 if self._activity.playing_white:515 if len(self.move_list) % 2 == 0:516 self.move(REMOVE)517 else:518 self.move(UNDO)519 else:520 if len(self.move_list) % 2 == 1:521 self.move(REMOVE)522 else:523 self.move(UNDO)524 elif len(self.move_list) > 0:525 self.move(UNDO)526 def hint(self):527 # TODO: Lock out while robot is playing528 if self._thinking:529 self._activity.status.set_label(_('Please wait for your turn.'))530 return531 self._activity.set_thinking_cursor()532 self._activity.status.set_label(_('Thinking'))533 self._thinking = True534 GLib.timeout_add(500, self.move, HINT)535 def _flash_check(self):536 if self.check:537 self._activity.status.set_label(_('Check'))538 self._show_check()539 else:540 self._activity.status.set_label(_('Checkmate'))541 self._show_checkmate()542 self._queue_check = True543 if len(self.move_list) % 2 == 0:544 self._flash_tile([self._xy_to_file_and_rank(545 self.white[4].get_xy())])546 else:547 self._flash_tile([self._xy_to_file_and_rank(548 self.black[4].get_xy())])549 def _flash_tile(self, tiles, flash_color=2):550 # Queue the flashing check for after the flashing of the move551 if self._queue_check or self._flashing:552 self._defer_flash = [tiles, flash_color]553 self._queue_check = False554 return555 self._counter = 0556 self._flashing = True557 GLib.timeout_add(100, self._flasher, tiles, flash_color)558 return559 def _flasher(self, tiles, flash_color):560 # Flash length (must be odd in order to guarentee that the561 # original color is restored)562 if self._counter < 13:563 self._counter += 1564 for tile in tiles:565 i = self._file_and_rank_to_index(tile)566 if self._counter % 2 == 0:567 self._board[i].set_image(self._squares[flash_color])568 else:569 self._board[i].set_image(self._squares[black_or_white(i)])570 self._board[i].set_layer(BOT)571 GLib.timeout_add(200, self._flasher, tiles, flash_color)572 else:573 self._reset_board_colors(tiles) # Just in case574 self._flashing = False575 if self._defer_flash[0] is not None:576 tiles = self._defer_flash[0]577 flash_color = self._defer_flash[1]578 self._defer_flash[0] = None579 self._flash_tile(tiles, flash_color)580 def _show_check(self):581 self._check_sprite.set_layer(100)582 GLib.timeout_add(4000, self._hide_check)583 def _hide_check(self):584 self._check_sprite.hide()585 def _show_checkmate(self):586 self._checkmate_sprite.set_layer(100)587 GLib.timeout_add(8000, self._hide_checkmate)588 def _hide_checkmate(self):589 self._checkmate_sprite.hide()590 def _reset_board_colors(self, tiles):591 for tile in tiles:592 i = self._file_and_rank_to_index(tile)593 self._board[i].set_image(self._squares[black_or_white(i)])594 self._board[i].set_layer(BOT)595 def _parse_move(self, move):596 tiles = []597 source_file = None598 source_rank = None599 capture_file = None600 capture_rank = None601 if 'x' in move:602 capture = True603 else:604 capture = False605 if len(self.move_list) % 2 == 0:606 white = True607 if move[0] in FILES:608 piece = 'P'609 source_file = move[0]610 if move[1] in RANKS:611 source_rank = move[1]612 elif move[0] == 'O':613 if move == 'O-O':614 tiles.append('e1')615 tiles.append('g1')616 else: # O-O-O617 tiles.append('c1')618 tiles.append('e1')619 self._flash_tile(tiles)620 return621 else:622 piece = move[0]623 if move[1] in FILES:624 source_file = move[1]625 if move[2] in RANKS:626 source_rank = move[2]627 elif move[1] in RANKS:628 source_rank = move[1]629 if source_rank is None or source_file is None:630 if move[2] in FILES:631 capture_file = move[2]632 if len(move) > 3:633 if move[3] in RANKS:634 capture_rank = move[3]635 else:636 white = False637 if move[0] in FILES:638 piece = 'p'639 source_file = move[0]640 if move[1] in RANKS:641 source_rank = move[1]642 elif move[0] == 'O':643 if move == 'O-O':644 tiles.append('e8')645 tiles.append('g8')646 else: # O-O-O647 tiles.append('c8')648 tiles.append('e8')649 self._flash_tile(tiles)650 return651 else:652 piece = move[0]653 if move[1] in FILES:654 source_file = move[1]655 if move[2] in RANKS:656 source_rank = move[2]657 elif move[1] in RANKS:658 source_rank = move[1]659 if source_rank is None or source_file is None:660 if move[2] in FILES:661 capture_file = move[2]662 if len(move) > 3:663 if move[3] in RANKS:664 capture_rank = move[3]665 if capture:666 move = move[move.find('x') + 1:]667 if white:668 if move[0] in 'KQBNR':669 # capture_piece = move[0]670 if len(move) > 1:671 if move[1] in FILES:672 capture_file = move[1]673 if len(move) > 2:674 if move[2] in RANKS:675 capture_rank = move[2]676 elif move[1] in RANKS:677 capture_rank = move[1]678 else:679 # capture_piece = 'p'680 if move[0] in FILES:681 capture_file = move[0]682 if len(move) > 1:683 if move[1] in RANKS:684 capture_rank = move[1]685 elif move[0] in RANKS:686 capture_rank = move[0]687 else:688 if move[0] in 'KQBNR':689 # capture_piece = move[0]690 if len(move) > 1:691 if move[1] in FILES:692 capture_file = move[1]693 if len(move) > 2:694 if move[2] in RANKS:695 capture_rank = move[2]696 elif move[1] in RANKS:697 capture_rank = move[1]698 else:699 # capture_piece = 'P'700 if move[0] in FILES:701 capture_file = move[0]702 if len(move) > 1:703 if move[1] in RANKS:704 capture_rank = move[1]705 elif move[0] in RANKS:706 capture_rank = move[0]707 if capture_file is None:708 capture_file = source_file709 if capture_rank is None:710 capture_rank = source_rank711 if source_file is None:712 source_file = capture_file713 if source_rank is None:714 source_rank = capture_rank715 if piece in 'pP':716 source_file, source_rank = self._search_for_pawn(717 piece, source_file, source_rank, capture_file, capture_rank,718 capture=capture)719 elif piece in 'rR':720 source_file, source_rank = self._search_for_rook(721 piece, source_file, source_rank, capture_file, capture_rank)722 elif piece in 'nN':723 source_file, source_rank = self._search_for_knight(724 piece, source_file, source_rank, capture_file, capture_rank)725 elif piece in 'bB':726 source_file, source_rank = self._search_for_bishop(727 piece, source_file, source_rank, capture_file, capture_rank)728 elif piece in 'qQ':729 source_file, source_rank = self._search_for_queen(730 piece, source_file, source_rank, capture_file, capture_rank)731 elif piece in 'kK':732 source_file, source_rank = self._search_for_king(733 piece, source_file, source_rank, capture_file, capture_rank)734 tiles.append('%s%s' % (source_file, source_rank))735 tiles.append('%s%s' % (capture_file, capture_rank))736 self._flash_tile(tiles)737 def _search_for_pawn(self, piece, source_file, source_rank, capture_file,738 capture_rank, capture=False):739 # Check for capture740 if capture and len(self.move_list) % 2 == 0:741 if source_file == capture_file:742 f = FILES.index(capture_file)743 if f > 0:744 i = self._file_and_rank_to_index(745 '%s%s' %746 (FILES[f - 1], RANKS[RANKS.index(capture_rank) - 1]))747 x, y = self._index_to_xy(i)748 for p in range(8):749 pos = self.white[8 + p].get_xy()750 if x == pos[0] and y == pos[1]:751 return FILES[f - 1], \752 RANKS[RANKS.index(capture_rank) - 1]753 if f < 7:754 i = self._file_and_rank_to_index(755 '%s%s' %756 (FILES[f + 1], RANKS[RANKS.index(capture_rank) - 1]))757 x, y = self._index_to_xy(i)758 for p in range(8):759 pos = self.white[8 + p].get_xy()760 if x == pos[0] and y == pos[1]:761 return FILES[f + 1], \762 RANKS[RANKS.index(capture_rank) - 1]763 else:764 i = self._file_and_rank_to_index(765 '%s%s' %766 (source_file, RANKS[RANKS.index(capture_rank) - 1]))767 x, y = self._index_to_xy(i)768 for p in range(8):769 pos = self.white[8 + p].get_xy()770 if x == pos[0] and y == pos[1]:771 return source_file, \772 RANKS[RANKS.index(capture_rank) - 1]773 elif capture:774 if source_file == capture_file:775 f = FILES.index(capture_file)776 if f > 0:777 i = self._file_and_rank_to_index(778 '%s%s' %779 (FILES[f - 1], RANKS[RANKS.index(capture_rank) + 1]))780 x, y = self._index_to_xy(i)781 for p in range(8):782 pos = self.black[8 + p].get_xy()783 if x == pos[0] and y == pos[1]:784 return FILES[f - 1], \785 RANKS[RANKS.index(capture_rank) + 1]786 if f < 7:787 i = self._file_and_rank_to_index(788 '%s%s' %789 (FILES[f + 1], RANKS[RANKS.index(capture_rank) + 1]))790 x, y = self._index_to_xy(i)791 for p in range(8):792 pos = self.black[8 + p].get_xy()793 if x == pos[0] and y == pos[1]:794 return FILES[f + 1], \795 RANKS[RANKS.index(capture_rank) + 1]796 else:797 i = self._file_and_rank_to_index(798 '%s%s' %799 (source_file, RANKS[RANKS.index(capture_rank) + 1]))800 x, y = self._index_to_xy(i)801 for p in range(8):802 pos = self.black[8 + p].get_xy()803 if x == pos[0] and y == pos[1]:804 return source_file, \805 RANKS[RANKS.index(capture_rank) + 1]806 # Check for first move807 if piece == 'p' and capture_rank == '5':808 i = self._file_and_rank_to_index('%s7' % (capture_file))809 x, y = self._index_to_xy(i)810 for p in range(8):811 pos = self.black[8 + p].get_xy()812 if x == pos[0] and y == pos[1]:813 return capture_file, '7'814 elif piece == 'P' and capture_rank == '4':815 i = self._file_and_rank_to_index('%s2' % (capture_file))816 x, y = self._index_to_xy(i)817 for p in range(8):818 pos = self.white[8 + p].get_xy()819 if x == pos[0] and y == pos[1]:820 return capture_file, '2'821 # Check for previous space822 if piece == 'p':823 i = self._file_and_rank_to_index(824 '%s%s' %825 (capture_file, RANKS[RANKS.index(capture_rank) + 1]))826 x, y = self._index_to_xy(i)827 for p in range(8):828 pos = self.black[8 + p].get_xy()829 if x == pos[0] and y == pos[1]:830 return capture_file, RANKS[RANKS.index(capture_rank) + 1]831 elif piece == 'P':832 i = self._file_and_rank_to_index(833 '%s%s' %834 (capture_file, RANKS[RANKS.index(capture_rank) - 1]))835 x, y = self._index_to_xy(i)836 for p in range(8):837 pos = self.white[8 + p].get_xy()838 if x == pos[0] and y == pos[1]:839 return capture_file, RANKS[RANKS.index(capture_rank) - 1]840 return capture_file, capture_rank841 def _search_for_rook(self, piece, source_file, source_rank, capture_file,842 capture_rank):843 # Change rank844 if len(self.move_list) % 2 == 1:845 for r in range(7 - RANKS.index(capture_rank)):846 i = self._file_and_rank_to_index(847 '%s%s' %848 (capture_file, RANKS[RANKS.index(capture_rank) + r + 1]))849 p = self._find_piece_at_index(i)850 if p in self.black:851 b = self.black.index(p)852 if piece in 'rR' and (b == 0 or b == 7):853 return capture_file, \854 RANKS[RANKS.index(capture_rank) + r + 1]855 elif piece in 'qQ' and b == 3:856 return capture_file, \857 RANKS[RANKS.index(capture_rank) + r + 1]858 else:859 break860 elif p is not None:861 break862 for r in range(RANKS.index(capture_rank)):863 i = self._file_and_rank_to_index(864 '%s%s' %865 (capture_file, RANKS[RANKS.index(capture_rank) - r - 1]))866 p = self._find_piece_at_index(i)867 if p in self.black:868 b = self.black.index(p)869 if piece in 'rR' and (b == 0 or b == 7):870 return capture_file, \871 RANKS[RANKS.index(capture_rank) - r - 1]872 elif piece in 'qQ' and b == 3:873 return capture_file, \874 RANKS[RANKS.index(capture_rank) - r - 1]875 else:876 break877 elif p is not None:878 break879 else:880 for r in range(7 - RANKS.index(capture_rank)):881 i = self._file_and_rank_to_index(882 '%s%s' %883 (capture_file, RANKS[RANKS.index(capture_rank) + r + 1]))884 p = self._find_piece_at_index(i)885 if p in self.white:886 w = self.white.index(p)887 if piece == 'R' and (w == 0 or w == 7):888 return capture_file, \889 RANKS[RANKS.index(capture_rank) + r + 1]890 elif piece == 'Q' and w == 3:891 return capture_file, \892 RANKS[RANKS.index(capture_rank) + r + 1]893 else:894 break895 elif p is not None:896 break897 for r in range(RANKS.index(capture_rank)):898 i = self._file_and_rank_to_index(899 '%s%s' %900 (capture_file, RANKS[RANKS.index(capture_rank) - r - 1]))901 p = self._find_piece_at_index(i)902 if p in self.white:903 w = self.white.index(p)904 if piece == 'R' and (w == 0 or w == 7):905 return capture_file, \906 RANKS[RANKS.index(capture_rank) - r - 1]907 elif piece == 'Q' and w == 3:908 return capture_file, \909 RANKS[RANKS.index(capture_rank) - r - 1]910 else:911 break912 elif p is not None:913 break914 # Change file915 if len(self.move_list) % 2 == 1:916 for f in range(7 - FILES.index(capture_file)):917 i = self._file_and_rank_to_index(918 '%s%s' %919 (FILES[FILES.index(capture_file) + f + 1], capture_rank))920 p = self._find_piece_at_index(i)921 if p in self.black:922 b = self.black.index(p)923 if piece in 'rR' and (b == 0 or b == 7):924 return FILES[FILES.index(capture_file) + f + 1], \925 capture_rank926 elif piece in 'qQ' and b == 3:927 return FILES[FILES.index(capture_file) + f + 1], \928 capture_rank929 else:930 break931 elif p is not None:932 break933 for f in range(FILES.index(capture_file)):934 i = self._file_and_rank_to_index(935 '%s%s' %936 (FILES[FILES.index(capture_file) - f - 1], capture_rank))937 p = self._find_piece_at_index(i)938 if p in self.black:939 b = self.black.index(p)940 if piece in 'rR' and (b == 0 or b == 7):941 return FILES[FILES.index(capture_file) - f - 1], \942 capture_rank943 elif piece in 'qQ' and b == 3:944 return FILES[FILES.index(capture_file) - f - 1], \945 capture_rank946 else:947 break948 elif p is not None:949 break950 else:951 for f in range(7 - FILES.index(capture_file)):952 i = self._file_and_rank_to_index(953 '%s%s' %954 (FILES[FILES.index(capture_file) + f + 1], capture_rank))955 p = self._find_piece_at_index(i)956 if p in self.white:957 w = self.white.index(p)958 if piece == 'R' and (w == 0 or w == 7):959 return FILES[FILES.index(capture_file) + f + 1], \960 capture_rank961 elif piece == 'Q' and w == 3:962 return FILES[FILES.index(capture_file) + f + 1], \963 capture_rank964 else:965 break966 elif p is not None:967 break968 for f in range(FILES.index(capture_file)):969 i = self._file_and_rank_to_index(970 '%s%s' %971 (FILES[FILES.index(capture_file) - f - 1], capture_rank))972 p = self._find_piece_at_index(i)973 if p in self.white:974 w = self.white.index(p)975 if piece == 'R' and (w == 0 or w == 7):976 return FILES[FILES.index(capture_file) - f - 1], \977 capture_rank978 elif piece == 'Q' and w == 3:979 return FILES[FILES.index(capture_file) - f - 1], \980 capture_rank981 else:982 break983 elif p is not None:984 break985 if piece in 'rR':986 return capture_file, capture_rank987 else:988 return None, None989 def _search_for_knight(self, piece, source_file, source_rank, capture_file,990 capture_rank):991 if len(self.move_list) % 2 == 1: # if piece == 'n':992 if RANKS.index(capture_rank) < 6 and FILES.index(capture_file) > 0:993 i = self._file_and_rank_to_index(994 '%s%s' %995 (FILES[FILES.index(capture_file) - 1],996 RANKS[RANKS.index(capture_rank) + 2]))997 p = self._find_piece_at_index(i)998 if p in self.black:999 b = self.black.index(p)1000 if b in [1, 6]:1001 return FILES[FILES.index(capture_file) - 1], \1002 RANKS[RANKS.index(capture_rank) + 2]1003 if RANKS.index(capture_rank) < 6 and FILES.index(capture_file) < 7:1004 i = self._file_and_rank_to_index(1005 '%s%s' %1006 (FILES[FILES.index(capture_file) + 1],1007 RANKS[RANKS.index(capture_rank) + 2]))1008 p = self._find_piece_at_index(i)1009 if p in self.black:1010 b = self.black.index(p)1011 if b in [1, 6]:1012 return FILES[FILES.index(capture_file) + 1], \1013 RANKS[RANKS.index(capture_rank) + 2]1014 if RANKS.index(capture_rank) > 1 and FILES.index(capture_file) < 7:1015 i = self._file_and_rank_to_index(1016 '%s%s' %1017 (FILES[FILES.index(capture_file) + 1],1018 RANKS[RANKS.index(capture_rank) - 2]))1019 p = self._find_piece_at_index(i)1020 if p in self.black:1021 b = self.black.index(p)1022 if b in [1, 6]:1023 return FILES[FILES.index(capture_file) + 1], \1024 RANKS[RANKS.index(capture_rank) - 2]1025 if RANKS.index(capture_rank) > 1 and FILES.index(capture_file) > 0:1026 i = self._file_and_rank_to_index(1027 '%s%s' %1028 (FILES[FILES.index(capture_file) - 1],1029 RANKS[RANKS.index(capture_rank) - 2]))1030 p = self._find_piece_at_index(i)1031 if p in self.black:1032 b = self.black.index(p)1033 if b in [1, 6]:1034 return FILES[FILES.index(capture_file) - 1], \1035 RANKS[RANKS.index(capture_rank) - 2]1036 if RANKS.index(capture_rank) < 7 and FILES.index(capture_file) > 1:1037 i = self._file_and_rank_to_index(1038 '%s%s' %1039 (FILES[FILES.index(capture_file) - 2],1040 RANKS[RANKS.index(capture_rank) + 1]))1041 p = self._find_piece_at_index(i)1042 if p in self.black:1043 b = self.black.index(p)1044 if b in [1, 6]:1045 return FILES[FILES.index(capture_file) - 2], \1046 RANKS[RANKS.index(capture_rank) + 1]1047 if RANKS.index(capture_rank) < 7 and FILES.index(capture_file) < 6:1048 i = self._file_and_rank_to_index(1049 '%s%s' %1050 (FILES[FILES.index(capture_file) + 2],1051 RANKS[RANKS.index(capture_rank) + 1]))1052 p = self._find_piece_at_index(i)1053 if p in self.black:1054 b = self.black.index(p)1055 if b in [1, 6]:1056 return FILES[FILES.index(capture_file) + 2], \1057 RANKS[RANKS.index(capture_rank) + 1]1058 if RANKS.index(capture_rank) > 0 and FILES.index(capture_file) < 6:1059 i = self._file_and_rank_to_index(1060 '%s%s' %1061 (FILES[FILES.index(capture_file) + 2],1062 RANKS[RANKS.index(capture_rank) - 1]))1063 p = self._find_piece_at_index(i)1064 if p in self.black:1065 b = self.black.index(p)1066 if b in [1, 6]:1067 return FILES[FILES.index(capture_file) + 2], \1068 RANKS[RANKS.index(capture_rank) - 1]1069 if RANKS.index(capture_rank) > 0 and FILES.index(capture_file) > 1:1070 i = self._file_and_rank_to_index(1071 '%s%s' %1072 (FILES[FILES.index(capture_file) - 2],1073 RANKS[RANKS.index(capture_rank) - 1]))1074 p = self._find_piece_at_index(i)1075 if p in self.black:1076 b = self.black.index(p)1077 if b in [1, 6]:1078 return FILES[FILES.index(capture_file) - 2], \1079 RANKS[RANKS.index(capture_rank) - 1]1080 else:1081 if RANKS.index(capture_rank) < 6 and FILES.index(capture_file) > 0:1082 i = self._file_and_rank_to_index(1083 '%s%s' %1084 (FILES[FILES.index(capture_file) - 1],1085 RANKS[RANKS.index(capture_rank) + 2]))1086 p = self._find_piece_at_index(i)1087 if p in self.white:1088 w = self.white.index(p)1089 if w in [1, 6]:1090 return FILES[FILES.index(capture_file) - 1], \1091 RANKS[RANKS.index(capture_rank) + 2]1092 if RANKS.index(capture_rank) < 6 and FILES.index(capture_file) < 7:1093 i = self._file_and_rank_to_index(1094 '%s%s' %1095 (FILES[FILES.index(capture_file) + 1],1096 RANKS[RANKS.index(capture_rank) + 2]))1097 p = self._find_piece_at_index(i)1098 if p in self.white:1099 w = self.white.index(p)1100 if w in [1, 6]:1101 return FILES[FILES.index(capture_file) + 1], \1102 RANKS[RANKS.index(capture_rank) + 2]1103 if RANKS.index(capture_rank) > 1 and FILES.index(capture_file) < 7:1104 i = self._file_and_rank_to_index(1105 '%s%s' %1106 (FILES[FILES.index(capture_file) + 1],1107 RANKS[RANKS.index(capture_rank) - 2]))1108 p = self._find_piece_at_index(i)1109 if p in self.white:1110 w = self.white.index(p)1111 if w in [1, 6]:1112 return FILES[FILES.index(capture_file) + 1], \1113 RANKS[RANKS.index(capture_rank) - 2]1114 if RANKS.index(capture_rank) > 1 and FILES.index(capture_file) > 0:1115 i = self._file_and_rank_to_index(1116 '%s%s' %1117 (FILES[FILES.index(capture_file) - 1],1118 RANKS[RANKS.index(capture_rank) - 2]))1119 p = self._find_piece_at_index(i)1120 if p in self.white:1121 w = self.white.index(p)1122 if w in [1, 6]:1123 return FILES[FILES.index(capture_file) - 1], \1124 RANKS[RANKS.index(capture_rank) - 2]1125 if RANKS.index(capture_rank) < 7 and FILES.index(capture_file) > 1:1126 i = self._file_and_rank_to_index(1127 '%s%s' %1128 (FILES[FILES.index(capture_file) - 2],1129 RANKS[RANKS.index(capture_rank) + 1]))1130 p = self._find_piece_at_index(i)1131 if p in self.white:1132 w = self.white.index(p)1133 if w in [1, 6]:1134 return FILES[FILES.index(capture_file) - 2], \1135 RANKS[RANKS.index(capture_rank) + 1]1136 if RANKS.index(capture_rank) < 7 and FILES.index(capture_file) < 6:1137 i = self._file_and_rank_to_index(1138 '%s%s' %1139 (FILES[FILES.index(capture_file) + 2],1140 RANKS[RANKS.index(capture_rank) + 1]))1141 p = self._find_piece_at_index(i)1142 if p in self.white:1143 w = self.white.index(p)1144 if w in [1, 6]:1145 return FILES[FILES.index(capture_file) + 2], \1146 RANKS[RANKS.index(capture_rank) + 1]1147 if RANKS.index(capture_rank) > 0 and FILES.index(capture_file) < 6:1148 i = self._file_and_rank_to_index(1149 '%s%s' %1150 (FILES[FILES.index(capture_file) + 2],1151 RANKS[RANKS.index(capture_rank) - 1]))1152 p = self._find_piece_at_index(i)1153 if p in self.white:1154 w = self.white.index(p)1155 if w in [1, 6]:1156 return FILES[FILES.index(capture_file) + 2], \1157 RANKS[RANKS.index(capture_rank) - 1]1158 if RANKS.index(capture_rank) > 0 and FILES.index(capture_file) > 1:1159 i = self._file_and_rank_to_index(1160 '%s%s' %1161 (FILES[FILES.index(capture_file) - 2],1162 RANKS[RANKS.index(capture_rank) - 1]))1163 p = self._find_piece_at_index(i)1164 if p in self.white:1165 w = self.white.index(p)1166 if w in [1, 6]:1167 return FILES[FILES.index(capture_file) - 2], \1168 RANKS[RANKS.index(capture_rank) - 1]1169 return capture_file, capture_rank1170 def _search_for_bishop(self, piece, source_file, source_rank, capture_file,1171 capture_rank):1172 # rank++, file++1173 if len(self.move_list) % 2 == 1: # if piece in 'bq':1174 r = RANKS.index(capture_rank) + 11175 f = FILES.index(capture_file) + 11176 while r < 8 and f < 8:1177 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1178 p = self._find_piece_at_index(i)1179 if p in self.black:1180 b = self.black.index(p)1181 if piece in 'bB' and (b == 2 or b == 5):1182 return FILES[f], RANKS[r]1183 elif piece in 'qQ' and b == 3:1184 return FILES[f], RANKS[r]1185 else:1186 break1187 elif p is not None:1188 break1189 r += 11190 f += 11191 if len(self.move_list) % 2 == 0: # if piece in 'BQ':1192 r = RANKS.index(capture_rank) + 11193 f = FILES.index(capture_file) + 11194 while r < 8 and f < 8:1195 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1196 p = self._find_piece_at_index(i)1197 if p in self.white:1198 w = self.white.index(p)1199 if piece == 'B' and (w == 2 or w == 5):1200 return FILES[f], RANKS[r]1201 elif piece == 'Q' and w == 3:1202 return FILES[f], RANKS[r]1203 else:1204 break1205 elif p is not None:1206 break1207 r += 11208 f += 11209 # rank--, file++1210 if len(self.move_list) % 2 == 1: # if piece in 'bq':1211 r = RANKS.index(capture_rank) - 11212 f = FILES.index(capture_file) + 11213 while r > -1 and f < 8:1214 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1215 p = self._find_piece_at_index(i)1216 if p in self.black:1217 b = self.black.index(p)1218 if piece in 'bB' and (b == 2 or b == 5):1219 return FILES[f], RANKS[r]1220 elif piece in 'qQ' and b == 3:1221 return FILES[f], RANKS[r]1222 else:1223 break1224 elif p is not None:1225 break1226 r -= 11227 f += 11228 if len(self.move_list) % 2 == 0: # if piece in 'BQ':1229 r = RANKS.index(capture_rank) - 11230 f = FILES.index(capture_file) + 11231 while r > -1 and f < 8:1232 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1233 p = self._find_piece_at_index(i)1234 if p in self.white:1235 w = self.white.index(p)1236 if piece == 'B' and (w == 2 or w == 5):1237 return FILES[f], RANKS[r]1238 elif piece == 'Q' and w == 3:1239 return FILES[f], RANKS[r]1240 else:1241 break1242 elif p is not None:1243 break1244 r -= 11245 f += 11246 # rank-- file--1247 if len(self.move_list) % 2 == 1: # if piece in 'bq':1248 r = RANKS.index(capture_rank) - 11249 f = FILES.index(capture_file) - 11250 while r > -1 and f > -1:1251 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1252 p = self._find_piece_at_index(i)1253 if p in self.black:1254 b = self.black.index(p)1255 if piece in 'bB' and (b == 2 or b == 5):1256 return FILES[f], RANKS[r]1257 elif piece in 'qQ' and b == 3:1258 return FILES[f], RANKS[r]1259 else:1260 break1261 elif p is not None:1262 break1263 r -= 11264 f -= 11265 if len(self.move_list) % 2 == 0: # if piece in 'BQ':1266 r = RANKS.index(capture_rank) - 11267 f = FILES.index(capture_file) - 11268 while r > -1 and f > -1:1269 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1270 p = self._find_piece_at_index(i)1271 if p in self.white:1272 w = self.white.index(p)1273 if piece == 'B' and (w == 2 or w == 5):1274 return FILES[f], RANKS[r]1275 elif piece == 'Q' and w == 3:1276 return FILES[f], RANKS[r]1277 else:1278 break1279 elif p is not None:1280 break1281 r -= 11282 f -= 11283 # rank++ file--1284 if len(self.move_list) % 2 == 1: # if piece in 'bq':1285 r = RANKS.index(capture_rank) + 11286 f = FILES.index(capture_file) - 11287 while r < 8 and f > -1:1288 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1289 p = self._find_piece_at_index(i)1290 if p in self.black:1291 b = self.black.index(p)1292 if piece in 'bB' and (b == 2 or b == 5):1293 return FILES[f], RANKS[r]1294 elif piece in 'qQ' and b == 3:1295 return FILES[f], RANKS[r]1296 else:1297 break1298 elif p is not None:1299 break1300 r += 11301 f -= 11302 if len(self.move_list) % 2 == 0: # if piece in 'BQ':1303 r = RANKS.index(capture_rank) + 11304 f = FILES.index(capture_file) - 11305 while r < 8 and f > -1:1306 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1307 p = self._find_piece_at_index(i)1308 if p in self.white:1309 w = self.white.index(p)1310 if piece == 'B' and (w == 2 or w == 5):1311 return FILES[f], RANKS[r]1312 elif piece == 'Q' and w == 3:1313 return FILES[f], RANKS[r]1314 else:1315 break1316 elif p is not None:1317 break1318 r += 11319 f -= 11320 return capture_file, capture_rank1321 def _search_for_queen(self, piece, source_file, source_rank, capture_file,1322 capture_rank):1323 file_and_rank = self._search_for_rook(1324 piece, source_file, source_rank, capture_file, capture_rank)1325 if file_and_rank[0] is not None:1326 return file_and_rank[0], file_and_rank[1]1327 return self._search_for_bishop(1328 piece, source_file, source_rank, capture_file, capture_rank)1329 def _search_for_king(self, piece, source_file, source_rank, capture_file,1330 capture_rank):1331 if len(self.move_list) % 2 == 1: # if piece == 'k':1332 r = RANKS.index(capture_rank) + 11333 f = FILES.index(capture_file) + 11334 if r < 8 and f < 8:1335 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1336 p = self._find_piece_at_index(i)1337 if p in self.black:1338 b = self.black.index(p)1339 if b == 4:1340 return FILES[f], RANKS[r]1341 r = RANKS.index(capture_rank) + 11342 f = FILES.index(capture_file)1343 if r < 8:1344 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1345 p = self._find_piece_at_index(i)1346 if p in self.black:1347 b = self.black.index(p)1348 if b == 4:1349 return FILES[f], RANKS[r]1350 r = RANKS.index(capture_rank) + 11351 f = FILES.index(capture_file) - 11352 if r < 8 and f > -1:1353 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1354 p = self._find_piece_at_index(i)1355 if p in self.black:1356 b = self.black.index(p)1357 if b == 4:1358 return FILES[f], RANKS[r]1359 r = RANKS.index(capture_rank)1360 f = FILES.index(capture_file) + 11361 if r < 8 and f < 8:1362 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1363 p = self._find_piece_at_index(i)1364 if p in self.black:1365 b = self.black.index(p)1366 if b == 4:1367 return FILES[f], RANKS[r]1368 r = RANKS.index(capture_rank)1369 f = FILES.index(capture_file) - 11370 if f > -1:1371 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1372 p = self._find_piece_at_index(i)1373 if p in self.black:1374 b = self.black.index(p)1375 if b == 4:1376 return FILES[f], RANKS[r]1377 r = RANKS.index(capture_rank) - 11378 f = FILES.index(capture_file) + 11379 if r > -1 and f < 8:1380 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1381 p = self._find_piece_at_index(i)1382 if p in self.black:1383 b = self.black.index(p)1384 if b == 4:1385 return FILES[f], RANKS[r]1386 r = RANKS.index(capture_rank) - 11387 f = FILES.index(capture_file)1388 if r > -1:1389 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1390 p = self._find_piece_at_index(i)1391 if p in self.black:1392 b = self.black.index(p)1393 if b == 4:1394 return FILES[f], RANKS[r]1395 r = RANKS.index(capture_rank) - 11396 f = FILES.index(capture_file) - 11397 if r > -1 and f > -1:1398 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1399 p = self._find_piece_at_index(i)1400 if p in self.black:1401 b = self.black.index(p)1402 if b == 4:1403 return FILES[f], RANKS[r]1404 else:1405 r = RANKS.index(capture_rank) + 11406 f = FILES.index(capture_file) + 11407 if r < 8 and f < 8:1408 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1409 p = self._find_piece_at_index(i)1410 if p in self.white:1411 w = self.white.index(p)1412 if w == 4:1413 return FILES[f], RANKS[r]1414 r = RANKS.index(capture_rank) + 11415 f = FILES.index(capture_file)1416 if r < 8:1417 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1418 p = self._find_piece_at_index(i)1419 if p in self.white:1420 w = self.white.index(p)1421 if w == 4:1422 return FILES[f], RANKS[r]1423 r = RANKS.index(capture_rank) + 11424 f = FILES.index(capture_file) - 11425 if r < 8 and f > -1:1426 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1427 p = self._find_piece_at_index(i)1428 if p in self.white:1429 w = self.white.index(p)1430 if w == 4:1431 return FILES[f], RANKS[r]1432 r = RANKS.index(capture_rank)1433 f = FILES.index(capture_file) + 11434 if r < 8 and f < 8:1435 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1436 p = self._find_piece_at_index(i)1437 if p in self.white:1438 w = self.white.index(p)1439 if w == 4:1440 return FILES[f], RANKS[r]1441 r = RANKS.index(capture_rank)1442 f = FILES.index(capture_file) - 11443 if f > -1:1444 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1445 p = self._find_piece_at_index(i)1446 if p in self.white:1447 w = self.white.index(p)1448 if w == 4:1449 return FILES[f], RANKS[r]1450 r = RANKS.index(capture_rank) - 11451 f = FILES.index(capture_file) + 11452 if r > -1 and f < 8:1453 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1454 p = self._find_piece_at_index(i)1455 if p in self.white:1456 w = self.white.index(p)1457 if w == 4:1458 return FILES[f], RANKS[r]1459 r = RANKS.index(capture_rank) - 11460 f = FILES.index(capture_file)1461 if r > -1:1462 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1463 p = self._find_piece_at_index(i)1464 if p in self.white:1465 w = self.white.index(p)1466 if w == 4:1467 return FILES[f], RANKS[r]1468 r = RANKS.index(capture_rank) - 11469 f = FILES.index(capture_file) - 11470 if r > -1 and f > -1:1471 i = self._file_and_rank_to_index('%s%s' % (FILES[f], RANKS[r]))1472 p = self._find_piece_at_index(i)1473 if p in self.white:1474 w = self.white.index(p)1475 if w == 4:1476 return FILES[f], RANKS[r]1477 return capture_file, capture_rank1478 def remote_move(self, move):1479 ''' Receive a move from a network '''1480 if not self.we_are_sharing:1481 return1482 if self._activity.playing_white and len(self.move_list) % 2 == 0:1483 return1484 elif not self._activity.playing_white and len(self.move_list) % 2 == 1:1485 return1486 _logger.debug('Processing remote move (%s)' % (move))1487 self.move(move)1488 def set_sharing(self, share=True):1489 _logger.debug('enabling sharing')1490 self.we_are_sharing = share1491 def _find_piece_at_index(self, i):1492 pos = self._index_to_xy(i)1493 return self._find_piece_at_xy(pos)1494 def _find_piece_at_xy(self, pos):1495 for w in self.white:1496 x, y = w.get_xy()1497 if x == pos[0] and y == pos[1]:1498 return w1499 for b in self.black:1500 x, y = b.get_xy()1501 if x == pos[0] and y == pos[1]:1502 return b1503 return None1504 def _index_to_file_and_rank(self, i):1505 return '%s%s' % (FILES[i % 8], RANKS[7 - int(i / 8)])1506 def _file_and_rank_to_index(self, file_and_rank):1507 ''' calculate the tile index from the file and rank '''1508 return FILES.index(file_and_rank[0]) + \1509 8 * (7 - RANKS.index(file_and_rank[1]))1510 def _index_to_xy(self, i):1511 return self._board[i].get_xy()1512 def _xy_to_file_and_rank(self, pos):1513 ''' calculate the board column and row for an xy position '''1514 xo = self._width - 8 * self.scale1515 xo = int(xo / 2)1516 yo = int(self.scale / 2)1517 x = int((pos[0] - xo) / self.scale)1518 y = 8 - int((pos[1] - yo) / self.scale)1519 if x < 0 or x > 7:1520 return None # off the board1521 else:1522 return ('{}{}'.format(FILES[x], y))1523 def __draw_cb(self, canvas, cr):1524 self._sprites.redraw_sprites(cr=cr)1525 def do_expose_event(self, event):1526 ''' Handle the expose-event by drawing '''1527 # Restrict Cairo to the exposed area1528 cr = self._canvas.window.cairo_create()1529 cr.rectangle(event.area.x, event.area.y,1530 event.area.width, event.area.height)1531 cr.clip()1532 # Refresh sprite list1533 self._sprites.redraw_sprites(cr=cr)1534 def _destroy_cb(self, win, event):1535 Gtk.main_quit()1536 def _load_board(self, board):1537 ''' Load the board based on gnuchess board output '''1538 # _logger.debug(board)1539 white_pawns = 01540 white_rooks = 01541 white_knights = 01542 white_bishops = 01543 white_queens = 01544 black_pawns = 01545 black_rooks = 01546 black_knights = 01547 black_bishops = 01548 black_queens = 01549 w, h = self.white[0].get_dimensions()1550 xo = self._width - 8 * self.scale1551 xo = int(xo / 2)1552 yo = int(self.scale / 2)1553 for i in range(17): # extra queen1554 self.black[i].move((-self.scale, -self.scale))1555 self.white[i].move((-self.scale, -self.scale))1556 k = 11557 for i in range(8):1558 x = xo1559 y = yo + i * self.scale1560 for j in range(8):1561 piece = board[k]1562 k += 21563 if piece in 'PRNBQK': # white1564 if piece == 'P':1565 self.white[8 + white_pawns].move((x, y))1566 white_pawns += 11567 elif piece == 'R':1568 if white_rooks == 0:1569 self.white[0].move((x, y))1570 white_rooks += 11571 else:1572 self.white[7].move((x, y))1573 white_rooks += 11574 elif piece == 'N':1575 if white_knights == 0:1576 self.white[1].move((x, y))1577 white_knights += 11578 else:1579 self.white[6].move((x, y))1580 white_knights += 11581 elif piece == 'B':1582 if white_bishops == 0:1583 self.white[2].move((x, y))1584 white_bishops += 11585 else:1586 self.white[5].move((x, y))1587 white_bishops += 11588 elif piece == 'Q':1589 if white_queens == 0:1590 self.white[3].move((x, y))1591 white_queens += 11592 else:1593 self.white[16].move((x, y))1594 self.white[16].set_layer(MID)1595 elif piece == 'K':1596 self.white[4].move((x, y))1597 elif piece in 'prnbqk': # black1598 if piece == 'p':1599 self.black[8 + black_pawns].move((x, y))1600 black_pawns += 11601 elif piece == 'r':1602 if black_rooks == 0:1603 self.black[0].move((x, y))1604 black_rooks += 11605 else:1606 self.black[7].move((x, y))1607 black_rooks += 11608 elif piece == 'n':1609 if black_knights == 0:1610 self.black[1].move((x, y))1611 black_knights += 11612 else:1613 self.black[6].move((x, y))1614 black_knights += 11615 elif piece == 'b':1616 if black_bishops == 0:1617 self.black[2].move((x, y))1618 black_bishops += 11619 else:1620 self.black[5].move((x, y))1621 black_bishops += 11622 elif piece == 'q':1623 if black_queens == 0:1624 self.black[3].move((x, y))1625 black_queens += 11626 else:1627 self.black[16].move((x, y))1628 self.black[16].set_layer(MID)1629 elif piece == 'k':1630 self.black[4].move((x, y))1631 x += self.scale1632 x = xo1633 y += self.scale1634 k += 11635 def reskin_from_svg(self, piece, colors, bw='#ffffff'):1636 DICT = {'white_pawn': svg_pawn, 'black_pawn': svg_pawn,1637 'white_rook': svg_rook, 'black_rook': svg_rook,1638 'white_knight': svg_knight, 'black_knight': svg_knight,1639 'white_bishop': svg_bishop, 'black_bishop': svg_bishop,1640 'white_queen': svg_queen, 'black_queen': svg_queen,1641 'white_king': svg_king, 'black_king': svg_king}1642 pixbuf = svg_str_to_pixbuf(1643 svg_header(colors) + DICT[piece](bw) + svg_footer(),1644 w=self.scale, h=self.scale)1645 self.reskin(piece, pixbuf)1646 def reskin_from_file(self, piece, file_path, return_pixbuf=False):1647 pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(1648 file_path, self.scale, self.scale)1649 self.reskin(piece, pixbuf)1650 if return_pixbuf:1651 return pixbuf1652 def reskin(self, piece, pixbuf):1653 DICT = {'white_pawn': WP, 'black_pawn': BP,1654 'white_rook': WR, 'black_rook': BR,1655 'white_knight': WN, 'black_knight': BN,1656 'white_bishop': WB, 'black_bishop': BB,1657 'white_queen': WQ, 'black_queen': BQ,1658 'white_king': WK, 'black_king': BK}1659 self.skins[DICT[piece]] = pixbuf1660 if piece == 'white_pawn':1661 for i in range(8):1662 self.white[i + 8].set_image(pixbuf)1663 self.white[i + 8].set_layer(MID)1664 elif piece == 'black_pawn':1665 for i in range(8):1666 self.black[i + 8].set_image(pixbuf)1667 self.black[i + 8].set_layer(MID)1668 elif piece == 'white_rook':1669 self.white[0].set_image(pixbuf)1670 self.white[7].set_image(pixbuf)1671 self.white[0].set_layer(MID)1672 self.white[7].set_layer(MID)1673 elif piece == 'black_rook':1674 self.black[0].set_image(pixbuf)1675 self.black[7].set_image(pixbuf)1676 self.black[0].set_layer(MID)1677 self.black[7].set_layer(MID)1678 elif piece == 'white_knight':1679 self.white[1].set_image(pixbuf)1680 self.white[6].set_image(pixbuf)1681 self.white[1].set_layer(MID)1682 self.white[6].set_layer(MID)1683 elif piece == 'black_knight':1684 self.black[1].set_image(pixbuf)1685 self.black[6].set_image(pixbuf)1686 self.black[1].set_layer(MID)1687 self.black[6].set_layer(MID)1688 elif piece == 'white_bishop':1689 self.white[2].set_image(pixbuf)1690 self.white[5].set_image(pixbuf)1691 self.white[2].set_layer(MID)1692 self.white[5].set_layer(MID)1693 elif piece == 'black_bishop':1694 self.black[2].set_image(pixbuf)1695 self.black[5].set_image(pixbuf)1696 self.black[2].set_layer(MID)1697 self.black[5].set_layer(MID)1698 elif piece == 'white_queen':1699 self.white[3].set_image(pixbuf)1700 self.white[16].set_image(pixbuf)1701 self.white[3].set_layer(MID)1702 self.white[16].set_layer(MID)1703 elif piece == 'black_queen':1704 self.black[3].set_image(pixbuf)1705 self.black[16].set_image(pixbuf)1706 self.black[3].set_layer(MID)1707 self.black[16].set_layer(MID)1708 elif piece == 'white_king':1709 self.white[4].set_image(pixbuf)1710 self.white[4].set_layer(MID)1711 elif piece == 'black_king':1712 self.black[4].set_image(pixbuf)1713 self.black[4].set_layer(MID)1714 def _generate_sprites(self, colors):1715 if 'xo' in self._activity.hardware:1716 fontsize = 241717 else:1718 fontsize = 181719 self.bg = []1720 for i in range(3):1721 self.bg.append(1722 Sprite(self._sprites, 0, 0, self._box(1723 int(self._width), self._height, color=colors[1])))1724 self.bg[-1].set_layer(-1)1725 self.bg[-1].set_margins(l=10, t=10, r=10, b=10)1726 self.bg[-1].set_label_attributes(fontsize, horiz_align="left",1727 vert_align="top")1728 self.bg[-1].type = None1729 self.bg[1].move_relative((int(self._width / 3), 0))1730 self.bg[2].move_relative((int(2 * self._width / 3), 0))1731 xo = self._width - 8 * self.scale1732 xo = int(xo / 2)1733 yo = int(self.scale / 2)1734 self.rank = Sprite(self._sprites, xo - self.scale, yo,1735 GdkPixbuf.Pixbuf.new_from_file_at_size(1736 '%s/images/rank.svg' % (self._bundle_path),1737 self.scale, 8 * self.scale))1738 self.rank.set_layer(0)1739 self.file = Sprite(self._sprites, xo, yo + int(self.scale * 8),1740 GdkPixbuf.Pixbuf.new_from_file_at_size(1741 '%s/images/file.svg' % (self._bundle_path),1742 8 * self.scale, self.scale))1743 self.file.set_layer(0)1744 x = int((Gdk.Screen.width() - 6 * self.scale) / 2.)1745 y = int((Gdk.Screen.height() - 4 * self.scale) / 2.)1746 self._check_sprite = Sprite(1747 self._sprites, x, y,1748 self._box(self.scale * 6, self.scale, color='none'))1749 self._check_sprite.set_label_attributes(fontsize * 2)1750 self._check_sprite.set_label_color(colors[0])1751 self._check_sprite.set_label('♚ ' + _('Check') + ' ♚')1752 self._check_sprite.type = 'check'1753 self._check_sprite.hide()1754 self._checkmate_sprite = Sprite(1755 self._sprites, x, y,1756 self._box(self.scale * 6, self.scale, color='none'))1757 self._checkmate_sprite.set_label_attributes(fontsize * 2)1758 self._checkmate_sprite.set_label_color(colors[0])1759 self._checkmate_sprite.set_label('♚ ' + _('Checkmate') + ' ♚')1760 self._checkmate_sprite.type = 'checkmate'1761 self._checkmate_sprite.hide()1762 w = h = self.scale1763 self._squares.append(self._box(w, h, color='black'))1764 self._squares.append(self._box(w, h, color='white'))1765 self._squares.append(self._box(w, h, color=colors[0]))1766 self._squares.append(self._box(w, h, color=colors[1]))1767 xo = self._width - 8 * self.scale1768 xo = int(xo / 2)1769 yo = int(self.scale / 2)1770 y = yo1771 for i in range(8):1772 x = xo1773 for j in range(8):1774 self._board.append(1775 Sprite(self._sprites, x, y,1776 self._squares[black_or_white([i, j])]))1777 self._board[-1].type = None # '%s%d' % (FILES[j], 8 - i)1778 self._board[-1].set_layer(BOT)1779 x += self.scale1780 y += self.scale1781 for piece in list(PATHS.keys()):1782 self.skins[piece] = GdkPixbuf.Pixbuf.new_from_file_at_size(1783 '%s/icons/%s.svg' % (self._bundle_path, PATHS[piece]), w, h)1784 for piece in [WR, WN, WB, WQ, WK, WB, WN, WR]:1785 self.white.append(Sprite(self._sprites, 0, 0, self.skins[piece]))1786 self.white[-1].type = TYPES[piece]1787 self.white[-1].set_layer(MID)1788 for i in range(8):1789 self.white.append(Sprite(self._sprites, 0, 0, self.skins[WP]))1790 self.white[-1].type = TYPES[WP]1791 self.white[-1].set_layer(MID)1792 # extra queen for pawn1793 self.white.append(Sprite(self._sprites, 0, 0, self.skins[WQ]))1794 self.white[-1].type = TYPES[WQ]1795 self.white[-1].hide()1796 for piece in [BR, BN, BB, BQ, BK, BB, BN, BR]:1797 self.black.append(Sprite(self._sprites, 0, 0, self.skins[piece]))1798 self.black[-1].type = TYPES[piece]1799 self.black[-1].set_layer(MID)1800 for i in range(8):1801 self.black.append(Sprite(self._sprites, 0, 0, self.skins[BP]))1802 self.black[-1].type = TYPES[BP]1803 self.black[-1].set_layer(MID)1804 # extra queen for pawn1805 self.black.append(Sprite(self._sprites, 0, 0, self.skins[BQ]))1806 self.black[-1].type = TYPES[BQ]1807 self.black[-1].hide()1808 def _box(self, w, h, color='black'):1809 ''' Generate a box '''1810 self._svg_width = w1811 self._svg_height = h1812 return svg_str_to_pixbuf(1813 self._header() +1814 self._rect(self._svg_width, self._svg_height, 0, 0,1815 color=color) +1816 self._footer())1817 def _header(self):1818 return '<svg\n' + 'xmlns:svg="http://www.w3.org/2000/svg"\n' + \1819 'xmlns="http://www.w3.org/2000/svg"\n' + \1820 'xmlns:xlink="http://www.w3.org/1999/xlink"\n' + \1821 'version="1.1"\n' + 'width="' + str(self._svg_width) + '"\n' + \1822 'height="' + str(self._svg_height) + '">\n'1823 def _rect(self, w, h, x, y, color='black'):1824 svg_string = ' <rect\n'1825 svg_string += ' width="%f"\n' % (w)1826 svg_string += ' height="%f"\n' % (h)1827 svg_string += ' rx="%f"\n' % (0)1828 svg_string += ' ry="%f"\n' % (0)1829 svg_string += ' x="%f"\n' % (x)1830 svg_string += ' y="%f"\n' % (y)1831 if color == 'black':1832 svg_string += 'style="fill:#000000;stroke:#000000;"/>\n'1833 elif color == 'white':1834 svg_string += 'style="fill:#ffffff;stroke:#ffffff;"/>\n'1835 else:1836 svg_string += 'style="fill:%s;stroke:%s;"/>\n' % (color, color)1837 return svg_string1838 def _footer(self):1839 return '</svg>\n'1840def svg_str_to_pixbuf(svg_string, w=None, h=None):1841 """ Load pixbuf from SVG string """1842 pl = GdkPixbuf.PixbufLoader.new_with_type('svg')1843 if w is not None:1844 pl.set_size(w, h)1845 pl.write(svg_string.encode())1846 pl.close()1847 pixbuf = pl.get_pixbuf()1848 return pixbuf1849def black_or_white(n):1850 ''' Return 0 is it is a black square; 1 if it is a white square '''1851 if type(n) is int:1852 i = int(n / 8)1853 j = n % 81854 else:1855 i = n[0]1856 j = n[1]1857 if i % 2 == 0:1858 if (i * 8 + j) % 2 == 1:1859 return 01860 else:1861 return 11862 else:1863 if (i * 8 + j) % 2 == 1:1864 return 11865 else:...

Full Screen

Full Screen

sniffer.py

Source:sniffer.py Github

copy

Full Screen

...46 """Destroys the sniffers and terminates any ongoing capture sessions.47 """48 for sniffer in objs:49 try:50 sniffer.stop_capture()51 except SnifferError:52 pass53class SnifferError(Exception):54 """This is the Exception class defined for all errors generated by55 Sniffer-related modules.56 """57 pass58class InvalidDataError(Exception):59 """This exception is thrown when invalid configuration data is passed60 to a method.61 """62 pass63class ExecutionError(SnifferError):64 """This exception is thrown when trying to configure the capture device65 or when trying to execute the capture operation.66 When this exception is seen, it is possible that the sniffer module is run67 without sudo (for local sniffers) or keys are out-of-date (for remote68 sniffers).69 """70 pass71class InvalidOperationError(SnifferError):72 """Certain methods may only be accessed when the instance upon which they73 are invoked is in a certain state. This indicates that the object is not74 in the correct state for a method to be called.75 """76 pass77class Sniffer(object):78 """This class defines an object representing a sniffer.79 The object defines the generic behavior of sniffers - irrespective of how80 they are implemented, or where they are located: on the local machine or on81 the remote machine.82 """83 CONFIG_KEY_CHANNEL = "channel"84 def __init__(self, interface, logger, base_configs=None):85 """The constructor for the Sniffer. It constructs a sniffer and86 configures it to be ready for capture.87 Args:88 interface: A string specifying the interface used to configure the89 sniffer.90 logger: ACTS logger object.91 base_configs: A dictionary containing baseline configurations of the92 sniffer. These can be overridden when staring a capture. The93 keys are specified by Sniffer.CONFIG_KEY_*.94 Returns:95 self: A configured sniffer.96 Raises:97 InvalidDataError: if the config_path is invalid.98 NoPermissionError: if an error occurs while configuring the99 sniffer.100 """101 raise NotImplementedError("Base class should not be called directly!")102 def get_descriptor(self):103 """This function returns a string describing the sniffer. The specific104 string (and its format) is up to each derived sniffer type.105 Returns:106 A string describing the sniffer.107 """108 raise NotImplementedError("Base class should not be called directly!")109 def get_type(self):110 """This function returns the type of the sniffer.111 Returns:112 The type (string) of the sniffer. Corresponds to the 'Type' key of113 the sniffer configuration.114 """115 raise NotImplementedError("Base class should not be called directly!")116 def get_subtype(self):117 """This function returns the sub-type of the sniffer.118 Returns:119 The sub-type (string) of the sniffer. Corresponds to the 'SubType'120 key of the sniffer configuration.121 """122 raise NotImplementedError("Base class should not be called directly!")123 def get_interface(self):124 """This function returns The interface used to configure the sniffer,125 e.g. 'wlan0'.126 Returns:127 The interface (string) used to configure the sniffer. Corresponds to128 the 'Interface' key of the sniffer configuration.129 """130 raise NotImplementedError("Base class should not be called directly!")131 def get_capture_file(self):132 """The sniffer places a capture in the logger directory. This function133 enables the caller to obtain the path of that capture.134 Returns:135 The full path of the current or last capture.136 """137 raise NotImplementedError("Base class should not be called directly!")138 def start_capture(self,139 override_configs=None,140 additional_args=None,141 duration=None,142 packet_count=None):143 """This function starts a capture which is saved to the specified file144 path.145 Depending on the type/subtype and configuration of the sniffer the146 capture may terminate on its own or may require an explicit call to the147 stop_capture() function.148 This is a non-blocking function so a terminating function must be149 called - either explicitly or implicitly:150 - Explicitly: call either stop_capture() or wait_for_capture()151 - Implicitly: use with a with clause. The wait_for_capture() function152 will be called if a duration is specified (i.e. is not153 None), otherwise a stop_capture() will be called.154 The capture is saved to a file in the log path of the logger. Use155 the get_capture_file() to get the full path to the current or most156 recent capture.157 Args:158 override_configs: A dictionary which is combined with the159 base_configs ("BaseConfigs" in the sniffer configuration). The160 keys (specified by Sniffer.CONFIG_KEY_*) determine the161 configuration of the sniffer for this specific capture.162 additional_args: A string specifying additional raw163 command-line arguments to pass to the underlying sniffer. The164 interpretation of these flags is sniffer-dependent.165 duration: An integer specifying the number of seconds over which to166 capture packets. The sniffer will be terminated after this167 duration. Used in implicit mode when using a 'with' clause. In168 explicit control cases may have to be performed using a169 sleep+stop or as the timeout argument to the wait function.170 packet_count: An integer specifying the number of packets to capture171 before terminating. Should be used with duration to guarantee172 that capture terminates at some point (even if did not capture173 the specified number of packets).174 Returns:175 An ActiveCaptureContext process which can be used with a 'with'176 clause.177 Raises:178 InvalidDataError: for invalid configurations179 NoPermissionError: if an error occurs while configuring and running180 the sniffer.181 """182 raise NotImplementedError("Base class should not be called directly!")183 def stop_capture(self):184 """This function stops a capture and guarantees that the capture is185 saved to the capture file configured during the start_capture() method.186 Depending on the type of the sniffer the file may previously contain187 partial results (e.g. for a local sniffer) or may not exist until the188 stop_capture() method is executed (e.g. for a remote sniffer).189 Depending on the type/subtype and configuration of the sniffer the190 capture may terminate on its own without requiring a call to this191 function. In such a case it is still necessary to call either this192 function or the wait_for_capture() function to make sure that the193 capture file is moved to the correct location.194 Raises:195 NoPermissionError: No permission when trying to stop a capture196 and save the capture file.197 """198 raise NotImplementedError("Base class should not be called directly!")199 def wait_for_capture(self, timeout=None):200 """This function waits for a capture to terminate and guarantees that201 the capture is saved to the capture file configured during the202 start_capture() method. Depending on the type of the sniffer the file203 may previously contain partial results (e.g. for a local sniffer) or204 may not exist until the stop_capture() method is executed (e.g. for a205 remote sniffer).206 Depending on the type/subtype and configuration of the sniffer the207 capture may terminate on its own without requiring a call to this208 function. In such a case it is still necessary to call either this209 function or the stop_capture() function to make sure that the capture210 file is moved to the correct location.211 Args:212 timeout: An integer specifying the number of seconds to wait for213 the capture to terminate on its own. On expiration of the214 timeout the sniffer is stopped explicitly using the215 stop_capture() function.216 Raises:217 NoPermissionError: No permission when trying to stop a capture and218 save the capture file.219 """220 raise NotImplementedError("Base class should not be called directly!")221class ActiveCaptureContext(object):222 """This class defines an object representing an active sniffer capture.223 The object is returned by a Sniffer.start_capture() command and terminates224 the capture when the 'with' clause exits. It is syntactic sugar for225 try/finally.226 """227 _sniffer = None228 _timeout = None229 def __init__(self, sniffer, timeout=None):230 self._sniffer = sniffer231 self._timeout = timeout232 def __enter__(self):233 pass234 def __exit__(self, type, value, traceback):235 if self._sniffer is not None:236 if self._timeout is None:237 self._sniffer.stop_capture()238 else:239 self._sniffer.wait_for_capture(self._timeout)...

Full Screen

Full Screen

video_capture.gypi

Source:video_capture.gypi Github

copy

Full Screen

1# Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.2#3# Use of this source code is governed by a BSD-style license4# that can be found in the LICENSE file in the root of the source5# tree. An additional intellectual property rights grant can be found6# in the file PATENTS. All contributing project authors may7# be found in the AUTHORS file in the root of the source tree.8{9 'targets': [10 {11 # Note this library is missing an implementation for the video capture.12 # Targets must link with either 'video_capture' or13 # 'video_capture_module_internal_impl' depending on whether they want to14 # use the internal capturer.15 'target_name': 'video_capture_module',16 'type': 'static_library',17 'dependencies': [18 'webrtc_utility',19 '<(webrtc_root)/common_video/common_video.gyp:common_video',20 '<(webrtc_root)/system_wrappers/system_wrappers.gyp:system_wrappers',21 ],22 'sources': [23 'device_info_impl.cc',24 'device_info_impl.h',25 'include/video_capture.h',26 'include/video_capture_defines.h',27 'include/video_capture_factory.h',28 'video_capture_config.h',29 'video_capture_delay.h',30 'video_capture_factory.cc',31 'video_capture_impl.cc',32 'video_capture_impl.h',33 ],34 },35 {36 # Default video capture module implementation that only supports external37 # capture.38 'target_name': 'video_capture',39 'type': 'static_library',40 'dependencies': [41 'video_capture_module',42 ],43 'sources': [44 'external/device_info_external.cc',45 'external/video_capture_external.cc',46 ],47 },48 ], # targets49 'conditions': [50 ['build_with_chromium==0', {51 'targets': [52 {53 'target_name': 'video_capture_module_internal_impl',54 'type': 'static_library',55 'conditions': [56 ['OS!="android"', {57 'dependencies': [58 'video_capture_module',59 '<(webrtc_root)/common.gyp:webrtc_common',60 ],61 }],62 ['OS=="linux"', {63 'sources': [64 'linux/device_info_linux.cc',65 'linux/device_info_linux.h',66 'linux/video_capture_linux.cc',67 'linux/video_capture_linux.h',68 ],69 }], # linux70 ['OS=="mac"', {71 'sources': [72 'mac/qtkit/video_capture_qtkit.h',73 'mac/qtkit/video_capture_qtkit.mm',74 'mac/qtkit/video_capture_qtkit_info.h',75 'mac/qtkit/video_capture_qtkit_info.mm',76 'mac/qtkit/video_capture_qtkit_info_objc.h',77 'mac/qtkit/video_capture_qtkit_info_objc.mm',78 'mac/qtkit/video_capture_qtkit_objc.h',79 'mac/qtkit/video_capture_qtkit_objc.mm',80 'mac/qtkit/video_capture_qtkit_utility.h',81 'mac/video_capture_mac.mm',82 ],83 'link_settings': {84 'xcode_settings': {85 'OTHER_LDFLAGS': [86 '-framework Cocoa',87 '-framework CoreVideo',88 '-framework QTKit',89 ],90 },91 },92 }], # mac93 ['OS=="win"', {94 'dependencies': [95 '<(DEPTH)/third_party/winsdk_samples/winsdk_samples.gyp:directshow_baseclasses',96 ],97 'sources': [98 'windows/device_info_ds.cc',99 'windows/device_info_ds.h',100 'windows/device_info_mf.cc',101 'windows/device_info_mf.h',102 'windows/help_functions_ds.cc',103 'windows/help_functions_ds.h',104 'windows/sink_filter_ds.cc',105 'windows/sink_filter_ds.h',106 'windows/video_capture_ds.cc',107 'windows/video_capture_ds.h',108 'windows/video_capture_factory_windows.cc',109 'windows/video_capture_mf.cc',110 'windows/video_capture_mf.h',111 ],112 'link_settings': {113 'libraries': [114 '-lStrmiids.lib',115 ],116 },117 }], # win118 ['OS=="ios"', {119 'sources': [120 'ios/device_info_ios.h',121 'ios/device_info_ios.mm',122 'ios/device_info_ios_objc.h',123 'ios/device_info_ios_objc.mm',124 'ios/rtc_video_capture_ios_objc.h',125 'ios/rtc_video_capture_ios_objc.mm',126 'ios/video_capture_ios.h',127 'ios/video_capture_ios.mm',128 ],129 'xcode_settings': {130 'CLANG_ENABLE_OBJC_ARC': 'YES',131 },132 'all_dependent_settings': {133 'xcode_settings': {134 'OTHER_LDFLAGS': [135 '-framework AVFoundation',136 '-framework CoreMedia',137 '-framework CoreVideo',138 '-framework UIKit',139 ],140 },141 },142 }], # ios143 ], # conditions144 },145 ],146 }], # build_with_chromium==0147 ['include_tests==1 and OS!="android"', {148 'targets': [149 {150 'target_name': 'video_capture_tests',151 'type': '<(gtest_target_type)',152 'dependencies': [153 'video_capture_module',154 'video_capture_module_internal_impl',155 'webrtc_utility',156 '<(webrtc_root)/system_wrappers/system_wrappers.gyp:system_wrappers',157 '<(DEPTH)/testing/gtest.gyp:gtest',158 ],159 'sources': [160 'test/video_capture_unittest.cc',161 'test/video_capture_main_mac.mm',162 ],163 'conditions': [164 ['OS=="mac" or OS=="linux"', {165 'cflags': [166 '-Wno-write-strings',167 ],168 'ldflags': [169 '-lpthread -lm',170 ],171 }],172 ['OS=="linux"', {173 'libraries': [174 '-lrt',175 '-lXext',176 '-lX11',177 ],178 }],179 ['OS=="mac"', {180 'dependencies': [181 # Link with a special main for mac so we can use the webcam.182 '<(webrtc_root)/test/test.gyp:test_support_main_threaded_mac',183 ],184 'xcode_settings': {185 # TODO(andrew): CoreAudio and AudioToolbox shouldn't be needed.186 'OTHER_LDFLAGS': [187 '-framework Foundation -framework AppKit -framework Cocoa -framework OpenGL -framework CoreVideo -framework CoreAudio -framework AudioToolbox',188 ],189 },190 }], # OS=="mac"191 ['OS!="mac"', {192 'dependencies': [193 # Otherwise, use the regular main.194 '<(webrtc_root)/test/test.gyp:test_support_main',195 ],196 }], # OS!="mac"197 ] # conditions198 },199 ], # targets200 }],201 ],...

Full Screen

Full Screen

test_call_policies.py

Source:test_call_policies.py Github

copy

Full Screen

1import pytest2from pybind11_tests import call_policies as m3from pybind11_tests import ConstructorStats4def test_keep_alive_argument(capture):5 n_inst = ConstructorStats.detail_reg_inst()6 with capture:7 p = m.Parent()8 assert capture == "Allocating parent."9 with capture:10 p.addChild(m.Child())11 assert ConstructorStats.detail_reg_inst() == n_inst + 112 assert capture == """13 Allocating child.14 Releasing child.15 """16 with capture:17 del p18 assert ConstructorStats.detail_reg_inst() == n_inst19 assert capture == "Releasing parent."20 with capture:21 p = m.Parent()22 assert capture == "Allocating parent."23 with capture:24 p.addChildKeepAlive(m.Child())25 assert ConstructorStats.detail_reg_inst() == n_inst + 226 assert capture == "Allocating child."27 with capture:28 del p29 assert ConstructorStats.detail_reg_inst() == n_inst30 assert capture == """31 Releasing parent.32 Releasing child.33 """34def test_keep_alive_return_value(capture):35 n_inst = ConstructorStats.detail_reg_inst()36 with capture:37 p = m.Parent()38 assert capture == "Allocating parent."39 with capture:40 p.returnChild()41 assert ConstructorStats.detail_reg_inst() == n_inst + 142 assert capture == """43 Allocating child.44 Releasing child.45 """46 with capture:47 del p48 assert ConstructorStats.detail_reg_inst() == n_inst49 assert capture == "Releasing parent."50 with capture:51 p = m.Parent()52 assert capture == "Allocating parent."53 with capture:54 p.returnChildKeepAlive()55 assert ConstructorStats.detail_reg_inst() == n_inst + 256 assert capture == "Allocating child."57 with capture:58 del p59 assert ConstructorStats.detail_reg_inst() == n_inst60 assert capture == """61 Releasing parent.62 Releasing child.63 """64# https://bitbucket.org/pypy/pypy/issues/244765@pytest.unsupported_on_pypy66def test_alive_gc(capture):67 n_inst = ConstructorStats.detail_reg_inst()68 p = m.ParentGC()69 p.addChildKeepAlive(m.Child())70 assert ConstructorStats.detail_reg_inst() == n_inst + 271 lst = [p]72 lst.append(lst) # creates a circular reference73 with capture:74 del p, lst75 assert ConstructorStats.detail_reg_inst() == n_inst76 assert capture == """77 Releasing parent.78 Releasing child.79 """80def test_alive_gc_derived(capture):81 class Derived(m.Parent):82 pass83 n_inst = ConstructorStats.detail_reg_inst()84 p = Derived()85 p.addChildKeepAlive(m.Child())86 assert ConstructorStats.detail_reg_inst() == n_inst + 287 lst = [p]88 lst.append(lst) # creates a circular reference89 with capture:90 del p, lst91 assert ConstructorStats.detail_reg_inst() == n_inst92 assert capture == """93 Releasing parent.94 Releasing child.95 """96def test_alive_gc_multi_derived(capture):97 class Derived(m.Parent, m.Child):98 def __init__(self):99 m.Parent.__init__(self)100 m.Child.__init__(self)101 n_inst = ConstructorStats.detail_reg_inst()102 p = Derived()103 p.addChildKeepAlive(m.Child())104 # +3 rather than +2 because Derived corresponds to two registered instances105 assert ConstructorStats.detail_reg_inst() == n_inst + 3106 lst = [p]107 lst.append(lst) # creates a circular reference108 with capture:109 del p, lst110 assert ConstructorStats.detail_reg_inst() == n_inst111 assert capture == """112 Releasing parent.113 Releasing child.114 Releasing child.115 """116def test_return_none(capture):117 n_inst = ConstructorStats.detail_reg_inst()118 with capture:119 p = m.Parent()120 assert capture == "Allocating parent."121 with capture:122 p.returnNullChildKeepAliveChild()123 assert ConstructorStats.detail_reg_inst() == n_inst + 1124 assert capture == ""125 with capture:126 del p127 assert ConstructorStats.detail_reg_inst() == n_inst128 assert capture == "Releasing parent."129 with capture:130 p = m.Parent()131 assert capture == "Allocating parent."132 with capture:133 p.returnNullChildKeepAliveParent()134 assert ConstructorStats.detail_reg_inst() == n_inst + 1135 assert capture == ""136 with capture:137 del p138 assert ConstructorStats.detail_reg_inst() == n_inst139 assert capture == "Releasing parent."140def test_keep_alive_constructor(capture):141 n_inst = ConstructorStats.detail_reg_inst()142 with capture:143 p = m.Parent(m.Child())144 assert ConstructorStats.detail_reg_inst() == n_inst + 2145 assert capture == """146 Allocating child.147 Allocating parent.148 """149 with capture:150 del p151 assert ConstructorStats.detail_reg_inst() == n_inst152 assert capture == """153 Releasing parent.154 Releasing child.155 """156def test_call_guard():157 assert m.unguarded_call() == "unguarded"158 assert m.guarded_call() == "guarded"159 assert m.multiple_guards_correct_order() == "guarded & guarded"160 assert m.multiple_guards_wrong_order() == "unguarded & guarded"161 if hasattr(m, "with_gil"):162 assert m.with_gil() == "GIL held"...

Full Screen

Full Screen

Page_PreferencesCapture.py

Source:Page_PreferencesCapture.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2# vim: expandtab ts=4 sw=4 sts=4:3#4# Copyright (C) 2007-2010 GNS3 Development Team (http://www.gns3.net/team).5#6# This program is free software; you can redistribute it and/or modify7# it under the terms of the GNU General Public License version 2 as8# published by the Free Software Foundation;9#10# This program is distributed in the hope that it will be useful,11# but WITHOUT ANY WARRANTY; without even the implied warranty of12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the13# GNU General Public License for more details.14#15# You should have received a copy of the GNU General Public License16# along with this program; if not, write to the Free Software17# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA18#19# http://www.gns3.net/contact20#21import sys, os22import GNS3.Globals as globals23from PyQt4 import QtGui, QtCore24from GNS3.Ui.ConfigurationPages.Form_PreferencesCapture import Ui_PreferencesCapture25from GNS3.Config.Objects import systemCaptureConf26from GNS3.Utils import fileBrowser, translate, testIfWritableDir27from GNS3.Config.Defaults import CAPTURE_PRESET_CMDS, CAPTURE_DEFAULT_CMD, CAPTURE_DEFAULT_WORKDIR28from GNS3.Config.Config import ConfDB29class UiConfig_PreferencesCapture(QtGui.QWidget, Ui_PreferencesCapture):30 def __init__(self):31 QtGui.QWidget.__init__(self)32 Ui_PreferencesCapture.setupUi(self, self)33 self.connect(self.CaptureWorkingDirectory_Browser, QtCore.SIGNAL('clicked()'), self.__setCaptureWorkdir)34 self.connect(self.pushButtonUsePresets, QtCore.SIGNAL('clicked()'), self.__setPresetsCmd)35 36 # TODO: implement named pipe method: http://wiki.wireshark.org/CaptureSetup/Pipes#Named_pipes37 for (name, cmd) in sorted(CAPTURE_PRESET_CMDS.iteritems()):38 self.comboBoxPresets.addItem(name, cmd)39 self.loadConf()40 def __setPresetsCmd(self):41 42 #self.CaptureCommand.clear()43 command = self.comboBoxPresets.itemData(self.comboBoxPresets.currentIndex(), QtCore.Qt.UserRole).toString()44 self.CaptureCommand.setText(command)45 def loadConf(self):46 # Use conf from GApp.systconf['capture'] it it exist,47 # else get a default config48 if globals.GApp.systconf.has_key('capture'):49 self.conf = globals.GApp.systconf['capture']50 else:51 self.conf = systemCaptureConf()52 # Set default capture command53 if self.conf.cap_cmd == '':54 self.conf.cap_cmd = CAPTURE_DEFAULT_CMD55 if self.conf.workdir == '':56 self.conf.workdir = CAPTURE_DEFAULT_WORKDIR57 # Push default values to GUI58 self.CaptureWorkingDirectory.setText(os.path.normpath(self.conf.workdir))59 self.CaptureCommand.setText(self.conf.cap_cmd)60 if self.conf.auto_start == True:61 self.checkBoxStartCaptureCommand.setCheckState(QtCore.Qt.Checked)62 else:63 self.checkBoxStartCaptureCommand.setCheckState(QtCore.Qt.Unchecked)64 def saveConf(self):65 self.conf.workdir = unicode(self.CaptureWorkingDirectory.text(), 'utf-8', errors='replace')66 self.conf.cap_cmd = unicode(self.CaptureCommand.text(), 'utf-8', errors='replace')67 if self.checkBoxStartCaptureCommand.checkState() == QtCore.Qt.Checked:68 self.conf.auto_start = True69 else:70 self.conf.auto_start = False71 globals.GApp.systconf['capture'] = self.conf72 ConfDB().sync()73 return True74 def __setCaptureWorkdir(self):75 """ Open a file dialog for choosing the location of local hypervisor76 working directory77 """78 79 capture_default_working_directory = '.'80 if os.environ.has_key("TEMP"):81 capture_default_working_directory = os.environ["TEMP"]82 elif os.environ.has_key("TMP"):83 capture_default_working_directory = os.environ["TMP"]84 elif os.path.exists('/tmp'):85 capture_default_working_directory = unicode('/tmp')86 fb = fileBrowser(translate('UiConfig_PreferencesCapture', 'Local capture working directory'), directory=capture_default_working_directory, parent=globals.preferencesWindow)87 path = fb.getDir()88 if path:89 path = os.path.normpath(path)90 self.CaptureWorkingDirectory.setText(path)91 92 if sys.platform.startswith('win'):93 try:94 path.encode('ascii')95 except:96 QtGui.QMessageBox.warning(globals.preferencesWindow, translate("Page_PreferencesCapture", "Capture directory"), translate("Page_PreferencesCapture", "The path you have selected should contains only ascii (English) characters. Dynamips (Cygwin DLL) doesn't support unicode on Windows!"))97 if not testIfWritableDir(path):...

Full Screen

Full Screen

SnifferSanityTest.py

Source:SnifferSanityTest.py Github

copy

Full Screen

...29 """30 index = 031 for sniffer in self.sniffers:32 for channel in self._channels:33 with sniffer.start_capture(34 override_configs={Sniffer.CONFIG_KEY_CHANNEL: channel},35 duration=self._capture_sec,36 packet_count=self._packet_count):37 self.log.info("Capture: %s", sniffer.get_capture_file())38 def test_sniffer_validation_manual(self):39 """Validate sniffer configuration & capture API using a manual/raw40 API mechanism.41 The standard process should use a with clause. This demonstrates the42 manual process which uses an explicit wait_for_capture() call.43 Alternatively, could also use a sleep() + stop_capture() process44 (though that mechanism won't terminate early if the capture is done).45 """46 index = 047 for sniffer in self.sniffers:48 for channel in self._channels:49 sniffer.start_capture(50 override_configs={Sniffer.CONFIG_KEY_CHANNEL: channel},51 packet_count=self._packet_count)52 self.log.info("Capture: %s", sniffer.get_capture_file())53 sniffer.wait_for_capture(timeout=self._capture_sec)54 def test_sniffer_validation_capture_3_beacons(self):55 """Demonstrate the use of additional configuration.56 """57 index = 058 for sniffer in self.sniffers:59 for channel in self._channels:60 with sniffer.start_capture(61 override_configs={Sniffer.CONFIG_KEY_CHANNEL: channel},62 duration=self._capture_sec,63 packet_count=3,64 additional_args=self._filter[sniffer.get_subtype()]):...

Full Screen

Full Screen

capture_pointcloud_server.py

Source:capture_pointcloud_server.py Github

copy

Full Screen

1#!/usr/bin/env python2from binpicking_msgs.srv import CapturePointcloud, CapturePointcloudRequest, CapturePointcloudResponse3import rospy4import copy5import numpy as np6import tf2_ros7import geometry_msgs.msg8import tf_conversions9from sensor_msgs import point_cloud210from sensor_msgs.msg import PointCloud211pcl_publisher = 012capture = 013tfBuffer = 014listener = 015pcl_publisher = 016broadcaster = 017transform_capture = 018def capture_cb(request):19 rospy.loginfo('capturing')20 global capture21 capture = copy.deepcopy(request)22 capture.header.frame_id = 'camera_depth_optical_frame_capture'23 transform = tfBuffer.lookup_transform("base_link", "camera_depth_optical_frame", rospy.Time())#now)24# print(trans)25 global transform_capture26 transform_capture = copy.deepcopy(transform)27 transform_capture.header.stamp = rospy.Time.now()28 transform_capture.header.frame_id = "base_link"29 transform_capture.child_frame_id = "camera_depth_optical_frame_capture"30 pcl_publisher.publish(capture)31 broadcaster.sendTransform(transform_capture)32# Service callback function.33def process_service_request(req):34 # Instantiate the response message object.35 res = CapturePointcloudResponse()36 res.success = False37 rospy.loginfo('Capture pointcloud')38 sb = rospy.Subscriber('/camera/depth/color/points', PointCloud2, capture_cb)39 rospy.wait_for_message('/camera/depth/color/points', PointCloud2)40 sb.unregister()41 #Return the response message.42 global transform_capture43 global capture44 res.pointcloud = capture45# res.camera_pose.position = transform_capture.transform.translation46# res.camera_pose.orientation = transform_capture.transform.rotation47 res.success = True48 return res49def capture_pointcloud_server():50 # ROS node for the service server.51 rospy.init_node('capture_pointcloud_server', anonymous = False)52 global tfBuffer53 tfBuffer = tf2_ros.Buffer()54 global listener55 listener = tf2_ros.TransformListener(tfBuffer)56 global pcl_publisher57 pcl_publisher = rospy.Publisher('/camera/depth/color/capture', PointCloud2, queue_size = 10)58 global broadcaster59 broadcaster = tf2_ros.StaticTransformBroadcaster()60 # Create a ROS service type.61 service = rospy.Service('capture_pointcloud', CapturePointcloud, process_service_request)62 # Log message about service availability.63 rospy.loginfo('Capture pointcluod service is now available.')64 rospy.spin()65if __name__ == "__main__":...

Full Screen

Full Screen

test_keep_alive.py

Source:test_keep_alive.py Github

copy

Full Screen

1import pytest2def test_keep_alive_argument(capture):3 from pybind11_tests import Parent, Child4 with capture:5 p = Parent()6 assert capture == "Allocating parent."7 with capture:8 p.addChild(Child())9 pytest.gc_collect()10 assert capture == """11 Allocating child.12 Releasing child.13 """14 with capture:15 del p16 pytest.gc_collect()17 assert capture == "Releasing parent."18 with capture:19 p = Parent()20 assert capture == "Allocating parent."21 with capture:22 p.addChildKeepAlive(Child())23 pytest.gc_collect()24 assert capture == "Allocating child."25 with capture:26 del p27 pytest.gc_collect()28 assert capture == """29 Releasing parent.30 Releasing child.31 """32def test_keep_alive_return_value(capture):33 from pybind11_tests import Parent34 with capture:35 p = Parent()36 assert capture == "Allocating parent."37 with capture:38 p.returnChild()39 pytest.gc_collect()40 assert capture == """41 Allocating child.42 Releasing child.43 """44 with capture:45 del p46 pytest.gc_collect()47 assert capture == "Releasing parent."48 with capture:49 p = Parent()50 assert capture == "Allocating parent."51 with capture:52 p.returnChildKeepAlive()53 pytest.gc_collect()54 assert capture == "Allocating child."55 with capture:56 del p57 pytest.gc_collect()58 assert capture == """59 Releasing parent.60 Releasing child.61 """62def test_return_none(capture):63 from pybind11_tests import Parent64 with capture:65 p = Parent()66 assert capture == "Allocating parent."67 with capture:68 p.returnNullChildKeepAliveChild()69 pytest.gc_collect()70 assert capture == ""71 with capture:72 del p73 pytest.gc_collect()74 assert capture == "Releasing parent."75 with capture:76 p = Parent()77 assert capture == "Allocating parent."78 with capture:79 p.returnNullChildKeepAliveParent()80 pytest.gc_collect()81 assert capture == ""82 with capture:83 del p84 pytest.gc_collect()...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { capture } = require('differencify');2const { Builder, By } = require('selenium-webdriver');3const chrome = require('selenium-webdriver/chrome');4const path = require('chromedriver').path;5const options = new chrome.Options();6options.addArguments('headless');7options.addArguments('disable-gpu');8options.addArguments('window-size=1920x1080');9options.addArguments('no-sandbox');10options.addArguments('disable-dev-shm-usage');11const driver = new Builder()12 .forBrowser('chrome')13 .setChromeOptions(options)14 .build();15const viewport = { width: 1920, height: 1080 };16(async function example() {17 await driver.get(url);18 await driver.findElement(By.name('q')).sendKeys('webdriver');19 await driver.findElement(By.name('btnK')).click();20 await driver.wait(() => driver.getTitle().then(title => title.endsWith('webdriver - Google Search')));21 await driver.sleep(1000);22 const image = await capture(driver, viewport);23 await driver.quit();24})();25const { expect } = require('chai');26const { compare } = require('differencify');27describe('Google', () => {28 it('should look the same', async () => {29 const result = await compare('test.js');30 expect(result.isSameDimensions).to.be.true;31 expect(result.misMatchPercentage).to.be.lessThan(0.1);32 });33});

Full Screen

Using AI Code Generation

copy

Full Screen

1const differencify = require('differencify');2const differencifyConfig = require('./differencify.conf.js');3const differencifyInstance = differencify.init(differencifyConfig);4describe('Google Search', function() {5 it('should display "Google" text on page', async function() {6 const image = await differencifyInstance.capture('google');7 await expect(image).to.matchImage('google');8 });9});10module.exports = {11 viewport: {12 },13};

Full Screen

Using AI Code Generation

copy

Full Screen

1const differencify = require('differencify');2const { expect } = require('chai');3describe('test', () => {4 it('should match', async () => {5 const { capture } = await differencify.init();6 expect(image).to.matchImage('google');7 });8});9const chai = require('chai');10const chaiImage = require('chai-image');11chai.use(chaiImage);12describe('test', () => {13 it('should match', async () => {14 const image = await page.screenshot();15 chai.expect(image).to.matchImage('google');16 });17});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { capture } = require('differencify')2const { expect } = require('chai')3const puppeteer = require('puppeteer')4describe('Test page', () => {5 before(async () => {6 browser = await puppeteer.launch()7 page = await browser.newPage()8 })9 after(async () => {10 await browser.close()11 })12 it('should match', async () => {13 const image = await capture(page)14 expect(image).to.matchImageSnapshot()15 })16})17{18 "scripts": {19 },20 "dependencies": {21 }22}23module.exports = {24 reporterOptions: {25 },26}27module.exports = {28 reporterOptions: {29 },30}31module.exports = {32 reporterOptions: {33 },34}35module.exports = {

Full Screen

Using AI Code Generation

copy

Full Screen

1const { capture } = require('differencify');2const { expect } = require('chai');3describe('homepage', function() {4 it('should look the same', async function() {5 await capture(this.test);6 });7});8{9 "scripts": {10 },11 "devDependencies": {12 }13}14✓ homepage should look the same (166ms)151 passing (1s)16 at Context.capture (node_modules/differencify/src/capture.js:48:13)17 at process._tickCallback (internal/process/next_tick.js:68:7)18const { getDiff } = require('differencify');19const diff = await getDiff({20});21const { getDiffPercentage } = require('differencify');22const diffPercentage = await getDiffPercentage({

Full Screen

Using AI Code Generation

copy

Full Screen

1const { capture } = require('differencify')2describe('sample test', () => {3 it('should pass', async () => {4 })5})6{7 "scripts": {8 },9 "devDependencies": {10 }11}12module.exports = {13}

Full Screen

Using AI Code Generation

copy

Full Screen

1const differencify = require('differencify');2const differencifyConfig = {3};4const differencifyInstance = differencify.init(differencifyConfig);5describe('test', () => {6 it('should be equal', async () => {7 const page = await browser.newPage();8 await page.waitFor(1000);9 await differencifyInstance.capture(page, 'google');10 await page.close();11 });12});13{14 "scripts": {15 },16 "dependencies": {17 },18 "devDependencies": {19 }20}21module.exports = {22};23const { setDefaultOptions } = require('expect-puppeteer');24setDefaultOptions({ timeout: 6000 });25const puppeteer = require('puppeteer');26let browser;27beforeAll(async () => {28 browser = await puppeteer.launch({ headless: false });29});30afterAll(async () => {31 await browser.close();32});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { capture } = require('differencify');2test('test', async () => {3 await capture(page, 'test', { threshold: 0.1 });4});5module.exports = {6};

Full Screen

Using AI Code Generation

copy

Full Screen

1const differencify = require('differencify');2const { get } = require('request-promise');3const config = {4 customDiffConfig: { threshold: 0.1 },5};6const init = async () => {7 const browser = await differencify.launch({ headless: false, slowMo: 1000 });8 const page = await browser.newPage();9 await page.setViewport({ width: 1280, height: 800 });10 await page.waitForSelector('input[name="q"]');11 await page.type('input[name="q"]', 'google');12 await page.waitForSelector('input[name="btnK"]');13 await page.click('input[name="btnK"]');14 await page.waitForSelector('#result-stats');15 await page.waitFor(5000);16 await page.differencify.screenshot('google');17 await page.waitFor(5000);18 await browser.close();19};20init();21{

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run differencify automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful