code
stringlengths
1
1.72M
language
stringclasses
1 value
import gtk import gobject from pychess.System.prefix import addDataPrefix from __init__ import CENTER from __init__ import DockComposite, DockLeaf, TopDock from PyDockComposite import PyDockComposite from StarArrowButton import StarArrowButton from HighlightArea import HighlightArea class PyDockLeaf (DockLeaf): def __init__ (self, widget, title, id): DockLeaf.__init__(self) self.set_no_show_all(True) self.book = gtk.Notebook() self.book.connect("drag-begin", self.__onDragBegin) self.book.connect("drag-end", self.__onDragEnd) self.book.connect_after("switch-page", self.__onPageSwitched) self.add(self.book) self.book.show() self.book.props.tab_vborder = 0 self.book.props.tab_hborder = 1 self.highlightArea = HighlightArea(self) #self.put(self.highlightArea, 0, 0) self.starButton = StarArrowButton(self, addDataPrefix("glade/dock_top.svg"), addDataPrefix("glade/dock_right.svg"), addDataPrefix("glade/dock_bottom.svg"), addDataPrefix("glade/dock_left.svg"), addDataPrefix("glade/dock_center.svg"), addDataPrefix("glade/dock_star.svg")) #self.put(self.starButton, 0, 0) self.starButton.connect("dropped", self.__onDrop) self.starButton.connect("hovered", self.__onHover) self.starButton.connect("left", self.__onLeave) self.dockable = True self.panels = [] self.zoomPointer = gtk.Label() self.realtop = None self.zoomed = False #assert isinstance(widget, gtk.Notebook) self.__add(widget, title, id) def __repr__ (self): s = DockLeaf.__repr__(self) panels = [] for widget, title, id in self.getPanels(): panels.append(id) return s + " (" + ", ".join(panels) + ")" def __add (self, widget, title, id): #widget = BorderBox(widget, top=True) self.panels.append((widget, title, id)) self.book.append_page(widget, title) self.book.set_tab_label_packing(widget, True, True, gtk.PACK_START) self.book.set_tab_detachable(widget, True) self.book.set_tab_reorderable(widget, True) widget.show_all() def dock (self, widget, position, title, id): """ if position == CENTER: Add a new widget to the leaf-notebook if position != CENTER: Fork this leaf into two """ if position == CENTER: self.__add(widget, title, id) return self else: parent = self.get_parent() while not isinstance(parent, DockComposite): parent = parent.get_parent() leaf = PyDockLeaf(widget, title, id) new = PyDockComposite(position) parent.changeComponent(self, new) new.initChildren(self, leaf) new.show_all() return leaf def undock (self, widget): """ remove the widget from the leaf-notebook if this was the only widget, remove this leaf from its owner """ for i, (widget_, title, id) in enumerate(self.panels): if widget_ == widget: break else: raise KeyError, "No %s in %s" % (widget, self) del self.panels[i] self.book.remove_page(self.book.page_num(widget)) if self.book.get_n_pages() == 0: def cb (): parent = self.get_parent() while not isinstance(parent, DockComposite): parent = parent.get_parent() parent.removeComponent(self) self.__del__() # We need to idle_add this, as the widget won't emit drag-ended, if # it is removed to early gobject.idle_add(cb) return title, id def zoomUp (self): if self.zoomed: return parent = self.get_parent() if not isinstance(parent, TopDock): while not isinstance(parent, DockComposite): parent = parent.get_parent() parent.changeComponent(self, self.zoomPointer) while not isinstance(parent, TopDock): parent = parent.get_parent() self.realtop = parent.getComponents()[0] parent.changeComponent(self.realtop, self) self.zoomed = True self.book.set_show_border(False) def zoomDown (self): if not self.zoomed: return if self.zoomPointer.get_parent(): top_parent = self.get_parent() old_parent = self.zoomPointer.get_parent() while not isinstance(old_parent, DockComposite): old_parent = old_parent.get_parent() top_parent.changeComponent(self, self.realtop) old_parent.changeComponent(self.zoomPointer, self) self.realtop = None self.zoomed = False self.book.set_show_border(True) def getPanels(self): return self.panels def getCurrentPanel (self): for i, (widget, title, id) in enumerate(self.panels): if i == self.book.get_current_page(): return id def setCurrentPanel (self, id): for i, (widget, title, id_) in enumerate(self.panels): if id == id_: self.book.set_current_page(i) break def isDockable (self): return self.dockable def setDockable (self, dockable): self.book.set_show_tabs(dockable) #self.book.set_show_border(dockable) self.dockable = dockable def showArrows (self): if self.dockable: self.starButton._calcSize() self.starButton.show() def hideArrows (self): self.starButton.hide() self.highlightArea.hide() def __onDragBegin (self, widget, context): for instance in self.getInstances(): instance.showArrows() def __onDragEnd (self, widget, context): for instance in self.getInstances(): instance.hideArrows() def __onDrop (self, starButton, position, sender): self.highlightArea.hide() if self.dockable: if sender.get_parent() == self and self.book.get_n_pages() == 1: return child = sender.get_nth_page(sender.get_current_page()) title, id = sender.get_parent().undock(child) self.dock(child, position, title, id) def __onHover (self, starButton, position, widget): if self.dockable: self.highlightArea.showAt(position) starButton.window.raise_() def __onLeave (self, starButton): self.highlightArea.hide() def __onPageSwitched (self, book, page, page_num): # When a tab is dragged over another tab, the page is temporally # switched, and the notebook child is hovered. Thus we need to reraise # our star if self.starButton.window: self.starButton.window.raise_()
Python
import gtk #=============================================================================== # Composite Constants #=============================================================================== POSITIONS_COUNT = 5 NORTH, EAST, SOUTH, WEST, CENTER = range(POSITIONS_COUNT) #=============================================================================== # Composite Interfaces #=============================================================================== class DockComponent (object): def dock (self, widget, position, title, id): raise NotImplementedError class TabReceiver (gtk.Alignment): __instances = [] def __init__ (self): gtk.Alignment.__init__(self,1,1,1,1) self.__instances.append(self) def __del__ (self): try: index = TabReceiver.__instances.index(self) except ValueError: return del TabReceiver.__instances[index] def getInstances (self): return iter(self.__instances) def showArrows (self): raise NotImplementedError def hideArrows (self): raise NotImplementedError class DockComposite (DockComponent): def __del__ (self): for component in self.getComponents(): component.__del__() def changeComponent (self, old, new): raise NotImplementedError def removeComponent (self, component): raise NotImplementedError def getComponents (self): raise NotImplementedError def getPosition (self): """ Returns NORTH or SOUTH if the children are packed vertically. Returns WEST or EAST if the children are packed horizontally. Returns CENTER if there is only one child """ raise NotImplementedError class DockLeaf (DockComponent, TabReceiver): def __del__ (self): TabReceiver.__del__(self) def undock (self, widget): """ Removes the widget from the leaf, and if it is the only widget, it removes the leaf as well. Returns (title, id) of the widget """ raise NotImplementedError def getPanels (self): """ Returns a list of (widget, title, id) tuples """ raise NotImplementedError def getCurrentPanel (self): """ Returns the panel id currently shown """ raise NotImplementedError def setCurrentPanel (self, id): raise NotImplementedError def setDockable (self, dockable): """ If the leaf is not dockable it won't be moveable and won't accept new panels """ raise NotImplementedError def isDockable (self): raise NotImplementedError class TopDock (DockComposite, TabReceiver): def __init__ (self, id): TabReceiver.__init__(self) self.__id = id def __del__ (self): TabReceiver.__del__(self) DockComposite.__del__(self) def getPosition (self): return CENTER def saveToXML (self, xmlpath): """ <docks> <dock id="x"> <v pos="200"> <leaf current="x" dockable="False"> <panel id="x" /> </leaf> <h pos="200"> <leaf current="y" dockable="True"> <panel id="y" /> <panel id="z" /> </leaf> <leaf current="y" dockable="True"> <panel id="y" /> </leaf> </h> </v> </dock> </docks> """ raise NotImplementedError def loadFromXML (self, xmlpath, idToWidget): """ idTowidget is a dictionary {id: (widget,title)} asserts that self.id is in the xmlfile """ raise NotImplementedError def getId(self): return self.__id id = property(getId, None, None, None)
Python
import gtk, cairo import gobject from OverlayWindow import OverlayWindow from __init__ import NORTH, EAST, SOUTH, WEST class ArrowButton (OverlayWindow): """ Leafs will connect to the drag-drop signal """ __gsignals__ = { 'dropped' : (gobject.SIGNAL_RUN_FIRST, None, (object,)), 'hovered' : (gobject.SIGNAL_RUN_FIRST, None, (object,)), 'left' : (gobject.SIGNAL_RUN_FIRST, None, ()), } def __init__ (self, parent, svgPath, position): OverlayWindow.__init__(self, parent) self.myparent = parent self.myposition = position self.svgPath = svgPath self.connect_after("expose-event", self.__onExposeEvent) targets = [("GTK_NOTEBOOK_TAB", gtk.TARGET_SAME_APP, 0xbadbeef)] self.drag_dest_set(gtk.DEST_DEFAULT_DROP | gtk.DEST_DEFAULT_MOTION, targets, gtk.gdk.ACTION_MOVE) self.drag_dest_set_track_motion(True) self.connect("drag-motion", self.__onDragMotion) self.connect("drag-leave", self.__onDragLeave) self.connect("drag-drop", self.__onDragDrop) self.hovered = False self.myparentAlloc = None self.myparentPos = None self.hasHole = False def _calcSize (self): parentAlloc = self.myparent.get_allocation() width, height = self.getSizeOfSvg(self.svgPath) if self.myparentAlloc == None: self.resize(width, height) if self.window and not self.hasHole: self.hasHole = True self.digAHole(self.svgPath, width, height) if self.myposition == NORTH: x, y = parentAlloc.width/2.-width/2., 0 elif self.myposition == EAST: x, y = parentAlloc.width-width, parentAlloc.height/2.-height/2. elif self.myposition == SOUTH: x, y = parentAlloc.width/2.-width/2., parentAlloc.height-height elif self.myposition == WEST: x, y = 0, parentAlloc.height/2.-height/2. x, y = self.translateCoords(int(x), int(y)) if (x,y) != self.get_position(): self.move(x, y) self.myparentAlloc = parentAlloc self.myparentPos = self.myparent.window.get_position() def __onExposeEvent (self, self_, event): self._calcSize() context = self.window.cairo_create() width, height = self.getSizeOfSvg(self.svgPath) surface = self.getSurfaceFromSvg(self.svgPath, width, height) if self.is_composited(): context.set_operator(cairo.OPERATOR_CLEAR) context.set_source_rgba(0.0,0.0,0.0,0.0) context.paint() context.set_operator(cairo.OPERATOR_OVER) mask = gtk.gdk.Pixmap(None, width, height, 1) mcontext = mask.cairo_create() mcontext.set_source_surface(surface, 0, 0) mcontext.paint() self.window.shape_combine_mask(mask, 0, 0) context.set_source_surface(surface, 0, 0) context.paint() def __containsPoint (self, x, y): alloc = self.get_allocation() return 0 <= x < alloc.width and 0 <= y < alloc.height def __onDragMotion (self, arrow, context, x, y, timestamp): if not self.hovered and self.__containsPoint(x,y): self.hovered = True self.emit("hovered", context.get_source_widget()) elif self.hovered and not self.__containsPoint(x,y): self.hovered = False self.emit("left") def __onDragLeave (self, arrow, context, timestamp): if self.hovered: self.hovered = False self.emit("left") def __onDragDrop (self, arrow, context, x, y, timestamp): if self.__containsPoint(x,y): self.emit("dropped", context.get_source_widget()) context.finish(True, True, timestamp) return True
Python
import os from xml.dom import minidom import gtk import gobject from pychess.System.prefix import addDataPrefix from PyDockLeaf import PyDockLeaf from PyDockComposite import PyDockComposite from ArrowButton import ArrowButton from HighlightArea import HighlightArea from __init__ import TopDock, DockLeaf, DockComponent, DockComposite from __init__ import NORTH, EAST, SOUTH, WEST, CENTER class PyDockTop (TopDock): def __init__ (self, id): TopDock.__init__(self, id) self.set_no_show_all(True) self.highlightArea = HighlightArea(self) self.buttons = (ArrowButton(self, addDataPrefix("glade/dock_top.svg"), NORTH), ArrowButton(self, addDataPrefix("glade/dock_right.svg"), EAST), ArrowButton(self, addDataPrefix("glade/dock_bottom.svg"), SOUTH), ArrowButton(self, addDataPrefix("glade/dock_left.svg"), WEST)) for button in self.buttons: button.connect("dropped", self.__onDrop) button.connect("hovered", self.__onHover) button.connect("left", self.__onLeave) def __del__ (self): TopDock.__del__(self) #=========================================================================== # Component stuff #=========================================================================== def addComponent (self, widget): self.add(widget) widget.show() def changeComponent (self, old, new): self.removeComponent(old) self.addComponent(new) def removeComponent (self, widget): self.remove(widget) def getComponents (self): if isinstance(self.child, DockComponent): return [self.child] return [] def dock (self, widget, position, title, id): if not self.getComponents(): leaf = PyDockLeaf(widget, title, id) self.addComponent(leaf) return leaf else: return self.child.dock(widget, position, title, id) def clear (self): self.remove(self.child) #=========================================================================== # Signals #=========================================================================== def showArrows (self): for button in self.buttons: button._calcSize() button.show() def hideArrows (self): for button in self.buttons: button.hide() self.highlightArea.hide() def __onDrop (self, arrowButton, sender): self.highlightArea.hide() child = sender.get_nth_page(sender.get_current_page()) title, id = sender.get_parent().undock(child) self.dock(child, arrowButton.myposition, title, id) def __onHover (self, arrowButton, widget): self.highlightArea.showAt(arrowButton.myposition) arrowButton.window.raise_() def __onLeave (self, arrowButton): self.highlightArea.hide() #=========================================================================== # XML #=========================================================================== def saveToXML (self, xmlpath): dockElem = None if os.path.isfile(xmlpath): doc = minidom.parse(xmlpath) for elem in doc.getElementsByTagName("dock"): if elem.getAttribute("id") == self.id: for node in elem.childNodes: elem.removeChild(node) dockElem = elem break if not dockElem: doc = minidom.getDOMImplementation().createDocument(None, "docks", None) dockElem = doc.createElement("dock") dockElem.setAttribute("id", self.id) doc.documentElement.appendChild(dockElem) if self.child: self.__addToXML(self.child, dockElem, doc) f = file(xmlpath, "w") doc.writexml(f) f.close() doc.unlink() def __addToXML (self, component, parentElement, document): if isinstance(component, DockComposite): pos = component.paned.get_position() if component.getPosition() in (NORTH, SOUTH): childElement = document.createElement("v") size = float(component.get_allocation().height) else: childElement = document.createElement("h") size = float(component.get_allocation().width) childElement.setAttribute("pos", str(pos/max(size,pos))) self.__addToXML(component.getComponents()[0], childElement, document) self.__addToXML(component.getComponents()[1], childElement, document) elif isinstance(component, DockLeaf): childElement = document.createElement("leaf") childElement.setAttribute("current", component.getCurrentPanel()) childElement.setAttribute("dockable", str(component.isDockable())) for panel, title, id in component.getPanels(): e = document.createElement("panel") e.setAttribute("id", id) childElement.appendChild(e) parentElement.appendChild(childElement) def loadFromXML (self, xmlpath, idToWidget): doc = minidom.parse(xmlpath) for elem in doc.getElementsByTagName("dock"): if elem.getAttribute("id") == self.id: break else: raise AttributeError, \ "XML file contains no <dock> elements with id '%s'" % self.id child = [n for n in elem.childNodes if isinstance(n, minidom.Element)] if child: self.addComponent(self.__createWidgetFromXML(child[0], idToWidget)) def __createWidgetFromXML (self, parentElement, idToWidget): children = [n for n in parentElement.childNodes if isinstance(n, minidom.Element)] if parentElement.tagName in ("h", "v"): child1, child2 = children if parentElement.tagName == "h": new = PyDockComposite(EAST) else: new = PyDockComposite(SOUTH) new.initChildren(self.__createWidgetFromXML(child1, idToWidget), self.__createWidgetFromXML(child2, idToWidget)) def cb (widget, event, pos): allocation = widget.get_allocation() if parentElement.tagName == "h": widget.set_position(int(allocation.width * pos)) else: widget.set_position(int(allocation.height * pos)) widget.disconnect(conid) conid = new.paned.connect("expose-event", cb, float(parentElement.getAttribute("pos"))) return new elif parentElement.tagName == "leaf": id = children[0].getAttribute("id") title, widget = idToWidget[id] leaf = PyDockLeaf(widget, title, id) for panelElement in children[1:]: id = panelElement.getAttribute("id") title, widget = idToWidget[id] leaf.dock(widget, CENTER, title, id) leaf.setCurrentPanel(parentElement.getAttribute("current")) if parentElement.getAttribute("dockable").lower() == "false": leaf.setDockable(False) return leaf
Python
import sys import gtk from __init__ import DockComposite from __init__ import NORTH, EAST, SOUTH, WEST, CENTER class PyDockComposite (gtk.Alignment, DockComposite): def __init__ (self, position): gtk.Alignment.__init__(self, xscale=1, yscale=1) if position == NORTH or position == SOUTH: paned = gtk.VPaned() elif position == EAST or position == WEST: paned = gtk.HPaned() self.position = position self.paned = paned self.add(self.paned) self.paned.show() def dock (self, widget, position, title, id): assert position != CENTER, "POSITION_CENTER only makes sense for leaves" parent = self.get_parent() while not isinstance(parent, DockComposite): parent = parent.get_parent() from PyDockLeaf import PyDockLeaf leaf = PyDockLeaf(widget, title, id) new = PyDockComposite(position) parent.changeComponent(self, new) new.initChildren(self, leaf) return leaf def changeComponent (self, old, new): if old == self.paned.get_child1(): self.paned.remove(old) self.paned.pack1(new, resize=False, shrink=False) else: self.paned.remove(old) self.paned.pack2(new, resize=False, shrink=False) new.show() def removeComponent (self, component): if component == self.paned.get_child1(): new = self.paned.get_child2() else: new = self.paned.get_child1() self.paned.remove(new) parent = self.get_parent() while not isinstance(parent, DockComposite): parent = parent.get_parent() parent.changeComponent(self, new) component.__del__() # TODO: is this necessary? new.show() def getComponents (self): return self.paned.get_children() def initChildren (self, old, new): if self.position == NORTH or self.position == WEST: self.paned.pack1(new, resize=False, shrink=False) self.paned.pack2(old, resize=False, shrink=False) elif self.position == SOUTH or self.position == EAST: self.paned.pack1(old, resize=False, shrink=False) self.paned.pack2(new, resize=False, shrink=False) old.show() new.show() def cb (widget, allocation): if allocation.height != 1: if self.position == NORTH: pos = 0.381966011 * allocation.height elif self.position == SOUTH: pos = 0.618033989 * allocation.height elif self.position == WEST: pos = 0.381966011 * allocation.width elif self.position == EAST: pos = 0.618033989 * allocation.width widget.set_position(int(pos+.5)) widget.disconnect(conid) conid = self.paned.connect("size-allocate", cb) def getPosition (self): return self.position
Python
""" This module intends to work as glue between the gamemodel and the gamewidget taking care of stuff that is neither very offscreen nor very onscreen like bringing up dialogs and """ import math import gtk from pychess.Utils.Offer import Offer from pychess.Utils.const import * from pychess.Utils.repr import reprResult_long, reprReason_long from pychess.System import conf from pychess.System import glock from pychess.System.Log import log from pychess.widgets import preferencesDialog from gamewidget import getWidgets, key2gmwidg, isDesignGWShown def nurseGame (gmwidg, gamemodel): """ Call this function when gmwidget is just created """ gmwidg.connect("infront", on_gmwidg_infront) gmwidg.connect("closed", on_gmwidg_closed) gmwidg.connect("title_changed", on_gmwidg_title_changed) # Because of the async loading of games, the game might already be started, # when the glock is ready and nurseGame is called. # Thus we support both cases. if gamemodel.status == WAITING_TO_START: gamemodel.connect("game_started", on_game_started, gmwidg) gamemodel.connect("game_loaded", game_loaded, gmwidg) else: if gamemodel.uri: game_loaded(gamemodel, gamemodel.uri, gmwidg) on_game_started(gamemodel, gmwidg) gamemodel.connect("game_saved", game_saved, gmwidg) gamemodel.connect("game_ended", game_ended, gmwidg) gamemodel.connect("game_unended", game_unended, gmwidg) gamemodel.connect("game_resumed", game_unended, gmwidg) gamemodel.connect("game_changed", game_changed, gmwidg) gamemodel.connect("game_paused", game_paused, gmwidg) #=============================================================================== # Gamewidget signals #=============================================================================== def on_gmwidg_infront (gmwidg): for widget in MENU_ITEMS: if widget in gmwidg.menuitems: continue elif widget == 'show_sidepanels' and isDesignGWShown(): getWidgets()[widget].set_property('sensitive', False) else: getWidgets()[widget].set_property('sensitive', True) # Change window title getWidgets()['window1'].set_title('%s - PyChess' % gmwidg.getTabText()) def on_gmwidg_closed (gmwidg): if len(key2gmwidg) == 1: getWidgets()['window1'].set_title('%s - PyChess' % _('Welcome')) def on_gmwidg_title_changed (gmwidg): if gmwidg.isInFront(): getWidgets()['window1'].set_title('%s - PyChess' % gmwidg.getTabText()) #=============================================================================== # Gamemodel signals #=============================================================================== def game_ended (gamemodel, reason, gmwidg): log.debug("gamenanny.game_ended: reason=%s gmwidg=%s\ngamemodel=%s\n" % \ (reason, gmwidg, gamemodel)) nameDic = {"white": gamemodel.players[WHITE], "black": gamemodel.players[BLACK], "mover": gamemodel.curplayer} if gamemodel.status == WHITEWON: nameDic["winner"] = gamemodel.players[WHITE] nameDic["loser"] = gamemodel.players[BLACK] elif gamemodel.status == BLACKWON: nameDic["winner"] = gamemodel.players[BLACK] nameDic["loser"] = gamemodel.players[WHITE] m1 = reprResult_long[gamemodel.status] % nameDic m2 = reprReason_long[reason] % nameDic md = gtk.MessageDialog() md.set_markup("<b><big>%s</big></b>" % m1) md.format_secondary_markup(m2) if gamemodel.players[0].__type__ == LOCAL or gamemodel.players[1].__type__ == LOCAL: if gamemodel.players[0].__type__ == REMOTE or gamemodel.players[1].__type__ == REMOTE: md.add_button(_("Offer Rematch"), 0) else: md.add_button(_("Play Rematch"), 1) if gamemodel.status in UNDOABLE_STATES and gamemodel.reason in UNDOABLE_REASONS: if gamemodel.ply == 1: md.add_button(_("Undo one move"), 2) elif gamemodel.ply > 1: md.add_button(_("Undo two moves"), 2) def cb (messageDialog, responseId): if responseId == 0: if gamemodel.players[0].__type__ == REMOTE: gamemodel.players[0].offerRematch() else: gamemodel.players[1].offerRematch() elif responseId == 1: # newGameDialog uses ionest uses gamenanny uses newGameDialog... from pychess.widgets.newGameDialog import createRematch createRematch(gamemodel) elif responseId == 2: if gamemodel.curplayer.__type__ == LOCAL and gamemodel.ply > 1: offer = Offer(TAKEBACK_OFFER, gamemodel.ply-2) else: offer = Offer(TAKEBACK_OFFER, gamemodel.ply-1) if gamemodel.players[0].__type__ == LOCAL: gamemodel.players[0].emit("offer", offer) else: gamemodel.players[1].emit("offer", offer) md.connect("response", cb) glock.acquire() try: gmwidg.showMessage(md) gmwidg.status("%s %s." % (m1,m2[0].lower()+m2[1:])) if reason == WHITE_ENGINE_DIED: engineDead(gamemodel.players[0], gmwidg) elif reason == BLACK_ENGINE_DIED: engineDead(gamemodel.players[1], gmwidg) finally: glock.release() def _set_statusbar (gamewidget, message): assert type(message) is str or type(message) is unicode glock.acquire() try: gamewidget.status(message) finally: glock.release() def game_paused (gamemodel, gmwidg): _set_statusbar(gmwidg, _("The game is paused")) def game_changed (gamemodel, gmwidg): _set_statusbar(gmwidg, "") def game_unended (gamemodel, gmwidg): log.debug("gamenanny.game_unended: %s\n" % gamemodel.boards[-1]) glock.acquire() try: gmwidg.hideMessage() finally: glock.release() _set_statusbar(gmwidg, "") # Connect game_loaded, game_saved and game_ended to statusbar def game_loaded (gamemodel, uri, gmwidg): if type(uri) in (str, unicode): s = "%s: %s" % (_("Loaded game"), str(uri)) else: s = _("Loaded game") _set_statusbar(gmwidg, s) def game_saved (gamemodel, uri, gmwidg): _set_statusbar(gmwidg, "%s: %s" % (_("Saved game"), str(uri))) def on_game_started (gamemodel, gmwidg): on_gmwidg_infront(gmwidg) # setup menu items sensitivity # Rotate to human player boardview = gmwidg.board.view if gamemodel.players[1].__type__ == LOCAL: if gamemodel.players[0].__type__ != LOCAL: boardview.rotation = math.pi elif conf.get("autoRotate", True) and \ gamemodel.curplayer == gamemodel.players[1]: boardview.rotation = math.pi # Play set-up sound preferencesDialog.SoundTab.playAction("gameIsSetup") # Connect player offers to statusbar for player in gamemodel.players: if player.__type__ == LOCAL: player.connect("offer", offer_callback, gamemodel, gmwidg) # Start analyzers if any setAnalyzerEnabled(gmwidg, HINT, getWidgets()["hint_mode"].get_active()) setAnalyzerEnabled(gmwidg, SPY, getWidgets()["spy_mode"].get_active()) #=============================================================================== # Player signals #=============================================================================== def offer_callback (player, offer, gamemodel, gmwidg): if gamemodel.status != RUNNING: # If the offer has already been handled by Gamemodel and the game was # drawn, we need to do nothing return message = "" if offer.type == ABORT_OFFER: message = _("You sent an abort offer") elif offer.type == ADJOURN_OFFER: message = _("You sent an adjournment offer") elif offer.type == DRAW_OFFER: message = _("You sent a draw offer") elif offer.type == PAUSE_OFFER: message = _("You sent a pause offer") elif offer.type == RESUME_OFFER: message = _("You sent a resume offer") elif offer.type == ABORT_OFFER: message = _("You sent an undo offer") elif offer.type == HURRY_ACTION: message = _("You asked your opponent to move") _set_statusbar(gmwidg, message) #=============================================================================== # Subfunctions #=============================================================================== def engineDead (engine, gmwidg): gmwidg.bringToFront() d = gtk.MessageDialog(type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_OK) d.set_markup(_("<big><b>Engine, %s, has died</b></big>") % repr(engine)) d.format_secondary_text(_("PyChess has lost connection to the engine, probably because it has died.\n\nYou can try to start a new game with the engine, or try to play against another one.")) d.connect("response", lambda d,r: d.hide()) d.show_all() def setAnalyzerEnabled (gmwidg, analyzerType, enabled): if not analyzerType in gmwidg.gamemodel.spectators: return analyzer = gmwidg.gamemodel.spectators[analyzerType] if analyzerType == HINT: arrow = gmwidg.board.view._set_greenarrow else: arrow = gmwidg.board.view._set_redarrow set_arrow = lambda x: gmwidg.board.view.runWhenReady(arrow, x) if enabled: if len(analyzer.getAnalysis()) >= 1: if gmwidg.gamemodel.curplayer.__type__ == LOCAL or \ [player.__type__ for player in gmwidg.gamemodel.players] == [REMOTE, REMOTE]: set_arrow (analyzer.getAnalysis()[0].cords) else: set_arrow (None) # This is a kludge using pythons ability to asign attributes to an # object, even if those attributes are nowhere mentioned in the objects # class. So don't go looking for it ;) # Code is used to save our connection ids, enabling us to later dis- # connect if not hasattr (gmwidg.gamemodel, "anacons"): gmwidg.gamemodel.anacons = {HINT:[], SPY:[]} if not hasattr (gmwidg.gamemodel, "chacons"): gmwidg.gamemodel.chacons = [] def on_analyze (analyzer, moves, score): if moves and (gmwidg.gamemodel.curplayer.__type__ == LOCAL or \ [player.__type__ for player in gmwidg.gamemodel.players] == [REMOTE, REMOTE]): set_arrow (moves[0].cords) else: set_arrow (None) def on_game_change (gamemodel): set_arrow (None) gmwidg.gamemodel.anacons[analyzerType].append( analyzer.connect("analyze", on_analyze)) gmwidg.gamemodel.chacons.append( gmwidg.gamemodel.connect("game_changed", on_game_change)) gmwidg.gamemodel.chacons.append( gmwidg.gamemodel.connect("game_ended", lambda model, reason: on_game_change(model))) gmwidg.gamemodel.chacons.append( gmwidg.gamemodel.connect("moves_undoing", lambda model, moves: on_game_change(model))) else: if hasattr (gmwidg.gamemodel, "anacons"): for conid in gmwidg.gamemodel.anacons[analyzerType]: analyzer.disconnect(conid) del gmwidg.gamemodel.anacons[analyzerType][:] if hasattr (gmwidg.gamemodel, "chacons"): for conid in gmwidg.gamemodel.chacons: gmwidg.gamemodel.disconnect(conid) del gmwidg.gamemodel.chacons[:] set_arrow (None)
Python
import re from pychess.Utils.const import * import time import math from pychess.System import conf elemExpr = re.compile(r"([a-zA-Z])\s*([0-9\.,\s]*)\s+") spaceExpr = re.compile(r"[\s,]+") l = [] def parse(n, psize): yield "def f(c):" s = psize/size for cmd, points in n: pstr = ",".join(str(p*s) for p in points) if cmd == "M": yield "c.rel_move_to(%s)" % pstr elif cmd == "L": yield "c.rel_line_to(%s)" % pstr else: yield "c.rel_curve_to(%s)" % pstr # This has double speed at drawing, but when generating new functions, it # takes about ten times longer. def drawPiece3 (piece, cc, x, y, psize): cc.save() cc.move_to(x,y) if not psize in parsedPieces[piece.color][piece.sign]: exec("\n ".join(parse(parsedPieces[piece.color][piece.sign][size],psize))) parsedPieces[piece.color][piece.sign][psize] = f cc.fill() cc.restore() def drawPieceReal (piece, cc, psize): # Do the actual drawing to the Cairo context for cmd, points in parsedPieces[piece.color][piece.sign][psize]: if cmd == 'M': cc.rel_move_to(*points) elif cmd == 'L': cc.rel_line_to(*points) else: cc.rel_curve_to(*points) def drawPiece (piece, cc, x, y, psize): cc.save() cc.move_to(x,y) if not psize in parsedPieces[piece.color][piece.sign]: list = [(cmd, [(p*psize/size) for p in points]) for cmd, points in parsedPieces[piece.color][piece.sign][size]] parsedPieces[piece.color][piece.sign][psize] = list drawPieceReal (piece, cc, psize) cc.fill() cc.restore() # This version has proven itself nearly three times as slow as the "draw each time" method. At least when drawing one path only. Might be useful when drawing svg import cairo def drawPiece2 (piece, cc, x, y, psize): if not piece in surfaceCache: s = cc.get_target().create_similar(cairo.CONTENT_COLOR_ALPHA, int(size), int(size)) ctx = cairo.Context(s) ctx.move_to(0,0) drawPieceReal (piece, ctx, size) ctx.set_source_rgb(0,0,0) ctx.fill() surfaceCache[piece] = s cc.save() cc.set_source_rgb(0,0,0) cc.scale(psize/size, psize/size) cc.translate(x*size/psize, y*size/psize) cc.rectangle (0, 0, int(size), int(size)) # TODO: DOes this give any performance boost? # From cairo thread: # Or paint() instead of fill(). fill() needs a path, so you should do a # rectangle() first. cc.set_source_surface(surfaceCache[piece], 0, 0) cc.fill() cc.restore() surfaceCache = {} size = 800.0 pieces = { BLACK: { KING: "M 653.57940,730.65870 L 671.57940,613.65870 C 725.57940,577.65870 797.57940,514.65870 797.57940,397.65870 C 797.57940,325.65870 734.57940,280.65870 662.57940,280.65870 C 590.57940,280.65870 509.57940,334.65870 509.57940,334.65870 C 509.57940,334.65870 554.57940,190.65870 428.57940,154.65870 L 428.57940,118.65870 L 482.57940,118.65870 L 482.57940,64.658690 L 428.57940,64.658690 L 428.57940,10.658690 L 374.57940,10.658690 L 374.57940,64.658690 L 320.57940,64.658690 L 320.57940,118.65870 L 374.57940,118.65870 L 374.57940,154.65870 C 248.57940,190.65870 293.57940,334.65870 293.57940,334.65870 C 293.57940,334.65870 212.57940,280.65870 140.57940,280.65870 C 68.579380,280.65870 5.5793840,325.65870 5.5793840,397.65870 C 5.5793840,514.65870 77.579380,577.65870 131.57940,613.65870 L 149.57940,730.65870 C 158.57940,757.65870 221.57940,793.65870 401.57940,793.65870 C 581.57940,793.65870 644.57940,757.65870 653.57940,730.65870 z M 374.57940,541.65870 C 329.57940,541.65870 212.57940,550.65870 167.57940,568.65870 C 113.57940,541.65870 59.579380,496.65870 59.579380,406.65870 C 59.579380,352.65870 86.579380,334.65870 149.57940,334.65870 C 212.57940,334.65870 356.57940,397.65870 374.57940,541.65870 z M 428.57940,541.65870 C 446.57940,397.65870 590.57940,334.65870 662.57940,334.65870 C 716.57940,334.65870 743.57940,352.65870 743.57940,406.65870 C 743.57940,496.65870 689.57940,541.65870 635.57940,568.65870 C 590.57940,550.65870 473.57940,541.65870 428.57940,541.65870 z M 617.57940,667.65870 L 608.57940,705.90870 C 437.57940,678.90870 365.57940,678.90870 194.57940,705.90870 L 185.57940,667.65870 C 365.57940,640.65870 437.57940,640.65870 617.57940,667.65870 z M 464.57940,514.65870 C 527.57940,514.65870 581.57940,523.65870 635.57940,541.65870 C 707.57940,487.65870 716.57940,442.65870 716.57940,406.65870 C 716.57940,379.65870 698.57940,361.65870 662.57940,361.65870 C 554.57940,361.65670 473.57940,451.65870 464.57940,514.65870 z M 338.57940,514.65870 C 329.57940,451.65870 239.57940,361.65670 140.57940,361.65870 C 104.57940,361.65870 86.579380,388.65870 86.579380,415.65870 C 86.579380,442.65870 95.579380,487.65870 167.57940,541.65870 C 221.57940,523.65870 275.57940,514.65870 338.57940,514.65870 z ", QUEEN: "M 617.12310,626.00950 C 617.12310,599.00950 627.77310,557.68550 671.12310,536.00950 C 689.12310,527.00950 689.12310,509.00950 689.12310,500.00950 C 689.12310,471.54950 743.12310,203.00950 743.12310,203.00950 C 779.62510,198.74750 796.96610,170.47750 796.96610,144.34650 C 796.96610,112.98940 772.26810,85.907430 738.52810,85.907430 C 710.73310,85.907430 680.56310,109.18740 679.85110,143.63450 C 679.66510,152.63250 681.03910,169.05250 697.43010,186.15650 L 590.12310,392.00950 L 590.12310,158.00950 C 619.03410,151.95050 636.85210,127.48250 636.85210,99.687430 C 636.85210,69.517430 610.72110,42.199430 577.93710,42.199430 C 544.44210,42.199430 519.27910,70.470430 519.73610,102.06340 C 519.97310,118.45540 527.57510,136.03450 545.12410,149.00950 L 464.12410,383.00950 L 428.12410,131.00950 C 452.74310,117.03040 459.86810,97.075430 459.86810,80.208430 C 459.86810,41.011430 428.74910,20.581430 401.19210,20.818430 C 371.26010,21.076430 342.75310,46.950430 342.75310,77.120430 C 342.75310,107.05240 359.14410,122.73150 374.12410,131.00950 L 338.12410,383.00950 L 257.12410,149.00950 C 275.75910,134.13450 282.17310,119.64340 282.17310,98.976430 C 282.17310,77.833430 264.35910,42.199430 223.25910,42.199430 C 190.47610,42.199430 165.29410,70.944430 165.29410,99.926430 C 165.29410,134.84850 190.23910,153.37750 212.12410,158.01050 L 212.12410,392.01050 L 104.12410,185.01050 C 117.78210,170.95350 120.15710,154.06050 120.15710,145.06050 C 120.15710,114.41440 97.114060,85.807430 59.124060,86.010430 C 33.925060,86.146430 3.4010650,109.06240 3.0420650,145.06050 C 2.8040650,168.81650 20.858060,200.88650 59.124060,203.01050 C 59.124060,203.01050 113.12410,473.01050 113.12410,500.01050 C 113.12410,509.01150 113.12410,527.01050 131.12410,536.01050 C 167.12410,554.01150 185.12410,599.01050 185.12410,626.01050 C 185.12410,662.01150 158.12410,698.01150 158.12410,707.01150 C 158.12410,752.01050 320.12410,779.01150 401.12410,778.99150 C 473.12410,778.97350 644.12410,752.01050 644.12410,707.01050 C 644.12410,698.01050 617.12410,671.01050 617.12410,626.01050 L 617.12310,626.00950 z M 594.55210,537.12950 C 583.21810,553.12950 581.21810,558.46250 576.55210,575.12950 C 487.21810,553.79650 327.21810,547.79650 225.88510,575.79650 C 221.21710,557.79650 219.21710,550.46250 208.55110,537.12950 C 325.21710,508.46250 479.21710,506.46250 594.55110,537.12950 L 594.55210,537.12950 z M 570.55210,663.79650 C 555.88510,674.46250 551.21810,682.46250 542.55210,693.79650 C 434.55210,677.12950 363.88410,674.46250 255.21810,693.12950 C 246.55210,679.79650 241.88610,673.12950 229.21810,663.79650 C 341.88610,634.46250 457.88610,644.46250 570.55210,663.79650 L 570.55210,663.79650 z ", ROOK: "M 232.94440,519.29360 L 124.94440,627.29360 L 124.94440,762.29360 L 682.94440,762.29360 L 682.94440,627.29360 L 574.94440,519.29360 L 574.94440,303.29360 L 682.94440,231.29360 L 682.94440,51.293580 L 520.94440,51.293580 L 520.94440,123.29360 L 484.94440,123.29360 L 484.94440,51.293580 L 322.94440,51.293580 L 322.94440,123.29360 L 286.94440,123.29360 L 286.94440,51.293580 L 124.94440,51.293580 L 124.94440,231.29360 L 232.94440,303.29360 L 232.94440,519.29360 z M 268.94440,321.29360 L 268.94440,285.29360 L 538.94440,285.29360 L 538.94440,321.29360 L 268.94440,321.29360 z M 268.94440,537.29360 L 268.94440,501.29360 L 538.94440,501.29360 L 538.94440,537.29360 L 268.94440,537.29360 z ", BISHOP: "M 491.69440,453.44430 L 500.69440,482.69430 C 464.69440,455.69430 338.69440,455.69430 302.69440,482.69430 L 311.69440,453.44430 C 332.69440,432.44430 470.69440,432.44430 491.69440,453.44430 z M 509.69440,518.69430 L 518.69440,545.69430 C 470.69440,521.69430 332.69440,521.69430 284.69440,545.69430 L 293.69440,518.69430 C 338.69440,491.69430 464.69440,491.69430 509.69440,518.69430 z M 797.69440,653.69430 C 797.69440,653.69430 752.69440,635.69430 689.69440,626.69430 C 652.95940,621.44630 599.69440,635.69430 554.69440,626.69430 C 518.69440,617.69430 482.69440,599.69430 482.69440,599.69430 L 572.69440,554.69430 L 545.69440,473.69430 C 545.69440,473.69430 608.69440,446.69430 608.69440,365.69430 C 608.69440,302.69430 563.69440,230.69430 500.69440,194.69430 C 455.13040,168.65830 446.69440,149.69430 446.69440,149.69430 C 446.69440,149.69430 482.69440,131.69430 482.69440,86.694330 C 482.69440,50.694330 455.69440,5.6943260 401.69440,5.6943260 C 347.69440,5.6943260 320.69440,50.694330 320.69440,86.694330 C 320.69440,131.69430 356.69440,149.69430 356.69440,149.69430 C 356.69440,149.69430 348.25840,168.65830 302.69440,194.69430 C 239.69440,230.69430 194.69440,302.69430 194.69440,365.69430 C 194.69440,446.69430 257.69440,473.69430 257.69440,473.69430 L 230.69440,554.69430 L 320.69440,599.69430 C 320.69440,599.69430 284.69440,617.69430 248.69440,626.69430 C 204.17340,637.82430 146.99540,621.93730 113.69440,626.69430 C 50.694360,635.69430 5.6943640,653.69430 5.6943640,653.69430 L 50.694360,797.69430 C 113.69440,779.69430 122.69440,779.69430 176.69440,770.69430 C 209.78640,765.17930 291.51040,774.42230 329.69440,761.69430 C 383.69440,743.69430 401.69440,716.69430 401.69440,716.69430 C 401.69440,716.69430 419.69440,743.69430 473.69440,761.69430 C 511.87840,774.42230 598.40740,767.15830 626.69440,770.69430 C 681.01640,777.48430 752.69440,797.69430 752.69440,797.69430 L 797.69440,653.69430 L 797.69440,653.69430 z M 428.69440,392.69430 L 374.69440,392.69430 L 374.69440,356.69430 L 338.69440,356.69430 L 338.69440,302.69430 L 374.69440,302.69430 L 374.69440,266.69430 L 428.69440,266.69430 L 428.69440,302.69430 L 464.69440,302.69430 L 464.69440,356.69430 L 428.69440,356.69430 L 428.69440,392.69430 z ", KNIGHT: "M 84.310370,730.48460 L 564.28850,729.48460 C 563.97550,600.58860 477.97550,556.58860 485.00550,477.74860 L 587.06050,552.58860 C 611.11150,581.44960 637.05150,594.72560 657.36750,594.91660 C 671.53450,595.04960 633.37050,547.08060 627.37050,536.08060 C 653.37050,535.08060 689.37050,585.08060 718.38750,574.11560 C 739.54850,566.12160 754.01750,540.22060 753.06850,502.24260 C 751.70850,447.81260 690.47450,367.52960 667.34250,266.83660 C 641.48850,160.69960 611.91250,147.09260 595.58450,141.64850 L 595.22350,64.085560 L 513.57950,123.95850 L 467.31450,43.675570 L 421.04950,138.92750 C 260.48350,91.300560 89.752370,428.40260 84.309370,730.48460 L 84.310370,730.48460 z M 125.87840,697.92560 C 125.87840,436.61260 289.76850,168.92760 381.72850,167.10560 C 399.37150,167.41260 415.37150,173.41260 415.32750,179.85360 C 415.24050,192.63260 399.02750,197.15260 379.90750,197.15260 C 307.97850,199.88460 158.65640,453.00260 156.83540,695.19560 C 156.83540,713.40460 127.70040,712.49460 125.87940,697.92560 L 125.87840,697.92560 z M 678.74350,471.34160 C 684.09050,477.57960 689.68150,486.16560 689.86350,492.19160 C 690.09450,499.83660 684.07150,505.86160 678.28050,503.54360 C 672.48850,501.22760 665.53850,488.25260 660.90550,485.70560 C 656.27250,483.15660 642.14050,481.30360 642.37250,474.81660 C 642.60450,468.32960 652.10250,462.53760 657.66250,462.76960 C 663.22250,463.00160 675.96450,468.09760 678.74450,471.34160 L 678.74350,471.34160 z M 520.98750,218.08460 C 534.62350,223.81160 559.71450,235.26460 577.44150,255.99260 C 594.62350,278.90060 595.98650,304.80860 596.53150,323.35560 C 566.80450,326.90060 541.87450,318.25160 529.44150,290.90060 C 521.25950,272.90060 520.98650,239.62960 520.98650,218.08460 L 520.98750,218.08460 z ", PAWN: "M 688.02380,750.97630 L 688.02380,624.97630 C 688.02380,579.97630 661.62380,452.47630 553.02380,408.97630 C 598.02380,354.97630 607.02380,255.97630 517.02380,192.97630 C 544.02380,156.97630 517.02380,30.976220 409.02380,30.976220 C 301.02380,30.976220 274.02380,156.97630 301.02380,192.97630 C 211.02380,255.97630 220.02380,354.97630 265.02380,408.97630 C 157.02380,453.97630 130.02380,579.97630 130.02380,624.97630 L 130.02380,750.97630 L 688.02380,750.97630 z " }, WHITE: { KING: "M 648.50000,730.65870 L 666.50000,613.65870 C 720.50000,577.65870 792.50000,514.65870 792.50000,397.65870 C 792.50000,325.65870 729.50000,280.65870 657.50000,280.65870 C 585.50000,280.65870 504.50000,334.65870 504.50000,334.65870 C 504.50000,334.65870 549.50000,190.65870 423.50000,154.65870 L 423.50000,118.65870 L 477.50000,118.65870 L 477.50000,64.658690 L 423.50000,64.658690 L 423.50000,10.658690 L 369.50000,10.658690 L 369.50000,64.658690 L 315.50000,64.658690 L 315.50000,118.65870 L 369.50000,118.65870 L 369.50000,154.65870 C 243.50000,190.65870 288.50000,334.65870 288.50000,334.65870 C 288.50000,334.65870 207.50000,280.65870 135.50000,280.65870 C 63.500000,280.65870 0.50000000,325.65870 0.50000000,397.65870 C 0.50000000,514.65870 72.500000,577.65870 126.50000,613.65870 L 144.50000,730.65870 C 153.50000,757.65870 216.50000,793.65870 396.50000,793.65870 C 576.50000,793.65870 639.50000,757.65870 648.50000,730.65870 z M 396.50000,451.65870 C 396.50000,451.65870 333.50000,343.65870 333.50000,280.65870 C 333.50000,217.65870 369.50000,208.65870 396.50000,208.65870 C 423.50000,208.65870 459.50000,226.65870 459.50000,280.65870 C 459.50000,334.65870 396.50000,451.65870 396.50000,451.65870 z M 369.50000,541.65870 C 324.50000,541.65870 207.50000,550.65870 162.50000,568.65870 C 108.50000,541.65870 54.500000,496.65870 54.500000,406.65870 C 54.500000,352.65870 81.500000,334.65870 144.50000,334.65870 C 207.50000,334.65870 351.50000,397.65870 369.50000,541.65870 z M 423.50000,541.65870 C 441.50000,397.65870 585.50000,334.65870 657.50000,334.65870 C 711.50000,334.65870 738.50000,352.65870 738.50000,406.65870 C 738.50000,496.65870 684.50000,541.65870 630.50000,568.65870 C 585.50000,550.65870 468.50000,541.65870 423.50000,541.65870 z M 612.50000,613.65870 L 603.50000,685.65870 C 432.50000,658.65870 360.50000,658.65870 189.50000,685.65870 L 180.50000,613.65870 C 360.50000,586.65870 432.50000,586.65870 612.50000,613.65870 z M 549.50000,730.65870 C 468.50000,748.65870 441.50000,748.65870 396.50000,748.65870 C 351.50000,748.65870 324.50000,748.65870 243.50000,730.65870 C 324.50000,712.65870 342.50000,712.65870 396.50000,712.65870 C 450.50000,712.65870 468.50000,712.65870 549.50000,730.65870 z ", QUEEN: "M 764.60380,143.65350 C 764.80680,155.66150 755.91880,166.72550 742.61880,166.56350 C 727.46980,166.37750 719.85480,154.92450 719.70980,144.57750 C 719.52480,131.46050 729.68780,121.66950 742.24980,121.66950 C 754.99780,121.66950 764.41980,132.75350 764.60380,143.65350 L 764.60380,143.65350 z M 619.66280,626.00950 C 619.66280,599.00950 630.31280,557.68550 673.66280,536.00950 C 691.66280,527.00950 691.66280,509.00950 691.66280,500.00950 C 691.66280,471.54950 745.66280,203.00950 745.66280,203.00950 C 782.16480,198.74750 799.50580,170.47750 799.50580,144.34650 C 799.50580,112.98950 774.80780,85.907570 741.06780,85.907570 C 713.27280,85.907570 683.10280,109.18750 682.39080,143.63450 C 682.20480,152.63250 683.57880,169.05250 699.96980,186.15650 L 592.66280,392.00950 L 592.66280,158.00950 C 621.57380,151.95050 639.39180,127.48250 639.39180,99.687540 C 639.39180,69.517570 613.26080,42.199570 580.47680,42.199570 C 546.98180,42.199570 521.81880,70.470570 522.27580,102.06350 C 522.51280,118.45550 530.11480,136.03450 547.66380,149.00950 L 466.66380,383.00950 L 430.66380,131.00950 C 455.28280,117.03050 462.40880,97.075540 462.40880,80.208570 C 462.40880,41.011570 431.28880,20.581570 403.73180,20.818570 C 373.79980,21.076570 345.29380,46.950570 345.29380,77.120570 C 345.29380,107.05250 361.68480,122.73150 376.66380,131.00950 L 340.66380,383.00950 L 259.66380,149.00950 C 278.29980,134.13450 284.71380,119.64350 284.71380,98.976540 C 284.71380,77.833570 266.89880,42.199570 225.79980,42.199570 C 193.01680,42.199570 167.83480,70.944570 167.83480,99.926540 C 167.83480,134.84850 192.77880,153.37750 214.66380,158.01050 L 214.66380,392.01050 L 106.66380,185.01050 C 120.32180,170.95350 122.69780,154.06050 122.69780,145.06050 C 122.69780,114.41450 99.654770,85.807570 61.663770,86.010570 C 36.464770,86.146570 5.9407760,109.06250 5.5817760,145.06050 C 5.3447760,168.81650 23.398770,200.88650 61.663770,203.01050 C 61.663770,203.01050 115.66380,473.01050 115.66380,500.01050 C 115.66380,509.01150 115.66380,527.01050 133.66380,536.01050 C 169.66380,554.01150 187.66380,599.01050 187.66380,626.01050 C 187.66380,662.01150 160.66380,698.01150 160.66380,707.01150 C 160.66380,752.01050 322.66380,779.01150 403.66380,778.99150 C 475.66380,778.97350 646.66380,752.01050 646.66380,707.01050 C 646.66380,698.01050 619.66380,671.01050 619.66380,626.01050 L 619.66280,626.00950 z M 87.606770,144.04950 C 87.809770,156.05650 78.921770,167.12050 65.621770,166.95850 C 50.472770,166.77350 42.857770,155.31950 42.712770,144.97350 C 42.527770,131.85650 52.690770,122.06450 65.252770,122.06450 C 78.000770,122.06450 87.422770,133.14950 87.606770,144.04950 z M 603.61080,99.656540 C 603.81380,111.66350 594.92580,122.72750 581.62580,122.56550 C 566.47680,122.38050 558.86180,110.92650 558.71680,100.58050 C 558.53180,87.463540 568.69480,77.671570 581.25680,77.671570 C 594.00480,77.671570 603.42680,88.756540 603.61080,99.656540 L 603.61080,99.656540 z M 426.61880,78.157570 C 426.82180,90.165540 417.93380,101.22950 404.63380,101.06750 C 389.48480,100.88150 381.86980,89.428540 381.72480,79.081570 C 381.53980,65.964570 391.70280,56.173570 404.26480,56.173570 C 417.01280,56.173570 426.43480,67.257570 426.61880,78.157570 z M 249.12780,100.65650 C 249.33080,112.66350 240.44280,123.72750 227.14280,123.56550 C 211.99380,123.38050 204.37880,111.92650 204.23380,101.58050 C 204.04880,88.463540 214.21180,78.671570 226.77380,78.671570 C 239.52180,78.671570 248.94380,89.756540 249.12780,100.65650 z M 578.63980,575.93450 C 569.63980,591.93450 563.63980,630.93450 573.63980,663.93450 C 467.97280,643.60050 338.63980,637.93450 231.63980,663.93450 C 238.63980,638.93450 240.63980,613.93450 227.63980,575.93450 C 320.63980,544.93450 515.63980,553.93450 578.63980,575.93450 L 578.63980,575.93450 z M 537.63980,707.93450 C 489.97280,725.93450 429.97280,726.26850 399.97280,726.26850 C 369.97280,726.26850 308.97280,723.93450 264.63980,708.93450 C 317.63980,697.93450 362.30680,695.60050 397.30680,695.60050 C 432.30680,695.60050 497.97280,700.26850 537.63980,707.93450 z M 210.32980,536.94050 C 210.32980,536.94050 205.66280,530.27350 200.99580,524.94050 C 210.32980,522.27350 232.99580,509.60650 244.32980,494.94050 C 291.66280,508.94050 316.32980,498.94050 350.99580,476.27350 C 384.32980,494.94050 417.66280,494.27350 458.99580,474.94050 C 486.32980,498.27350 515.66280,504.27350 559.66280,495.60650 C 576.32980,512.94050 586.99580,518.94050 604.32980,525.60650 L 596.32980,536.94050 C 454.32980,506.94050 358.99580,506.27350 210.32980,536.94050 L 210.32980,536.94050 z M 691.30580,290.55250 L 654.25080,486.80250 C 626.80380,493.20650 606.21880,481.76950 593.40980,465.30150 L 691.30580,290.55250 z M 553.20180,247.31050 L 550.98680,445.24750 C 523.09080,454.98950 508.03480,450.56150 487.66580,434.17750 L 553.20180,247.31050 z M 401.76580,233.14150 L 433.64780,429.30650 C 416.82180,441.26250 388.48180,443.47650 369.44080,428.74850 L 401.76580,233.14150 z M 252.98380,254.39550 L 318.96280,441.26250 C 304.35080,457.64650 279.55280,464.28750 255.64180,452.77550 L 252.98480,254.39550 L 252.98380,254.39550 z M 116.63980,294.93450 L 212.13980,463.43450 C 201.63980,481.43450 175.13980,492.43450 151.13980,485.43450 L 116.63980,294.93450 z ", ROOK: "M 227.86510,504.05560 L 119.86510,612.05560 L 119.86510,747.05560 L 677.86510,747.05560 L 677.86510,612.05560 L 569.86510,504.05560 L 569.86510,288.05560 L 677.86510,216.05560 L 677.86510,36.055570 L 515.86510,36.055570 L 515.86510,108.05560 L 479.86510,108.05560 L 479.86510,36.055570 L 317.86510,36.055570 L 317.86510,108.05560 L 281.86510,108.05560 L 281.86510,36.055570 L 119.86510,36.055570 L 119.86510,216.05560 L 227.86510,288.05560 L 227.86510,504.05560 z M 623.86510,90.055570 L 623.86510,180.05560 L 515.86510,252.05560 L 281.86510,252.05560 L 173.86510,180.05560 L 173.86510,90.055570 L 227.86510,90.055570 L 227.86510,162.05560 L 371.86510,162.05560 L 371.86510,90.055570 L 425.86510,90.055570 L 425.86510,162.05560 L 569.86510,162.05560 L 569.86510,90.055570 L 623.86510,90.055570 z M 515.86510,315.05560 L 515.86510,468.05560 L 281.86510,468.05560 L 281.86510,315.05560 L 515.86510,315.05560 z M 623.86510,657.05560 L 623.86510,693.05560 L 173.86510,693.05560 L 173.86510,657.05560 L 623.86510,657.05560 z M 515.86510,531.05560 L 596.86510,603.05560 L 200.86510,603.05560 L 281.86510,531.05560 L 515.86510,531.05560 z ", BISHOP: "M 404.23410,59.693330 C 422.23410,59.693330 431.23410,68.693330 431.23410,86.693330 C 431.23410,104.69330 422.23410,113.69330 404.23410,113.69330 C 386.23410,113.69330 377.23410,104.69330 377.23410,86.693330 C 377.23410,68.693330 386.23410,59.693330 404.23410,59.693330 z M 404.23410,167.69330 C 440.23410,221.69330 458.23410,221.69330 503.23410,257.69330 C 548.23410,293.69330 557.23410,338.69330 557.23410,374.69430 C 557.23410,410.69330 536.23410,432.29530 512.23410,446.69430 C 512.23410,446.69430 476.23410,428.69430 404.23410,428.69430 C 332.23410,428.69430 296.23410,446.69430 296.23410,446.69430 C 296.23410,446.69430 251.23410,410.69330 251.23410,374.69430 C 251.23410,338.69330 260.23410,293.69330 305.23410,257.69330 C 350.23410,221.69330 368.23410,221.69330 404.23410,167.69330 z M 503.23410,482.69430 L 512.23410,509.69430 C 467.23410,491.69430 341.23410,491.69430 296.23410,509.69430 L 305.23410,482.69430 C 341.23410,464.69430 467.23410,464.69430 503.23410,482.69430 z M 404.23410,536.69430 C 440.23410,536.69530 494.23410,545.69430 494.23410,545.69430 C 494.23410,545.69430 440.23410,554.69430 404.23410,554.69430 C 368.23410,554.69430 314.23410,545.69530 314.23410,545.69530 C 314.23410,545.69530 368.23410,536.69330 404.23410,536.69430 z M 440.23410,635.69430 C 494.23410,671.69430 503.59610,666.60330 539.23410,671.69430 C 602.23410,680.69430 628.16110,676.01530 656.23410,680.69430 C 710.23410,689.69430 737.23410,698.69430 737.23410,698.69430 L 719.23410,743.69430 C 719.23410,743.69430 710.66410,732.18430 665.23410,725.69430 C 602.23410,716.69430 548.23410,716.69430 503.23410,707.69430 C 458.23410,698.69430 422.23410,680.69430 404.23410,662.69430 C 386.84810,680.08030 350.23410,698.69430 305.23410,707.69430 C 260.23410,716.69430 207.48310,712.84430 143.23410,725.69430 C 98.234040,734.69430 89.234040,743.69430 89.234040,743.69430 L 71.234040,698.69430 C 71.234040,698.69430 98.234040,689.69430 152.23410,680.69430 C 176.77810,676.60330 206.23410,680.69430 269.23410,671.69430 C 305.96910,666.44630 314.23410,671.69430 368.23410,635.69430 L 440.23410,635.69430 z M 431.23410,266.69430 L 377.23410,266.69430 L 377.23410,302.69430 L 341.23410,302.69430 L 341.23410,356.69430 L 377.23410,356.69430 L 377.23410,392.69430 L 431.23410,392.69430 L 431.23410,356.69430 L 467.23410,356.69430 L 467.23410,302.69430 L 431.23410,302.69430 L 431.23410,266.69430 z M 800.23410,653.69430 C 800.23410,653.69430 755.23410,635.69430 692.23410,626.69430 C 655.49910,621.44630 602.23410,635.69430 557.23410,626.69430 C 521.23410,617.69430 485.23410,599.69430 485.23410,599.69430 L 575.23410,554.69430 L 548.23410,473.69430 C 548.23410,473.69430 611.23410,446.69430 611.23410,365.69430 C 611.23410,302.69430 566.23410,230.69430 503.23410,194.69430 C 457.67010,168.65830 449.23410,149.69430 449.23410,149.69430 C 449.23410,149.69430 485.23410,131.69430 485.23410,86.694330 C 485.23410,50.694330 458.23410,5.6943260 404.23410,5.6943260 C 350.23410,5.6943260 323.23410,50.694330 323.23410,86.694330 C 323.23410,131.69430 359.23410,149.69430 359.23410,149.69430 C 359.23410,149.69430 350.79810,168.65830 305.23410,194.69430 C 242.23410,230.69430 197.23410,302.69430 197.23410,365.69430 C 197.23410,446.69430 260.23410,473.69430 260.23410,473.69430 L 233.23410,554.69430 L 323.23410,599.69430 C 323.23410,599.69430 287.23410,617.69430 251.23410,626.69430 C 206.71310,637.82430 149.53510,621.93730 116.23410,626.69430 C 53.234040,635.69430 8.2340370,653.69430 8.2340370,653.69430 L 53.234040,797.69430 C 116.23410,779.69430 125.23410,779.69430 179.23410,770.69430 C 212.32610,765.17930 294.05010,774.42230 332.23410,761.69430 C 386.23410,743.69430 404.23410,716.69430 404.23410,716.69430 C 404.23410,716.69430 422.23410,743.69430 476.23410,761.69430 C 514.41810,774.42230 600.94710,767.15830 629.23410,770.69430 C 683.55610,777.48430 755.23410,797.69430 755.23410,797.69430 L 800.23410,653.69430 L 800.23410,653.69430 z ", KNIGHT: "M 76.688770,727.94590 L 556.66680,726.94590 C 556.35380,598.04990 470.35380,554.04990 477.38380,475.20990 L 579.43880,550.04990 C 620.25980,599.03590 666.52580,603.11790 681.49380,574.54390 C 715.51280,581.34690 746.80780,554.13390 745.44780,499.70390 C 744.08780,445.27390 682.85280,364.99090 659.72080,264.29690 C 633.86680,158.15990 604.29080,144.55290 587.96280,139.10890 L 587.60180,61.545870 L 505.95780,121.41890 L 459.69280,41.135870 L 413.42780,136.38790 C 252.86280,88.761870 82.131770,425.86390 76.688770,727.94590 z M 505.95780,677.95990 L 126.31380,677.95990 C 205.68580,187.71690 362.68580,154.71690 437.92180,193.53890 L 462.41480,144.55290 L 481.46480,178.57090 L 567.19080,198.98090 L 576.71580,189.45790 C 597.12680,205.78590 608.14980,284.03590 634.35280,350.71790 C 662.29280,421.82190 697.90980,477.31990 697.82080,496.98190 C 697.68580,526.71790 689.01880,532.71790 671.96680,525.55790 C 663.68580,512.04990 655.01880,500.71790 639.30980,499.70390 C 632.35280,500.04990 621.14380,503.00890 631.68580,509.71790 C 646.35280,519.04990 642.75180,540.16490 642.75180,540.16490 C 616.01880,518.71790 515.25280,437.01890 459.69280,401.73090 C 442.35180,390.71690 426.68480,380.71690 414.68480,350.21690 C 390.82180,377.37090 416.35180,430.71690 431.68480,444.04890 C 408.35180,536.04890 484.35180,618.71690 505.95680,677.95890 L 505.95780,677.95990 z M 682.04780,490.00990 C 682.04780,485.18590 675.98380,472.91790 669.91880,467.95690 C 663.85480,462.99390 654.48180,460.23590 648.96880,460.37490 C 643.45580,460.51390 634.49680,465.74990 634.90980,472.36690 C 635.32280,478.98190 647.17680,480.77490 651.86280,482.56590 C 656.54880,484.35690 662.88880,496.62590 669.50480,500.75990 C 676.12080,504.89390 682.04780,496.67790 682.04780,490.00990 L 682.04780,490.00990 z M 588.45680,320.97290 C 588.11380,280.48690 578.16380,263.67390 566.49780,249.26390 C 554.83180,234.85190 512.97280,215.29490 512.97280,215.29490 C 512.97280,215.29490 508.16880,266.41790 525.66780,296.26990 C 543.16680,326.11990 570.61480,321.31690 588.45680,320.97290 L 588.45680,320.97290 z ", PAWN: "M 688.02380,753.51590 L 688.02380,627.51590 C 688.02380,582.51590 661.62380,455.01590 553.02380,411.51590 C 598.02380,357.51590 607.02380,258.51590 517.02380,195.51590 C 544.02380,159.51590 517.02380,33.515900 409.02380,33.515900 C 301.02380,33.515900 274.02380,159.51590 301.02380,195.51590 C 211.02380,258.51590 220.02380,357.51590 265.02380,411.51590 C 157.02380,456.51590 130.02380,582.51590 130.02380,627.51590 L 130.02380,753.51590 L 688.02380,753.51590 z M 409.02380,87.515900 C 490.02380,87.515900 490.02380,177.51590 454.02380,213.51590 C 562.02380,258.51590 535.02380,375.51590 481.02380,429.51590 C 571.02380,456.51590 634.02380,546.51590 634.02380,609.51590 L 634.02380,699.51590 L 184.02380,699.51590 L 184.02380,609.51590 C 184.02380,546.51590 247.02380,456.51590 337.02380,429.51590 C 283.02380,375.51590 256.02380,258.51590 364.02380,213.51590 C 328.02380,177.51590 328.02380,87.515900 409.02380,87.515900 z " } } parsedPieces = [[[], [], [], [], [], [], []], \ [[], [], [], [], [], [], []]] for color in (WHITE, BLACK): for piece in range(PAWN, KING+1): list = [] thep = [0,0] for g1, g2 in elemExpr.findall(pieces[color][piece]): if not g1 or not g2: continue points = [float(s) for s in spaceExpr.split(g2)] list += [(g1, [f-thep[i%2] for i,f in enumerate(points)])] thep = points[-2:] parsedPieces[color][piece] = {size:list}
Python
from pychess.Utils.Cord import Cord from pychess.Utils.const import * from lutils import lmove from lutils.lmove import ParsingError, FLAG_PIECE class Move: def __init__ (self, cord0, cord1=None, board=None, promotion=None): """ Inits a new highlevel Move object. The object can be initialized in the follow ways: Move(cord0, cord1, board, [promotionPiece]) Move(lovLevelMoveInt) """ if not cord1: self.move = cord0 self.flag = self.move >> 12 if self.flag in PROMOTIONS: self.promotion = lmove.PROMOTE_PIECE (self.move) else: self.promotion = QUEEN self.cord0 = Cord(lmove.FCORD(self.move)) self.cord1 = Cord(lmove.TCORD(self.move)) else: assert cord0 != None and cord1 != None, "cord0=%s, cord1=%s, board=%s" % (cord0, cord1, board) assert board[cord0] != None, "cord0=%s, cord1=%s, board=%s" % (cord0, cord1, board) self.cord0 = cord0 self.cord1 = cord1 if not board: raise ValueError, "Move needs a Board object in order to investigate flags" self.flag = NORMAL_MOVE if board[self.cord0].piece == PAWN and self.cord1.y in (0,7): if promotion == None: promotion = QUEEN self.flag = FLAG_PIECE(promotion) elif board[self.cord0].piece == KING: if board.variant == FISCHERRANDOMCHESS: if (abs(self.cord0.x - self.cord1.x) > 1 and self.cord1.x==C1) or \ \ (board.board.ini_rooks[board.color][0] == self.cord1.cord and \ ((board.board.color == WHITE and board.board.castling & W_OOO) or \ (board.board.color == BLACK and board.board.castling & B_OOO))): self.flag = QUEEN_CASTLE elif (abs(self.cord0.x - self.cord1.x) > 1 and self.cord1.x==G1) or \ \ (board.board.ini_rooks[board.color][1] == self.cord1.cord and \ ((board.board.color == WHITE and board.board.castling & W_OO) or \ (board.board.color == BLACK and board.board.castling & B_OO))): self.flag = KING_CASTLE else: if self.cord0.x - self.cord1.x == 2: self.flag = QUEEN_CASTLE elif self.cord0.x - self.cord1.x == -2: self.flag = KING_CASTLE elif board[self.cord0].piece == PAWN and \ board[self.cord1] == None and \ self.cord0.x != self.cord1.x and \ self.cord0.y != self.cord1.y: self.flag = ENPASSANT self.move = lmove.newMove(self.cord0.cord, self.cord1.cord, self.flag) def _get_cords (self): return (self.cord0, self.cord1) cords = property(_get_cords) def _get_promotion (self): if self.flag in PROMOTIONS: return lmove.PROMOTE_PIECE(self.flag) return None promotion = property(_get_promotion) def __repr__ (self): return str(self.cord0) + str(self.cord1) def __eq__ (self, other): if isinstance(other, Move): return self.move == other.move def __hash__ (self): return hash(self.cords) def is_capture (self, board): return self.flag == ENPASSANT or \ board[self.cord1] != None and \ self.flag != QUEEN_CASTLE and self.flag != KING_CASTLE ################################################################################ # Parsers # ################################################################################ def listToMoves (board, mstrs, type=None, validate=False, ignoreErrors=False): return [Move(move) for move in lmove.listToMoves(board.board, mstrs, type, validate, ignoreErrors)] def parseAny (board, algnot): return Move(lmove.parseAny (board.board, algnot)) def parseSAN (board, san): """ Parse a Short/Abbreviated Algebraic Notation string """ return Move (lmove.parseSAN (board.board, san)) def parseLAN (board, lan): """ Parse a Long/Expanded Algebraic Notation string """ return Move (lmove.parseLAN (board.board, lan)) def parseFAN (board, lan): """ Parse a Long/Expanded Algebraic Notation string """ return Move (lmove.parseFAN (board.board, lan)) def parseAN (board, an): """ Parse an Algebraic Notation string """ return Move(lmove.parseAN (board.board, an)) ################################################################################ # Exporters # ################################################################################ def listToSan (board, moves): return lmove.listToSan(board.board, (m.move for m in moves)) def toAN (board, move, short=False): """ Returns a Algebraic Notation string of a move board should be prior to the move """ return lmove.toAN (board.board, move.move, short=short) def toSAN (board, move, localRepr=False): """ Returns a Short/Abbreviated Algebraic Notation string of a move The board should be prior to the move, board2 past. If not board2, toSAN will not test mate """ return lmove.toSAN (board.board, move.move, localRepr) def toLAN (board, move): """ Returns a Long/Expanded Algebraic Notation string of a move board should be prior to the move """ return lmove.toLAN (board.board, move.move) def toFAN (board, move): """ Returns a Figurine Algebraic Notation string of a move """ return lmove.toFAN (board.board, move.move)
Python
from gtk import icon_theme_get_default, ICON_LOOKUP_USE_BUILTIN from pychess.System.Log import log it = icon_theme_get_default() def load_icon(size, *alternatives): alternatives = list(alternatives) name = alternatives.pop(0) try: return it.load_icon(name, size, ICON_LOOKUP_USE_BUILTIN) except: if alternatives: return load_icon(size, *alternatives) log.warn("no %s icon in icon-theme-gnome" % name)
Python
from const import * import __builtin__ if '_' not in __builtin__.__dict__: __builtin__.__dict__['_'] = lambda s: s reprColor = [_("White"), _("Black")] reprPiece = ["Empty", _("Pawn"), _("Knight"), _("Bishop"), _("Rook"), _("Queen"), _("King"), "BPawn"] localReprSign = ["", _("P"), _("N"), _("B"), _("R"), _("Q"), _("K")] reprResult_long = { DRAW: _("The game ended in a draw"), WHITEWON: _("%(white)s won the game"), BLACKWON: _("%(black)s won the game"), KILLED: _("The game has been killed"), ADJOURNED: _("The game has been adjourned"), ABORTED: _("The game has been aborted"), } reprReason_long = { DRAW_INSUFFICIENT: _("Because neither player has sufficient material to mate"), DRAW_REPITITION: _("Because the same position was repeated three times in a row"), DRAW_50MOVES: _("Because the last 50 moves brought nothing new"), DRAW_CALLFLAG: _("Because both players ran out of time"), DRAW_STALEMATE: _("Because %(mover)s stalemated"), DRAW_AGREE: _("Because the players agreed to"), DRAW_ADJUDICATION: _("Because of adjudication by an admin"), DRAW_LENGTH: _("Because the game exceed the max length"), DRAW_BLACKINSUFFICIENTANDWHITETIME: _("Because %(white)s ran out of time and %(black)s has insufficient material to mate"), DRAW_WHITEINSUFFICIENTANDBLACKTIME: _("Because %(black)s ran out of time and %(white)s has insufficient material to mate"), WON_RESIGN: _("Because %(loser)s resigned"), WON_CALLFLAG: _("Because %(loser)s ran out of time"), WON_MATE: _("Because %(loser)s was checkmated"), WON_DISCONNECTION: _("Because %(loser)s disconnected"), WON_ADJUDICATION: _("Because of adjudication by an admin"), WON_NOMATERIAL: _("Because %(loser)s lost all pieces but the king"), ADJOURNED_LOST_CONNECTION: _("Because a player lost connection"), ADJOURNED_AGREEMENT: _("Because both players agreed to adjourn the game"), ADJOURNED_SERVER_SHUTDOWN: _("Because the server was shutdown"), ADJOURNED_COURTESY: _("Because a player lost connection and the other player requested adjournment"), ADJOURNED_COURTESY_WHITE: _("Because %(black)s lost connection to the server and %(white)s requested adjournment"), ADJOURNED_COURTESY_BLACK: _("Because %(white)s lost connection to the server and %(black)s requested adjournment"), ADJOURNED_LOST_CONNECTION_WHITE: _("Because %(white)s lost connection to the server"), ADJOURNED_LOST_CONNECTION_BLACK: _("Because %(black)s lost connection to the server"), ABORTED_ADJUDICATION: _("Because of adjudication by an admin"), ABORTED_AGREEMENT: _("Because the players agreed to"), ABORTED_COURTESY: _("Because of courtesy by a player"), ABORTED_EARLY: _("Because a player quit. No winner was found due to the early phase of the game"), ABORTED_SERVER_SHUTDOWN: _("Because the server was shutdown"), WHITE_ENGINE_DIED: _("Because the %(white)s engine died"), BLACK_ENGINE_DIED: _("Because the %(white)s engine died"), DISCONNECTED: _("Because the connection to the server was lost"), UNKNOWN_REASON: _("The reason is unknown") }
Python
from lutils.lmove import FILE, RANK class CordFormatException(Exception): pass class Cord: def __init__ (self, var1, var2 = None): """ Inits a new highlevel cord object. The cord B3 can be inited in the folowing ways: Cord(17), Cord("b3"), Cord(1,2), Cord("b",3) """ if var2 == None: if type(var1) == int: # We assume the format Cord(17) self.x = FILE(var1) self.y = RANK(var1) else: # We assume the format Cord("b3") self.x = self.charToInt(var1[0]) self.y = int(var1[1]) - 1 else: if type(var1) == str: # We assume the format Cord("b",3) self.x = self.charToInt(var1) self.y = var2 -1 else: # We assume the format Cord(1,2) self.x = var1 self.y = var2 def _get_cord (self): return self.y*8+self.x cord = property(_get_cord) def _get_cx (self): return self.intToChar(self.x) cx = property(_get_cx) def _get_cy (self): return str(self.y+1) cy = property(_get_cy) def intToChar (self, x): assert 0 <= x <= 7 return chr(x + ord('a')) def charToInt (self, char): a = ord(char) if ord('A') <= a <= ord('H'): a -= ord('A'); elif ord('a') <= a <= ord('h'): a -= ord('a'); else: raise CordFormatException, "x < 0 || x > 7 (%s, %d)" % (char, a) return a def _set_cords (self, (x, y)): self.x, self.y = x, y def _get_cords (self): return (self.x, self.y) cords = property(_get_cords, _set_cords) def __cmp__ (self, other): if other == None: return 1 if cmp (self.x, other.x): return cmp (self.x, other.x) if cmp (self.y, other.y): return cmp (self.y, other.y) return 0 def __eq__ (self, other): return other != None and other.x == self.x and other.y == self.y def __ne__ (self, other): return not self.__eq__(other) def __repr__ (self): return self.cx + self.cy def __hash__ (self): return self.x*8+self.y
Python
from collections import defaultdict from threading import RLock import traceback import cStringIO import datetime import Queue from gobject import SIGNAL_RUN_FIRST, TYPE_NONE, GObject from pychess.Savers.ChessFile import LoadingError from pychess.Players.Player import PlayerIsDead, TurnInterrupt from pychess.System.ThreadPool import PooledThread, pool from pychess.System.protoopen import protoopen, protosave, isWriteable from pychess.System.Log import log from pychess.Utils.Move import Move, toSAN from pychess.Variants.normal import NormalChess from pychess.Variants import variants from logic import getStatus, isClaimableDraw, playerHasMatingMaterial from const import * def undolocked (f): def newFunction(*args, **kw): self = args[0] log.debug("undolocked: adding func to queue: %s %s %s\n" % \ (repr(f), repr(args), repr(kw))) self.undoQueue.put((f, args, kw)) locked = self.undoLock.acquire(blocking=False) if locked: try: while True: try: func, args, kw = self.undoQueue.get_nowait() log.debug("undolocked: running queued func: %s %s %s\n" % \ (repr(func), repr(args), repr(kw))) func(*args, **kw) except Queue.Empty: break finally: self.undoLock.release() return newFunction def inthread (f): def newFunction(*args, **kw): pool.start(f, *args, **kw) return newFunction class GameModel (GObject, PooledThread): """ GameModel contains all available data on a chessgame. It also has the task of controlling players actions and moves """ __gsignals__ = { # game_started is emitted when control is given to the players for the # first time. Notice this is after players.start has been called. "game_started": (SIGNAL_RUN_FIRST, TYPE_NONE, ()), # game_changed is emitted when a move has been made. "game_changed": (SIGNAL_RUN_FIRST, TYPE_NONE, ()), # moves_undoig is emitted when a undoMoves call has been accepted, but # before anywork has been done to execute it. "moves_undoing": (SIGNAL_RUN_FIRST, TYPE_NONE, (int,)), # moves_undone is emitted after n moves have been undone in the # gamemodel and the players. "moves_undone": (SIGNAL_RUN_FIRST, TYPE_NONE, (int,)), # game_unended is emitted if moves have been undone, such that the game # which had previously ended, is now again active. "game_unended": (SIGNAL_RUN_FIRST, TYPE_NONE, ()), # game_loading is emitted if the GameModel is about to load in a chess # game from a file. "game_loading": (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)), # game_loaded is emitted after the chessformat handler has loaded in # all the moves from a file to the game model. "game_loaded": (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)), # game_saved is emitted in the end of model.save() "game_saved": (SIGNAL_RUN_FIRST, TYPE_NONE, (str,)), # game_ended is emitted if the models state has been changed to an # "ended state" "game_ended": (SIGNAL_RUN_FIRST, TYPE_NONE, (int,)), # game_terminated is emitted if the game was terminated. That is all # players and clocks were stopped, and it is no longer possible to # resume the game, even by undo. "game_terminated": (SIGNAL_RUN_FIRST, TYPE_NONE, ()), # game_paused is emitted if the game was successfully paused. "game_paused": (SIGNAL_RUN_FIRST, TYPE_NONE, ()), # game_paused is emitted if the game was successfully resumed from a # pause. "game_resumed": (SIGNAL_RUN_FIRST, TYPE_NONE, ()), # action_error is currently only emitted by ICGameModel, in the case # the "web model" didn't accept the action you were trying to do. "action_error": (SIGNAL_RUN_FIRST, TYPE_NONE, (object, int)), # players_changed is emitted if the players list was changed. "players_changed": (SIGNAL_RUN_FIRST, TYPE_NONE, ()), # spectators_changed is emitted if the spectators list was changed. "spectators_changed": (SIGNAL_RUN_FIRST, TYPE_NONE, ()), } def __init__ (self, timemodel=None, variant=NormalChess): GObject.__init__(self) self.variant = variant self.boards = [variant.board(setup=True)] self.moves = [] self.players = [] self.gameno = 0 self.variations = [self.boards] self.status = WAITING_TO_START self.reason = UNKNOWN_REASON self.timemodel = timemodel self.connections = defaultdict(list) # mainly for IC subclasses now = datetime.datetime.now() self.tags = { "Event": _("Local Event"), "Site": _("Local Site"), "Round": 1, "Year": now.year, "Month": now.month, "Day": now.day, "Time": "%02d:%02d:00" % (now.hour, now.minute), "Result": "*", } if self.timemodel: self.tags["TimeControl"] = \ "%d+%d" % (self.timemodel.minutes*60, self.timemodel.gain) # Notice: tags["WhiteClock"] and tags["BlackClock"] are never set # on the gamemodel, but simply written or read during saving/ # loading from pgn. If you want to know the time left for a player, # check the time model. # Keeps track of offers, so that accepts can be spotted self.offers = {} # True if the game has been changed since last save self.needsSave = False # The uri the current game was loaded from, or None if not a loaded game self.uri = None self.spectators = {} self.applyingMoveLock = RLock() self.undoLock = RLock() self.undoQueue = Queue.Queue() def __repr__ (self): s = "<GameModel at %s" % id(self) s += " (ply=%s" % self.ply if len(self.moves) > 0: s += ", move=%s" % self.moves[-1] s += ", variant=%s" % self.variant.name s += ", status=%s, reason=%s" % (str(self.status), str(self.reason)) s += ", players=%s" % str(self.players) s += ", tags=%s" % str(self.tags) if len(self.boards) > 0: s += "\nboard=%s" % self.boards[-1] return s + ")>" @property def display_text (self): if self.variant == NormalChess and self.timemodel is None: return "[ " + _("Untimed") + " ]" else: t = "[ " if self.variant != NormalChess: t += self.variant.name + " " if self.timemodel is not None: t += self.timemodel.display_text + " " return t + "]" def setPlayers (self, players): assert self.status == WAITING_TO_START self.players = players for player in self.players: self.connections[player].append(player.connect("offer", self.offerRecieved)) self.connections[player].append(player.connect("withdraw", self.withdrawRecieved)) self.connections[player].append(player.connect("decline", self.declineRecieved)) self.connections[player].append(player.connect("accept", self.acceptRecieved)) self.tags["White"] = str(self.players[WHITE]) self.tags["Black"] = str(self.players[BLACK]) self.emit("players_changed") def setSpectators (self, spectators): assert self.status == WAITING_TO_START self.spectators = spectators self.emit("spectators_changed") ############################################################################ # Board stuff # ############################################################################ def _get_ply (self): return self.boards[-1].ply ply = property(_get_ply) def _get_lowest_ply (self): return self.boards[0].ply lowply = property(_get_lowest_ply) def _get_curplayer (self): try: return self.players[self.getBoardAtPly(self.ply).color] except IndexError: log.error("%s %s\n" % (self.players, self.getBoardAtPly(self.ply).color)) raise curplayer = property(_get_curplayer) def _get_waitingplayer (self): try: return self.players[1 - self.getBoardAtPly(self.ply).color] except IndexError: log.error("%s %s\n" % (self.players, 1 - self.getBoardAtPly(self.ply).color)) raise waitingplayer = property(_get_waitingplayer) def _plyToIndex (self, ply): index = ply - self.lowply if index < 0: raise IndexError, "%s < %s\n" % (ply, self.lowply) return index def getBoardAtPly (self, ply): try: return self.boards[self._plyToIndex(ply)] except: log.error("%d\t%d\t%d\t%d\n" % (self.lowply, ply, self.ply, len(self.boards))) raise def getMoveAtPly (self, ply): try: return Move(self.boards[self._plyToIndex(ply)+1].board.history[-1][0]) except IndexError: log.error("%d\t%d\t%d\t%d\n" % (self.lowply, ply, self.ply, len(self.moves))) raise def isObservationGame (self): if self.players[0].__type__ == LOCAL or self.players[1].__type__ == LOCAL: return False else: return True def isMainlineBoard(self, ply): return self.getBoardAtPly(ply) in self.variations[0] ############################################################################ # Offer management # ############################################################################ def offerRecieved (self, player, offer): log.debug("GameModel.offerRecieved: offerer=%s %s\n" % (repr(player), offer)) if player == self.players[WHITE]: opPlayer = self.players[BLACK] else: opPlayer = self.players[WHITE] if offer.type == HURRY_ACTION: opPlayer.hurry() elif offer.type == CHAT_ACTION: opPlayer.putMessage(offer.param) elif offer.type == RESIGNATION: if player == self.players[WHITE]: self.end(BLACKWON, WON_RESIGN) else: self.end(WHITEWON, WON_RESIGN) elif offer.type == FLAG_CALL: assert self.timemodel is not None if self.timemodel.getPlayerTime(1-player.color) <= 0: if self.timemodel.getPlayerTime(player.color) <= 0: self.end(DRAW, DRAW_CALLFLAG) elif not playerHasMatingMaterial(self.boards[-1], 1-player.color): if 1-player.color == WHITE: self.end(DRAW, DRAW_BLACKINSUFFICIENTANDWHITETIME) else: self.end(DRAW, DRAW_WHITEINSUFFICIENTANDBLACKTIME) else: if player == self.players[WHITE]: self.end(WHITEWON, WON_CALLFLAG) else: self.end(BLACKWON, WON_CALLFLAG) else: player.offerError(offer, ACTION_ERROR_NOT_OUT_OF_TIME) elif offer.type == DRAW_OFFER and isClaimableDraw(self.boards[-1]): reason = getStatus(self.boards[-1])[1] self.end(DRAW, reason) elif offer.type == TAKEBACK_OFFER and offer.param < self.lowply: player.offerError(offer, ACTION_ERROR_TOO_LARGE_UNDO) elif offer.type in OFFERS: if offer not in self.offers: log.debug("GameModel.offerRecieved: doing %s.offer(%s)\n" % \ (repr(opPlayer), offer)) self.offers[offer] = player opPlayer.offer(offer) # If we updated an older offer, we want to delete the old one for offer_ in self.offers.keys(): if offer.type == offer_.type and offer != offer_: del self.offers[offer_] def withdrawRecieved (self, player, offer): log.debug("GameModel.withdrawRecieved: withdrawer=%s %s\n" % \ (repr(player), offer)) if player == self.players[WHITE]: opPlayer = self.players[BLACK] else: opPlayer = self.players[WHITE] if offer in self.offers and self.offers[offer] == player: del self.offers[offer] opPlayer.offerWithdrawn(offer) else: player.offerError(offer, ACTION_ERROR_NONE_TO_WITHDRAW) def declineRecieved (self, player, offer): log.debug("GameModel.declineRecieved: decliner=%s %s\n" % (repr(player), offer)) if player == self.players[WHITE]: opPlayer = self.players[BLACK] else: opPlayer = self.players[WHITE] if offer in self.offers and self.offers[offer] == opPlayer: del self.offers[offer] log.debug("GameModel.declineRecieved: declining %s\n" % offer) opPlayer.offerDeclined(offer) else: player.offerError(offer, ACTION_ERROR_NONE_TO_DECLINE) def acceptRecieved (self, player, offer): log.debug("GameModel.acceptRecieved: accepter=%s %s\n" % (repr(player), offer)) if player == self.players[WHITE]: opPlayer = self.players[BLACK] else: opPlayer = self.players[WHITE] if offer in self.offers and self.offers[offer] == opPlayer: if offer.type == DRAW_OFFER: self.end(DRAW, DRAW_AGREE) elif offer.type == TAKEBACK_OFFER: log.debug("GameModel.acceptRecieved: undoMoves(%s)\n" % \ (self.ply - offer.param)) self.undoMoves(self.ply - offer.param) elif offer.type == ADJOURN_OFFER: self.end(ADJOURNED, ADJOURNED_AGREEMENT) elif offer.type == ABORT_OFFER: self.end(ABORTED, ABORTED_AGREEMENT) elif offer.type == PAUSE_OFFER: self.pause() elif offer.type == RESUME_OFFER: self.resume() del self.offers[offer] else: player.offerError(offer, ACTION_ERROR_NONE_TO_ACCEPT) ############################################################################ # Data stuff # ############################################################################ def loadAndStart (self, uri, loader, gameno, position): assert self.status == WAITING_TO_START uriIsFile = type(uri) != str if not uriIsFile: chessfile = loader.load(protoopen(uri)) else: chessfile = loader.load(uri) self.gameno = gameno self.emit("game_loading", uri) try: chessfile.loadToModel(gameno, position, self, False) #Postpone error raising to make games loadable to the point of the error except LoadingError, e: error = e else: error = None if self.players: self.players[WHITE].setName(self.tags["White"]) self.players[BLACK].setName(self.tags["Black"]) self.emit("game_loaded", uri) self.needsSave = False if not uriIsFile: self.uri = uri else: self.uri = None # Even if the game "starts ended", the players should still be moved # to the last position, so analysis is correct, and a possible "undo" # will work as expected. for spectator in self.spectators.values(): spectator.setOptionInitialBoard(self) for player in self.players: player.setOptionInitialBoard(self) if self.timemodel: self.timemodel.setMovingColor(self.boards[-1].color) if self.status == RUNNING: if self.timemodel and self.ply >= 2: self.timemodel.start() self.status = WAITING_TO_START self.start() else: self.emit("game_started") if self.status == WHITEWON: self.emit("game_ended", self.reason) elif self.status == BLACKWON: self.emit("game_ended", self.reason) elif self.status == DRAW: self.emit("game_ended", self.reason) if error: raise error def save (self, uri, saver, append): if type(uri) == str: fileobj = protosave(uri, append) self.uri = uri else: fileobj = uri self.uri = None saver.save(fileobj, self) self.emit("game_saved", uri) self.needsSave = False ############################################################################ # Run stuff # ############################################################################ def run (self): log.debug("GameModel.run: Starting. self=%s\n" % self) # Avoid racecondition when self.start is called while we are in self.end if self.status != WAITING_TO_START: return self.status = RUNNING for player in self.players + self.spectators.values(): player.start() log.debug("GameModel.run: emitting 'game_started' self=%s\n" % self) self.emit("game_started") while self.status in (PAUSED, RUNNING, DRAW, WHITEWON, BLACKWON): curColor = self.boards[-1].color curPlayer = self.players[curColor] if self.timemodel: log.debug("GameModel.run: id=%s, players=%s, self.ply=%s: updating %s's time\n" % \ (id(self), str(self.players), str(self.ply), str(curPlayer))) curPlayer.updateTime(self.timemodel.getPlayerTime(curColor), self.timemodel.getPlayerTime(1-curColor)) try: log.debug("GameModel.run: id=%s, players=%s, self.ply=%s: calling %s.makeMove()\n" % \ (id(self), str(self.players), self.ply, str(curPlayer))) if self.ply > self.lowply: move = curPlayer.makeMove(self.boards[-1], self.moves[-1], self.boards[-2]) else: move = curPlayer.makeMove(self.boards[-1], None, None) log.debug("GameModel.run: id=%s, players=%s, self.ply=%s: got move=%s from %s\n" % \ (id(self), str(self.players), self.ply, move, str(curPlayer))) except PlayerIsDead, e: if self.status in (WAITING_TO_START, PAUSED, RUNNING): stringio = cStringIO.StringIO() traceback.print_exc(file=stringio) error = stringio.getvalue() log.error("GameModel.run: A Player died: player=%s error=%s\n%s" % (curPlayer, error, e)) if curColor == WHITE: self.kill(WHITE_ENGINE_DIED) else: self.kill(BLACK_ENGINE_DIED) break except TurnInterrupt: log.debug("GameModel.run: id=%s, players=%s, self.ply=%s: TurnInterrupt\n" % \ (id(self), str(self.players), self.ply)) continue log.debug("GameModel.run: id=%s, players=%s, self.ply=%s: acquiring self.applyingMoveLock\n" % \ (id(self), str(self.players), self.ply)) assert isinstance(move, Move), "%s" % repr(move) self.applyingMoveLock.acquire() try: log.debug("GameModel.run: id=%s, players=%s, self.ply=%s: applying move=%s\n" % \ (id(self), str(self.players), self.ply, str(move))) self.needsSave = True newBoard = self.boards[-1].move(move) newBoard.prev = self.boards[-1] if self.ply % 2 == 0: newBoard.movecount = str((self.ply+1)/2 + 1)+"." else: newBoard.movecount = "" self.boards = self.variations[0] self.boards[-1].next = newBoard self.boards.append(newBoard) self.moves.append(move) if self.timemodel: self.timemodel.tap() self.checkStatus() self.emit("game_changed") for spectator in self.spectators.values(): spectator.putMove(self.boards[-1], self.moves[-1], self.boards[-2]) finally: log.debug("GameModel.run: releasing self.applyingMoveLock\n") self.applyingMoveLock.release() def checkStatus (self): """ Updates self.status so it fits with what getStatus(boards[-1]) would return. That is, if the game is e.g. check mated this will call mode.end(), or if moves have been undone from an otherwise ended position, this will call __resume and emit game_unended. """ log.debug("GameModel.checkStatus:\n") status, reason = getStatus(self.boards[-1]) if status != RUNNING and self.status in (WAITING_TO_START, PAUSED, RUNNING): if not (status == DRAW and reason in (DRAW_REPITITION, DRAW_50MOVES)): self.end(status, reason) return if status != self.status and self.status in UNDOABLE_STATES \ and self.reason in UNDOABLE_REASONS: self.__resume() self.status = status self.reason = UNKNOWN_REASON self.emit("game_unended") def __pause (self): log.debug("GameModel.__pause: %s\n" % self) for player in self.players: player.pause() try: for spectator in self.spectators.values(): spectator.pause() except NotImplementedError: pass if self.timemodel: self.timemodel.pause() @inthread def pause (self): """ Players will raise NotImplementedError if they doesn't support pause. Spectators will be ignored. """ self.applyingMoveLock.acquire() try: self.__pause() self.status = PAUSED finally: self.applyingMoveLock.release() self.emit("game_paused") def __resume (self): for player in self.players: player.resume() try: for spectator in self.spectators.values(): spectator.resume() except NotImplementedError: pass if self.timemodel: self.timemodel.resume() self.emit("game_resumed") @inthread def resume (self): self.applyingMoveLock.acquire() try: self.status = RUNNING self.__resume() finally: self.applyingMoveLock.release() def end (self, status, reason): if self.status not in UNFINISHED_STATES: log.log("GameModel.end: Can't end a game that's already ended: %s %s\n" % (status, reason)) return if self.status not in (WAITING_TO_START, PAUSED, RUNNING): self.needsSave = True #log.debug("Ending a game with status %d for reason %d\n%s" % (status, reason, # "".join(traceback.format_list(traceback.extract_stack())).strip())) log.debug("GameModel.end: players=%s, self.ply=%s: Ending a game with status %d for reason %d\n" % \ (repr(self.players), str(self.ply), status, reason)) self.status = status self.reason = reason self.emit("game_ended", reason) self.__pause() def kill (self, reason): log.debug("GameModel.kill: players=%s, self.ply=%s: Killing a game for reason %d\n%s" % \ (repr(self.players), str(self.ply), reason, "".join(traceback.format_list(traceback.extract_stack())).strip())) self.status = KILLED self.reason = reason for player in self.players: player.end(self.status, reason) for spectator in self.spectators.values(): spectator.end(self.status, reason) if self.timemodel: self.timemodel.end() self.emit("game_ended", reason) def terminate (self): if self.status != KILLED: #self.resume() for player in self.players: player.end(self.status, self.reason) for spectator in self.spectators.values(): spectator.end(self.status, self.reason) if self.timemodel: self.timemodel.end() self.emit("game_terminated") ############################################################################ # Other stuff # ############################################################################ @inthread @undolocked def undoMoves (self, moves): """ Undo and remove moves number of moves from the game history from the GameModel, players, and any spectators """ if self.ply < 1 or moves < 1: return if self.ply - moves < 0: # There is no way in the current threaded/asynchronous design # for the GUI to know that the number of moves it requests to takeback # will still be valid once the undo is actually processed. So, until # we either add some locking or get a synchronous design, we quietly # "fix" the takeback request rather than cause AssertionError or IndexError moves = 1 log.debug("GameModel.undoMoves: players=%s, self.ply=%s, moves=%s, board=%s" % \ (repr(self.players), self.ply, moves, self.boards[-1])) log.debug("GameModel.undoMoves: acquiring self.applyingMoveLock\n") self.applyingMoveLock.acquire() log.debug("GameModel.undoMoves: self.applyingMoveLock acquired\n") try: self.emit("moves_undoing", moves) self.needsSave = True self.boards = self.variations[0] del self.boards[-moves:] del self.moves[-moves:] self.boards[-1].next = None for player in self.players: player.playerUndoMoves(moves, self) for spectator in self.spectators.values(): spectator.spectatorUndoMoves(moves, self) log.debug("GameModel.undoMoves: undoing timemodel\n") if self.timemodel: self.timemodel.undoMoves(moves) self.checkStatus() finally: log.debug("GameModel.undoMoves: releasing self.applyingMoveLock\n") self.applyingMoveLock.release() self.emit("moves_undone", moves) def isChanged (self): if self.ply == 0: return False if self.needsSave: return True if not self.uri or not isWriteable (self.uri): return True return False
Python
################################################################################ # This module is deprecated and uses no longer existing APIs. # After work has been made towards supporting general book formats, its # usefulness may also be disputed. ################################################################################ from pychess.System import tsqlite from pychess.System.ThreadPool import pool from pychess.System.prefix import addDataPrefix from pychess.Utils.const import * from time import time import atexit import os.path import re import sys path = os.path.join(addDataPrefix("open.db")) tsqlite.connect(path) atexit.register(tsqlite.close) def getOpenings (board): return tsqlite.execSQL ( "select move,wins,draws,loses from openings where fen = '%s'" % \ fen(board)) # # # CREATION # # # def stripBrackets (string): brackets = 0 end = 0 result = "" for i, c in enumerate(string): if c == '(': if brackets == 0: result += string[end:i] brackets += 1 elif c == ')': brackets -= 1 if brackets == 0: end = i+1 result += string[end:] return result if __name__ == "__main__": MAXMOVES = 14 PROFILE = False FILESMAX = 0 from pychess.Utils.Move import movePool, parseSAN, toSAN tagre = re.compile(r"\[([a-zA-Z]+)[ \t]+\"(.+?)\"\]") movre = re.compile(r"([a-hxOKQRBN0-8+#=-]{2,7})\s") comre = re.compile(r"(?:\{.*?\})|(?:;.*?[\n\r])|(?:\$[0-9]+)", re.DOTALL) resultDic = {"1-0":0, "1/2-1/2":1, "0-1":2} def load (file): files = [] inTags = False for line in file: if FILESMAX and len(files) > FILESMAX: break line = line.lstrip() if not line: continue elif line.startswith("%"): continue if line.startswith("["): if not inTags: files.append(["",""]) inTags = True files[-1][0] += line else: inTags = False files[-1][1] += line history = History(False) max = str(len(files)) start = time() for i, myFile in enumerate(files): number = str(i).rjust(len(max)) procent = ("%.1f%%" % (i/float(len(files))*100)).rjust(4) if i == 0: estimation = "N/A etr" speed = "N/A g/s" else: s = round((time()-start)/i*(len(files)-i)) estimation = ("%d:%02d etr" % (s / 60, s % 60)).rjust(5) speed = "%.2f g/s" % (i/(time()-start)) print "%s/%s: %s - %s (%s)" % (number, max, procent, estimation, speed) try: tags = dict(tagre.findall(myFile[0])) if not tags["Result"] in ("1/2-1/2", "1-0", "0-1"): continue moves = comre.sub("", myFile[1]) moves = stripBrackets(moves) moves = movre.findall(moves+" ") if moves[-1] in ("*", "1/2-1/2", "1-0", "0-1"): del moves[-1] except: # Could not parse game continue mcatch = [] if MAXMOVES: moves = moves[:MAXMOVES] for move in moves: try: m = parseSAN(history,move) except: continue epd = fen(history[-1]) res = resultDic[tags["Result"]] if epd.endswith("b"): res = 2-res history.add(m, False) yield epd, toSAN(history[-2], history[-1], history.moves[-1]), res mcatch.append(m) history.reset(False) for move in mcatch: movePool.add(move) del mcatch[:] # We can't use boardhash for dbkeys, as the boardhashes vary for each time Board.py is loaded. def fen (board): """ Returns a fenstring, only containing the two first fields, as the book is build in a such way. In next book this should probably be changed. """ return " ".join(board.asFen().split(" ")[:2]) def remake (): tsqlite.execSQL("drop table if exists openings") tsqlite.execSQL("create table openings( fen varchar(73), move varchar(7), \ wins int DEFAULT 0, draws int DEFAULT 0, loses int DEFAULT 0)") resd = ["wins","draws","loses"] sql1 = "select * from openings WHERE fen = '%s' AND move = '%s'" sql2 = "UPDATE openings SET %s = %s+1 WHERE fen = '%s' AND move = '%s'" sql3 = "INSERT INTO openings (fen,move,%s) VALUES ('%s','%s',1)" def toDb (fenstr, move, res): if tsqlite.execSQL (sql1 % (fenstr, move)): tsqlite.execSQL (sql2 % (res, res, fenstr, move)) else: tsqlite.execSQL (sql3 % (res, fenstr, move)) for fenstr, move, score in load(open(sys.argv[1])): pool.start(toDb,fenstr, move, resd[score]) for fen, move, w, l, d in tsqlite.execSQL ("select * from openings"): print fen.ljust(65), move.ljust(7), w, "\t", l, "\t", d tsqlite.close() if __name__ == "__main__": if not PROFILE: remake() else: import profile profile.run("remake()", "/tmp/pychessprofile") from pstats import Stats s = Stats("/tmp/pychessprofile") s.sort_stats("time") s.print_stats()
Python
""" This module contains chess logic functins for the pychess client. They are based upon the lutils modules, but supports standard object types and is therefore not as fast. """ from lutils import lmovegen from lutils.validator import validateMove from lutils.lmove import FCORD, TCORD from lutils import ldraw from Cord import Cord from Move import Move from const import * from lutils.bitboard import iterBits from lutils.attack import getAttacks from pychess.Variants.losers import testKingOnly def getDestinationCords (board, cord): tcords = [] for move in lmovegen.genAllMoves (board.board): if FCORD(move) == cord.cord: if not board.willLeaveInCheck (Move(move)): tcords.append(Cord(TCORD(move))) return tcords def repetitionCount (board): return ldraw.repetitionCount(board.board) def isClaimableDraw (board): lboard = board.board if ldraw.repetitionCount (lboard) >= 3: return True if ldraw.testFifty (lboard): return True return False def playerHasMatingMaterial (board, playercolor): lboard = board.board return ldraw.testPlayerMatingMaterial(lboard, playercolor) def getStatus (board): lboard = board.board if board.variant == LOSERSCHESS: if testKingOnly(lboard): if board.color == WHITE: status = WHITEWON else: status = BLACKWON return status, WON_NOMATERIAL else: if ldraw.testMaterial (lboard): return DRAW, DRAW_INSUFFICIENT if ldraw.repetitionCount (lboard) >= 3: return DRAW, DRAW_REPITITION if ldraw.testFifty (lboard): return DRAW, DRAW_50MOVES board_clone = lboard.clone() for move in lmovegen.genAllMoves (board_clone): board_clone.applyMove(move) if board_clone.opIsChecked(): board_clone.popMove() continue board_clone.popMove() return RUNNING, UNKNOWN_REASON if lboard.isChecked(): if board.variant == LOSERSCHESS: if board.color == WHITE: status = WHITEWON else: status = BLACKWON else: if board.color == WHITE: status = BLACKWON else: status = WHITEWON return status, WON_MATE if board.variant == LOSERSCHESS: if board.color == WHITE: status = WHITEWON else: status = BLACKWON return status, DRAW_STALEMATE else: return DRAW, DRAW_STALEMATE def standard_validate (board, move): return validateMove (board.board, move.move) and \ not board.willLeaveInCheck(move) def validate (board, move): if board.variant == LOSERSCHESS: capture = board[move.cord1] != None if capture: return standard_validate (board, move) else: can_capture = False can_escape = False ischecked = board.board.isChecked() for c in lmovegen.genCaptures(board.board): can_capture = True if ischecked: if not board.willLeaveInCheck(Move(c)): can_escape = True break else: break if can_capture: if ischecked and not can_escape: return standard_validate (board, move) else: return False else: return standard_validate (board, move) else: return standard_validate (board, move) def getMoveKillingKing (board): """ Returns a move from the current color, able to capture the opponent king """ lboard = board.board color = lboard.color opking = lboard.kings[1-color] for cord in iterBits (getAttacks(lboard, opking, color)): return Move(Cord(cord), Cord(opking), board) def genCastles (board): for move in lmovegen.genCastles(board.board): yield Move(move)
Python
from pychess.Utils.const import * import gobject class Rating (gobject.GObject): def __init__(self, ratingtype, elo, deviation=DEVIATION_NONE, wins=0, losses=0, draws=0, bestElo=0, bestTime=0): gobject.GObject.__init__(self) self.type = ratingtype for v in (elo, deviation, wins, losses, draws, bestElo, bestTime): assert v == None or type(v) == int, v self.elo = elo self.deviation = deviation self.wins = wins self.losses = losses self.draws = draws self.bestElo = bestElo self.bestTime = bestTime def get_elo (self): return self._elo def set_elo (self, elo): self._elo = elo elo = gobject.property(get_elo, set_elo) def __repr__ (self): r = "type=%s, elo=%s" % (self.type, self.elo) if self.deviation != None: r += ", deviation=%s" % str(self.deviation) if self.wins > 0: r += ", wins=%s" % str(self.wins) if self.losses > 0: r += ", losses=%s" % str(self.losses) if self.draws > 0: r += ", draws=%s" % str(self.draws) if self.bestElo > 0: r += ", bestElo=%s" % str(self.bestElo) if self.bestTime > 0: r += ", bestTime=%s" % str(self.bestTime) return r def copy (self): return Rating(self.type, self.elo, deviation=self.deviation, wins=self.wins, losses=self.losses, draws=self.draws, bestElo=self.bestElo, bestTime=self.bestTime) def update (self, rating): if self.type != rating.type: raise TypeError elif self.elo != rating.elo: self.elo = rating.elo elif self.deviation != rating.deviation: self.deviation = rating.deviation elif self.wins != rating.wins: self.wins = rating.wins elif self.losses != rating.losses: self.losses = rating.losses elif self.draws != rating.draws: self.draws = rating.draws elif self.bestElo != rating.bestElo: self.bestElo = rating.bestElo elif self.bestTime != rating.bestTime: self.bestTime = rating.bestTime
Python
from pychess.Utils.const import ACTIONS class Offer: def __init__(self, type_, param=None, index=None): assert type_ in ACTIONS, "Offer.__init__(): type not in ACTIONS: %s" % repr(type_) assert index is None or type(index) is int, \ "Offer.__init__(): index not int: %s" % repr(index) self.type = type_ self.param = param self.index = index # for IC games def __hash__(self): return hash((self.type, self.param, self.index)) def __cmp__(self, other): assert type(other) is type(self), "Offer.__cmp__(): not of type Offer: %s" % repr(other) return cmp(hash(self), hash(other)) def __repr__(self): s = "type=\"%s\"" % self.type if self.param is not None: s += ", param=%s" % str(self.param) if self.index is not None: s += ", index=%s" % str(self.index) return "Offer(" + s + ")"
Python
from array import array from pychess.Utils.const import * from pychess.Utils.repr import reprColor from ldata import * from attack import isAttacked from bitboard import * from threading import RLock from copy import deepcopy ################################################################################ # Zobrit hashing 32 bit implementation # ################################################################################ from sys import maxint from random import randint pieceHashes = [[[0]*64 for i in range(7)] for j in range(2)] for color in WHITE, BLACK: for piece in PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING: for cord in range(64): pieceHashes[color][piece][cord] = randint(0, maxint) epHashes = [] for cord in range(64): epHashes.append(randint(0, maxint)) W_OOHash = randint(0, maxint) W_OOOHash = randint(0, maxint) B_OOHash = randint(0, maxint) B_OOOHash = randint(0, maxint) # Will be set each time black is on move colorHash = randint(0, maxint) # 50 moves rule is not hashed, as it is so rarly used and would greatly damage # our transposition table. ################################################################################ # FEN # ################################################################################ # This will cause applyFen to raise an exception, if halfmove clock and fullmove # number is not specified STRICT_FEN = False ################################################################################ # LBoard # ################################################################################ class LBoard: def __init__ (self, variant): self.variant = variant self._reset() def _reset (self): self.blocker = createBoard(0) self.friends = [createBoard(0)]*2 self.kings = [-1]*2 self.boards = [[createBoard(0)]*7 for i in range(2)] self.enpassant = -1 self.color = WHITE self.castling = B_OOO | B_OO | W_OOO | W_OO self.hasCastled = [False, False] self.fifty = 0 self.checked = None self.opchecked = None self.arBoard = array("B", [0]*64) self.hash = 0 self.pawnhash = 0 ######################################################################## # The format of history is a list of tuples of the following fields # # move: The move that was applied to get the position # # tpiece: The piece the move captured, == EMPTY for normal moves # # enpassant: cord which can be captured by enpassant or None # # castling: The castling availability in the position # # hash: The hash of the position # # fifty: A counter for the fifty moves rule # # # # Early entries may be None instead of tuples if the information is # # not available (e.g. if the board was loaded from a position). # ######################################################################## self.history = [] # initial cords of rooks and kings for castling in Chess960 if self.variant == FISCHERRANDOMCHESS: self.ini_kings = [None, None] self.ini_rooks = [[None, None], [None, None]] else: self.ini_kings = [E1, E8] self.ini_rooks = [[A1, H1], [A8, H8]] def applyFen (self, fenstr): """ Applies the fenstring to the board. If the string is not properly written a SyntaxError will be raised, having its message ending in Pos(%d) specifying the string index of the problem. if an error is found, no changes will be made to the board. """ # Get information parts = fenstr.split() if len(parts) > 6: raise SyntaxError, "Can't have more than 6 fields in fenstr. "+ \ "Pos(%d)" % fenstr.find(parts[6]) if STRICT_FEN and len(parts) != 6: raise SyntaxError, "Needs 6 fields in fenstr. Pos(%d)" % len(fenstr) elif len(parts) < 4: raise SyntaxError, "Needs at least 6 fields in fenstr. Pos(%d)" % \ len(fenstr) elif len(parts) >= 6: pieceChrs, colChr, castChr, epChr, fiftyChr, moveNoChr = parts[:6] elif len(parts) == 5: pieceChrs, colChr, castChr, epChr, fiftyChr = parts moveNoChr = "1" else: pieceChrs, colChr, castChr, epChr = parts fiftyChr = "0" moveNoChr = "1" # Try to validate some information # TODO: This should be expanded and perhaps moved slashes = len([c for c in pieceChrs if c == "/"]) if slashes != 7: raise SyntaxError, "Needs 7 slashes in piece placement field. "+ \ "Pos(%d)" % fenstr.rfind("/") if not colChr.lower() in ("w", "b"): raise SyntaxError, "Active color field must be one of w or b. "+ \ "Pos(%d)" % fenstr.find(len(pieceChrs), colChr) if epChr != "-" and not epChr in cordDic: raise SyntaxError, ("En passant cord %s is not legal. "+ \ "Pos(%d) - %s") % (epChr, fenstr.rfind(epChr), \ fenstr) if (not 'k' in pieceChrs) or (not 'K' in pieceChrs): raise SyntaxError, "FEN needs at least 'k' and 'K' in piece placement field." # Reset this board self._reset() # Parse piece placement field for r, rank in enumerate(pieceChrs.split("/")): cord = (7-r)*8 for char in rank: if char.isdigit(): cord += int(char) else: color = char.islower() and BLACK or WHITE piece = reprSign.index(char.upper()) self._addPiece(cord, piece, color) cord += 1 if self.variant == FISCHERRANDOMCHESS: # Save ranks fo find outermost rooks # if KkQq was used in castling rights if r == 0: rank8 = rank elif r == 7: rank1 = rank # Parse active color field if colChr.lower() == "w": self.setColor (WHITE) else: self.setColor (BLACK) # Parse castling availability castling = 0 for char in castChr: if self.variant == FISCHERRANDOMCHESS: if char in reprFile: if char < reprCord[self.kings[BLACK]][0]: castling |= B_OOO self.ini_rooks[1][0] = reprFile.index(char) + 56 else: castling |= B_OO self.ini_rooks[1][1] = reprFile.index(char) + 56 self.ini_kings[BLACK] = self.kings[BLACK] elif char in [c.upper() for c in reprFile]: if char < reprCord[self.kings[WHITE]][0].upper(): castling |= W_OOO self.ini_rooks[0][0] = reprFile.index(char.lower()) else: castling |= W_OO self.ini_rooks[0][1] = reprFile.index(char.lower()) self.ini_kings[WHITE] = self.kings[WHITE] elif char == "K": castling |= W_OO self.ini_rooks[0][1] = rank1.rfind('R') self.ini_kings[WHITE] = self.kings[WHITE] elif char == "Q": castling |= W_OOO self.ini_rooks[0][0] = rank1.find('R') self.ini_kings[WHITE] = self.kings[WHITE] elif char == "k": castling |= B_OO self.ini_rooks[1][1] = rank8.rfind('r') self.ini_kings[BLACK] = self.kings[BLACK] elif char == "q": castling |= B_OOO self.ini_rooks[1][0] = rank8.find('r') self.ini_kings[BLACK] = self.kings[BLACK] else: if char == "K": castling |= W_OO elif char == "Q": castling |= W_OOO elif char == "k": castling |= B_OO elif char == "q": castling |= B_OOO self.setCastling(castling) # Parse en passant target sqaure if epChr == "-": self.setEnpassant (None) else: self.setEnpassant(cordDic[epChr]) # Parse halfmove clock field self.fifty = max(int(fiftyChr),0) # Parse fullmove number movenumber = int(moveNoChr)*2 -2 if self.color == BLACK: movenumber += 1 self.history = [None]*movenumber self.updateBoard() def isChecked (self): if self.checked == None: kingcord = self.kings[self.color] self.checked = isAttacked (self, kingcord, 1-self.color) return self.checked def opIsChecked (self): if self.opchecked == None: kingcord = self.kings[1-self.color] self.opchecked = isAttacked (self, kingcord, self.color) return self.opchecked def _addPiece (self, cord, piece, color): self.boards[color][piece] = \ setBit(self.boards[color][piece], cord) if piece == PAWN: #assert not (color == WHITE and cord > 55) #assert not (color == BLACK and cord < 8) self.pawnhash ^= pieceHashes[color][PAWN][cord] elif piece == KING: self.kings[color] = cord self.hash ^= pieceHashes[color][piece][cord] self.arBoard[cord] = piece def _removePiece (self, cord, piece, color): self.boards[color][piece] = \ clearBit(self.boards[color][piece], cord) if piece == PAWN: self.pawnhash ^= pieceHashes[color][PAWN][cord] self.hash ^= pieceHashes[color][piece][cord] self.arBoard[cord] = EMPTY def _move (self, fcord, tcord, piece, color): """ Moves the piece at fcord to tcord. """ self._removePiece(fcord, piece, color) self._addPiece(tcord, piece, color) def updateBoard (self): self.friends[WHITE] = sum(self.boards[WHITE]) self.friends[BLACK] = sum(self.boards[BLACK]) self.blocker = self.friends[WHITE] | self.friends[BLACK] def setColor (self, color): if color == self.color: return self.color = color self.hash ^= colorHash self.pawnhash ^= colorHash def setCastling (self, castling): if self.castling == castling: return if castling & W_OO != self.castling & W_OO: self.hash ^= W_OOHash if castling & W_OOO != self.castling & W_OOO: self.hash ^= W_OOOHash if castling & B_OO != self.castling & B_OO: self.hash ^= B_OOHash if castling & B_OOO != self.castling & B_OOO: self.hash ^= B_OOOHash self.castling = castling def setEnpassant (self, epcord): if self.enpassant == epcord: return if self.enpassant != None: self.hash ^= epHashes[self.enpassant] if epcord != None: self.hash ^= epHashes[epcord] self.enpassant = epcord def applyMove (self, move): flag = move >> 12 fcord = (move >> 6) & 63 tcord = move & 63 fpiece = self.arBoard[fcord] tpiece = self.arBoard[tcord] opcolor = 1-self.color # Update history self.history.append ( (move, tpiece, self.enpassant, self.castling, self.hash, self.fifty, self.checked, self.opchecked) ) self.opchecked = None self.checked = None # Capture if tpiece != EMPTY: if self.variant == FISCHERRANDOMCHESS: # don't capture _our_ piece when castling king steps on rook! if flag not in (KING_CASTLE, QUEEN_CASTLE): self._removePiece(tcord, tpiece, opcolor) else: self._removePiece(tcord, tpiece, opcolor) if fpiece == PAWN: if flag == ENPASSANT: takenPawnC = tcord + (self.color == WHITE and -8 or 8) self._removePiece (takenPawnC, PAWN, opcolor) elif flag in PROMOTIONS: piece = flag - 2 # The flags has values: 7, 6, 5, 4 self._removePiece(fcord, PAWN, self.color) self._addPiece(tcord, piece, self.color) if fpiece == PAWN and abs(fcord-tcord) == 16: self.setEnpassant ((fcord + tcord) / 2) else: self.setEnpassant (None) if flag in (KING_CASTLE, QUEEN_CASTLE): if flag == QUEEN_CASTLE: if self.variant == FISCHERRANDOMCHESS: if self.color == WHITE: rookf = self.ini_rooks[0][0] rookt = D1 else: rookf = self.ini_rooks[1][0] rookt = D8 # don't move our rook yet else: rookf = fcord - 4 rookt = fcord - 1 self._move (rookf, rookt, ROOK, self.color) else: if self.variant == FISCHERRANDOMCHESS: if self.color == WHITE: rookf = self.ini_rooks[0][1] rookt = F1 else: rookf = self.ini_rooks[1][1] rookt = F8 # don't move our rook yet else: rookf = fcord + 3 rookt = fcord + 1 self._move (rookf, rookt, ROOK, self.color) self.hasCastled[self.color] = True if tpiece == EMPTY and fpiece != PAWN and \ not flag in (KING_CASTLE, QUEEN_CASTLE): self.fifty += 1 else: self.fifty = 0 # Clear castle flags if self.color == WHITE: if fpiece == KING: if self.castling & W_OOO: self.hash ^= W_OOOHash self.castling &= ~W_OOO if self.castling & W_OO: self.hash ^= W_OOHash self.castling &= ~W_OO if fpiece == ROOK: if fcord == self.ini_rooks[0][1]: #H1 if self.castling & W_OO: self.hash ^= W_OOHash self.castling &= ~W_OO elif fcord == self.ini_rooks[0][0]: #A1 if self.castling & W_OOO: self.hash ^= W_OOOHash self.castling &= ~W_OOO if tpiece == ROOK: if tcord == self.ini_rooks[1][1]: #H8 if self.castling & B_OO: self.hash ^= B_OOHash self.castling &= ~B_OO elif tcord == self.ini_rooks[1][0]: #A8 if self.castling & B_OOO: self.hash ^= B_OOOHash self.castling &= ~B_OOO else: if fpiece == KING: if self.castling & B_OOO: self.hash ^= B_OOOHash self.castling &= ~B_OOO if self.castling & B_OO: self.hash ^= B_OOHash self.castling &= ~B_OO if fpiece == ROOK: if fcord == self.ini_rooks[1][1]: #H8 if self.castling & B_OO: self.hash ^= B_OOHash self.castling &= ~B_OO elif fcord == self.ini_rooks[1][0]: #A8 if self.castling & B_OOO: self.hash ^= B_OOOHash self.castling &= ~B_OOO if tpiece == ROOK: if tcord == self.ini_rooks[0][1]: #H1 if self.castling & W_OO: self.hash ^= W_OOHash self.castling &= ~W_OO elif tcord == self.ini_rooks[0][0]: #A1 if self.castling & W_OOO: self.hash ^= W_OOOHash self.castling &= ~W_OOO if not flag in PROMOTIONS: if self.variant == FISCHERRANDOMCHESS: if flag in (KING_CASTLE, QUEEN_CASTLE): if tpiece == EMPTY: self._move(fcord, tcord, KING, self.color) self._move(rookf, rookt, ROOK, self.color) else: self._removePiece(rookf, ROOK, self.color) if flag == KING_CASTLE: self._move(fcord, rookt+1, KING, self.color) else: self._move(fcord, rookt-1, KING, self.color) self._addPiece(rookt, ROOK, self.color) else: self._move(fcord, tcord, fpiece, self.color) else: self._move(fcord, tcord, fpiece, self.color) self.setColor(opcolor) self.updateBoard () return move # Move is returned with the captured piece flag set def popMove (self): # Note that we remove the last made move, which was not made by boards # current color, but by its opponent color = 1 - self.color opcolor = self.color # Get information from history move, cpiece, enpassant, castling, \ hash, fifty, checked, opchecked = self.history.pop() flag = move >> 12 fcord = (move >> 6) & 63 tcord = move & 63 tpiece = self.arBoard[tcord] if self.variant == FISCHERRANDOMCHESS: if flag in (KING_CASTLE, QUEEN_CASTLE): if color == WHITE: if flag == QUEEN_CASTLE: rookf = self.ini_rooks[0][0] rookt = D1 else: rookf = self.ini_rooks[0][1] rookt = F1 else: if flag == QUEEN_CASTLE: rookf = self.ini_rooks[1][0] rookt = D8 else: rookf = self.ini_rooks[1][1] rookt = F8 if cpiece == EMPTY: self._removePiece (tcord, KING, color) else: if flag == KING_CASTLE: self._removePiece (rookt+1, KING, color) else: self._removePiece (rookt-1, KING, color) else: self._removePiece (tcord, tpiece, color) else: self._removePiece (tcord, tpiece, color) # Put back rook moved by castling if flag in (KING_CASTLE, QUEEN_CASTLE): if self.variant == FISCHERRANDOMCHESS: self._move (rookt, rookf, ROOK, color) else: if flag == QUEEN_CASTLE: rookf = fcord - 4 rookt = fcord - 1 else: rookf = fcord + 3 rookt = fcord + 1 self._move (rookt, rookf, ROOK, color) self.hasCastled[color] = False # Put back captured piece if cpiece != EMPTY: if flag in PROMOTIONS: self._addPiece (tcord, cpiece, opcolor) self._addPiece (fcord, PAWN, color) else: if self.variant == FISCHERRANDOMCHESS: if flag in (KING_CASTLE, QUEEN_CASTLE): if flag == KING_CASTLE: self._addPiece (fcord, KING, color) else: self._addPiece (fcord, KING, color) else: self._addPiece (tcord, cpiece, opcolor) self._addPiece (fcord, tpiece, color) else: self._addPiece (tcord, cpiece, opcolor) self._addPiece (fcord, tpiece, color) # Put back piece captured by enpassant elif flag == ENPASSANT: epcord = color == WHITE and tcord - 8 or tcord + 8 self._addPiece (epcord, PAWN, opcolor) self._addPiece (fcord, PAWN, color) # Put back promoted pawn elif flag in PROMOTIONS: self._addPiece (fcord, PAWN, color) # Put back moved piece else: self._addPiece (fcord, tpiece, color) self.setColor(color) self.updateBoard () self.checked = checked self.opchecked = opchecked self.enpassant = enpassant self.castling = castling self.hash = hash self.fifty = fifty def __hash__ (self): return self.hash def reprCastling (self): if not self.castling: return "-" else: strs = [] if self.variant == FISCHERRANDOMCHESS: if self.castling & W_OO: strs.append(reprCord[self.ini_rooks[0][1]][0].upper()) if self.castling & W_OOO: strs.append(reprCord[self.ini_rooks[0][0]][0].upper()) if self.castling & B_OO: strs.append(reprCord[self.ini_rooks[1][1]][0]) if self.castling & B_OOO: strs.append(reprCord[self.ini_rooks[1][0]][0]) else: if self.castling & W_OO: strs.append("K") if self.castling & W_OOO: strs.append("Q") if self.castling & B_OO: strs.append("k") if self.castling & B_OOO: strs.append("q") return "".join(strs) def __repr__ (self): b = reprColor[self.color] + " " b += self.reprCastling() + " " b += self.enpassant != None and reprCord[self.enpassant] or "-" b += "\n" rows = [self.arBoard[i:i+8] for i in range(0,64,8)][::-1] for r, row in enumerate(rows): for i, piece in enumerate(row): if piece != EMPTY: sign = reprSign[piece] if bitPosArray[(7-r)*8+i] & self.friends[WHITE]: sign = sign.upper() else: sign = sign.lower() b += sign else: b += "." b += " " b += "\n" return b def asFen (self, useXFen=False): fenstr = [] rows = [self.arBoard[i:i+8] for i in range(0,64,8)][::-1] for r, row in enumerate(rows): empty = 0 for i, piece in enumerate(row): if piece != EMPTY: if empty > 0: fenstr.append(str(empty)) empty = 0 sign = reprSign[piece] if bitPosArray[(7-r)*8+i] & self.friends[WHITE]: sign = sign.upper() else: sign = sign.lower() fenstr.append(sign) else: empty += 1 if empty > 0: fenstr.append(str(empty)) if r != 7: fenstr.append("/") fenstr.append(" ") fenstr.append(self.color == WHITE and "w" or "b") fenstr.append(" ") fenstr.append(self.reprCastling()) fenstr.append(" ") if not self.enpassant: fenstr.append("-") else: fwdPawns = self.boards[self.color][PAWN] if self.color == WHITE: fwdPawns >>= 8 else: fwdPawns <<= 8 pawnTargets = (fwdPawns & ~fileBits[0]) << 1; pawnTargets |= (fwdPawns & ~fileBits[7]) >> 1; if useXFen and not pawnTargets & bitPosArray[self.enpassant]: fenstr.append("-") else: fenstr.append(reprCord[self.enpassant]) fenstr.append(" ") fenstr.append(str(self.fifty)) fenstr.append(" ") fullmove = (len(self.history))/2 + 1 fenstr.append(str(fullmove)) return "".join(fenstr) def clone (self): copy = LBoard(self.variant) copy.blocker = self.blocker copy.friends = self.friends[:] copy.kings = self.kings[:] copy.boards = [self.boards[WHITE][:], self.boards[BLACK][:]] copy.enpassant = self.enpassant copy.color = self.color copy.castling = self.castling copy.hasCastled = self.hasCastled[:] copy.fifty = self.fifty copy.checked = self.checked copy.opchecked = self.opchecked copy.arBoard = self.arBoard[:] copy.hash = self.hash copy.pawnhash = self.pawnhash # We don't need to deepcopy the tupples, as they are imutable copy.history = self.history[:] copy.ini_kings = self.ini_kings[:] copy.ini_rooks = [self.ini_rooks[0][:], self.ini_rooks[1][:]] return copy
Python
from bitboard import * from attack import * from pychess.Utils.const import * from lmove import newMove ################################################################################ # Generate all moves # ################################################################################ def genCastles (board): def generateOne (color, rooknum, king_after, rook_after): if rooknum == 0: castle = QUEEN_CASTLE else: castle = KING_CASTLE king = board.ini_kings[color] rook = board.ini_rooks[color][rooknum] blocker = clearBit(clearBit(board.blocker, king), rook) stepover = fromToRay[king][king_after] | fromToRay[rook][rook_after] if not stepover & blocker: for cord in xrange(min(king,king_after), max(king,king_after)+1): if isAttacked (board, cord, 1-color): return return newMove (king, king_after, castle) if board.color == WHITE: if board.castling & W_OO: move = generateOne (WHITE, 1, G1, F1) if move: yield move if board.castling & W_OOO: move = generateOne (WHITE, 0, C1, D1) if move: yield move else: if board.castling & B_OO: move = generateOne (BLACK, 1, G8, F8) if move: yield move if board.castling & B_OOO: move = generateOne (BLACK, 0, C8, D8) if move: yield move def genAllMoves (board): blocker = board.blocker notblocker = ~blocker enpassant = board.enpassant friends = board.friends[board.color] notfriends = ~friends enemies = board.friends[1- board.color] pawns = board.boards[board.color][PAWN] knights = board.boards[board.color][KNIGHT] bishops = board.boards[board.color][BISHOP] rooks = board.boards[board.color][ROOK] queens = board.boards[board.color][QUEEN] kings = board.boards[board.color][KING] # Knights knightMoves = moveArray[KNIGHT] for cord in iterBits(knights): for c in iterBits(knightMoves[cord] & notfriends): yield newMove(cord, c) # King kingMoves = moveArray[KING] cord = firstBit( kings ) for c in iterBits(kingMoves[cord] & notfriends): yield newMove(cord, c) # Rooks and Queens for cord in iterBits(rooks | queens): attackBoard = attack00[cord][ray00[cord] & blocker] | \ attack90[cord][ray90[cord] & blocker] for c in iterBits(attackBoard & notfriends): yield newMove(cord, c) # Bishops and Queens for cord in iterBits(bishops | queens): attackBoard = attack45 [cord][ray45 [cord] & blocker] | \ attack135[cord][ray135[cord] & blocker] for c in iterBits(attackBoard & notfriends): yield newMove(cord, c) # White pawns pawnEnemies = enemies | (enpassant != None and bitPosArray[enpassant] or 0) if board.color == WHITE: # One step movedpawns = (pawns >> 8) & notblocker # Move all pawns one step forward for cord in iterBits(movedpawns): if cord >= 56: for p in PROMOTIONS: yield newMove(cord-8, cord, p) else: #if (cord-8, cord) == (33, 41): # print repr(board) #print toString(pawns) yield newMove (cord-8, cord) # Two steps seccondrow = pawns & rankBits[1] # Get seccond row pawns movedpawns = (seccondrow >> 8) & notblocker # Move two steps forward, while movedpawns = (movedpawns >> 8) & notblocker # ensuring middle cord is clear for cord in iterBits(movedpawns): yield newMove (cord-16, cord) # Capture left capLeftPawns = pawns & ~fileBits[0] capLeftPawns = (capLeftPawns >> 7) & pawnEnemies for cord in iterBits(capLeftPawns): if cord >= 56: for p in PROMOTIONS: yield newMove(cord-7, cord, p) elif cord == enpassant: yield newMove (cord-7, cord, ENPASSANT) else: yield newMove (cord-7, cord) # Capture right capRightPawns = pawns & ~fileBits[7] capRightPawns = (capRightPawns >> 9) & pawnEnemies for cord in iterBits(capRightPawns): if cord >= 56: for p in PROMOTIONS: yield newMove(cord-9, cord, p) elif cord == enpassant: yield newMove (cord-9, cord, ENPASSANT) else: yield newMove (cord-9, cord) # Black pawns else: # One step movedpawns = (pawns << 8) & notblocker for cord in iterBits(movedpawns): if cord <= 7: for p in PROMOTIONS: yield newMove(cord+8, cord, p) else: yield newMove (cord+8, cord) # Two steps seccondrow = pawns & rankBits[6] # Get seventh row pawns # Move two steps forward, while ensuring middle cord is clear movedpawns = seccondrow << 8 & notblocker movedpawns = movedpawns << 8 & notblocker for cord in iterBits(movedpawns): yield newMove (cord+16, cord) # Capture left capLeftPawns = pawns & ~fileBits[7] capLeftPawns = capLeftPawns << 7 & pawnEnemies for cord in iterBits(capLeftPawns): if cord <= 7: for p in PROMOTIONS: yield newMove(cord+7, cord, p) elif cord == enpassant: yield newMove (cord+7, cord, ENPASSANT) else: yield newMove (cord+7, cord) # Capture right capRightPawns = pawns & ~fileBits[0] capRightPawns = capRightPawns << 9 & pawnEnemies for cord in iterBits(capRightPawns): if cord <= 7: for p in PROMOTIONS: yield newMove(cord+9, cord, p) elif cord == enpassant: yield newMove (cord+9, cord, ENPASSANT) else: yield newMove (cord+9, cord) # Castling for m in genCastles(board): yield m ################################################################################ # Generate capturing moves # ################################################################################ def genCaptures (board): blocker = board.blocker notblocker = ~blocker enpassant = board.enpassant friends = board.friends[board.color] notfriends = ~friends enemies = board.friends[1- board.color] pawns = board.boards[board.color][PAWN] knights = board.boards[board.color][KNIGHT] bishops = board.boards[board.color][BISHOP] rooks = board.boards[board.color][ROOK] queens = board.boards[board.color][QUEEN] kings = board.boards[board.color][KING] # Knights knightMoves = moveArray[KNIGHT] for cord in iterBits(knights): for c in iterBits(knightMoves[cord] & enemies): yield newMove(cord, c) # King kingMoves = moveArray[KING] cord = firstBit( kings ) for c in iterBits(kingMoves[cord] & enemies): yield newMove(cord, c) # Rooks and Queens for cord in iterBits(rooks|queens): attackBoard = attack00[cord][ray00[cord] & blocker] | \ attack90[cord][ray90[cord] & blocker] for c in iterBits(attackBoard & enemies): yield newMove(cord, c) # Bishops and Queens for cord in iterBits(bishops|queens): attackBoard = attack45 [cord][ray45 [cord] & blocker] | \ attack135[cord][ray135[cord] & blocker] for c in iterBits(attackBoard & enemies): yield newMove(cord, c) # White pawns pawnEnemies = enemies | (enpassant != None and bitPosArray[enpassant] or 0) if board.color == WHITE: # Promotes movedpawns = (pawns >> 8) & notblocker & rankBits[7] #for cord in iterBits(movedpawns): # for p in PROMOTIONS: # yield newMove(cord-8, cord, p) # Capture left capLeftPawns = pawns & ~fileBits[0] capLeftPawns = (capLeftPawns >> 7) & pawnEnemies for cord in iterBits(capLeftPawns): if cord >= 56: for p in PROMOTIONS: yield newMove(cord-7, cord, p) elif cord == enpassant: yield newMove (cord-7, cord, ENPASSANT) else: yield newMove (cord-7, cord) # Capture right capRightPawns = pawns & ~fileBits[7] capRightPawns = (capRightPawns >> 9) & pawnEnemies for cord in iterBits(capRightPawns): if cord >= 56: for p in PROMOTIONS: yield newMove(cord-9, cord, p) elif cord == enpassant: yield newMove (cord-9, cord, ENPASSANT) else: yield newMove (cord-9, cord) # Black pawns else: # One step movedpawns = pawns << 8 & notblocker & rankBits[0] #for cord in iterBits(movedpawns): # for p in PROMOTIONS: # yield newMove(cord+8, cord, p) # Capture left capLeftPawns = pawns & ~fileBits[7] capLeftPawns = capLeftPawns << 7 & pawnEnemies for cord in iterBits(capLeftPawns): if cord <= 7: for p in PROMOTIONS: yield newMove(cord+7, cord, p) elif cord == enpassant: yield newMove (cord+7, cord, ENPASSANT) else: yield newMove (cord+7, cord) # Capture right capRightPawns = pawns & ~fileBits[0] capRightPawns = capRightPawns << 9 & pawnEnemies for cord in iterBits(capRightPawns): if cord <= 7: for p in PROMOTIONS: yield newMove(cord+9, cord, p) elif cord == enpassant: yield newMove (cord+9, cord, ENPASSANT) else: yield newMove (cord+9, cord) def genNonCaptures (board): blocker = board.blocker notblocker = ~blocker enpassant = board.enpassant friends = board.friends[board.color] notfriends = ~friends enemies = board.friends[1- board.color] pawns = board.boards[board.color][PAWN] knights = board.boards[board.color][KNIGHT] bishops = board.boards[board.color][BISHOP] rooks = board.boards[board.color][ROOK] queens = board.boards[board.color][QUEEN] kings = board.boards[board.color][KING] # Knights knightMoves = moveArray[KNIGHT] for cord in iterBits(knights): for c in iterBits(knightMoves[cord] & notblocker): yield newMove(cord, c) # King kingMoves = moveArray[KING] cord = firstBit( kings ) for c in iterBits(kingMoves[cord] & notblocker): yield newMove(cord, c) # Rooks and Queens for cord in iterBits(rooks): attackBoard = attack00[cord][ray00[cord] & blocker] | \ attack90[cord][ray90[cord] & blocker] for c in iterBits(attackBoard & notblocker): yield newMove(cord, c) # Bishops and Queens for cord in iterBits(bishops): attackBoard = attack45 [cord][ray45 [cord] & blocker] | \ attack135[cord][ray135[cord] & blocker] for c in iterBits(attackBoard & notblocker): yield newMove(cord, c) # White pawns if board.color == WHITE: # One step movedpawns = (pawns >> 8) & ~rankBits[7] for cord in iterBits(movedpawns): yield newMove (cord-8, cord) # Two steps seccondrow = pawns & rankBits[1] # Get seccond row pawns movedpawns = (seccondrow >> 8) & notblocker # Move two steps forward, while movedpawns = (movedpawns >> 8) & notblocker # ensuring middle cord is clear for cord in iterBits(movedpawns): yield newMove (cord-16, cord) # Black pawns else: # One step movedpawns = pawns << 8 & notblocker & ~rankBits[0] for cord in iterBits(movedpawns): yield newMove (cord+8, cord) # Two steps seccondrow = pawns & rankBits[6] # Get seventh row pawns # Move two steps forward, while ensuring middle cord is clear movedpawns = seccondrow << 8 & notblocker movedpawns = movedpawns << 8 & notblocker for cord in iterBits(movedpawns): yield newMove (cord+16, cord) # Castling for move in genCastles(board): yield move ################################################################################ # Generate escapes from check # ################################################################################ def genCheckEvasions (board): color = board.color opcolor = 1-color kcord = board.kings[color] kings = board.boards[color][KING] pawns = board.boards[color][PAWN] checkers = getAttacks (board, kcord, opcolor) arBoard = board.arBoard if bitLength(checkers) == 1: # Captures of checking pieces (except by king, which we will test later) chkcord = firstBit (checkers) b = getAttacks (board, chkcord, color) & ~kings for cord in iterBits(b): if not pinnedOnKing (board, cord, color): if arBoard[cord] == PAWN and \ (chkcord <= H1 or chkcord >= A8): for p in PROMOTIONS: yield newMove(cord, chkcord, p) else: yield newMove (cord, chkcord) # Maybe enpassant can help if board.enpassant: ep = board.enpassant if ep + (color == WHITE and -8 or 8) == chkcord: bits = moveArray[color == WHITE and BPAWN or PAWN][ep] & pawns for cord in iterBits (bits): if not pinnedOnKing (board, cord, color): yield newMove (cord, ep, ENPASSANT) # Lets block/capture the checking piece if sliders[arBoard[chkcord]]: bits = clearBit(fromToRay[kcord][chkcord], chkcord) for cord in iterBits (bits): b = getAttacks (board, cord, color) b &= ~(kings | pawns) # Add in pawn advances if color == WHITE and cord > H2: if bitPosArray[cord-8] & pawns: b |= bitPosArray[cord-8] if cord >> 3 == 3 and arBoard[cord-8] == EMPTY and \ bitPosArray[cord-16] & pawns: b |= bitPosArray[cord-16] elif color == BLACK and cord < H7: if bitPosArray[cord+8] & pawns: b |= bitPosArray[cord+8] if cord >> 3 == 4 and arBoard[cord+8] == EMPTY and \ bitPosArray[cord+16] & pawns: b |= bitPosArray[cord+16] for fcord in iterBits (b): # If the piece is blocking another attack, we cannot move it if pinnedOnKing (board, fcord, color): continue if arBoard[fcord] == PAWN and (cord > H7 or cord < A2): for p in PROMOTIONS: yield newMove(fcord, cord, p) else: yield newMove (fcord, cord) # If more than one checkers, move king to get out of check if checkers: escapes = moveArray[KING][kcord] & ~board.friends[color] else: escapes = 0 for chkcord in iterBits (checkers): dir = directions[chkcord][kcord] if sliders[arBoard[chkcord]]: escapes &= ~rays[chkcord][dir] for cord in iterBits (escapes): if not isAttacked (board, cord, opcolor): yield newMove (kcord, cord)
Python
from attack import getAttacks, staticExchangeEvaluate from pychess.Utils.eval import pos as positionValues from sys import maxint from ldata import * def getCaptureValue (board, move): mpV = PIECE_VALUES[board.arBoard[move>>6 & 63]] cpV = PIECE_VALUES[board.arBoard[move & 63]] if mpV < cpV: return cpV - mpV else: temp = staticExchangeEvaluate (board, move) return temp < 0 and -maxint or temp def sortCaptures (board, moves): f = lambda move: getCaptureValue (board, move) moves.sort(key=f, reverse=True) return moves def getMoveValue (board, table, depth, move): """ Sort criteria is as follows. 1. The move from the hash table 2. Captures as above. 3. Killers. 4. History. 5. Moves to the centre. """ # As we only return directly from transposition table if hashf == hashfEXACT # There could be a non hashfEXACT very promising move for us to test if table.isHashMove(depth, move): return maxint fcord = (move >> 6) & 63 tcord = move & 63 arBoard = board.arBoard fpiece = arBoard[fcord] tpiece = arBoard[tcord] if tpiece != EMPTY: # We add some extra to ensure also bad captures will be searched early return PIECE_VALUES[tpiece] - PIECE_VALUES[fpiece] + 1000 flag = move >> 12 if flag in PROMOTIONS: return PIECE_VALUES[flag-3] - PAWN_VALUE + 1000 killervalue = table.isKiller(depth, move) if killervalue: return 1000 + killervalue # King tropism - a move that brings us nearer to the enemy king, is probably # a good move #opking = board.kings[1-board.color] #score = distance[fpiece][fcord][opking] - distance[fpiece][tcord][opking] if fpiece not in positionValues: # That is, fpiece == EMPTY print fcord, tcord print repr(board) score = positionValues[fpiece][board.color][tcord] - \ positionValues[fpiece][board.color][fcord] # History heuristic score += table.getButterfly(move) return score def sortMoves (board, table, ply, hashmove, moves): f = lambda move: getMoveValue (board, table, ply, hashmove, move) moves.sort(key=f, reverse=True) return moves
Python
import urllib import re from pychess.Utils.lutils.lmove import newMove, FILE, RANK from pychess.Utils.const import * from pychess.Utils.repr import reprColor from pychess.Utils.lutils.bitboard import bitLength from pychess.System.Log import log URL = "http://www.k4it.de/egtb/fetch.php?action=egtb&fen=" expression = re.compile("(\d+)-(\d+)-?(\d+)?: (Win in \d+|Draw|Lose in \d+)") PROMOTION_FLAGS = { 2: QUEEN_PROMOTION, 3: ROOK_PROMOTION, 4: BISHOP_PROMOTION, 5: KNIGHT_PROMOTION } table = {} def probeEndGameTable (board): fen = board.asFen().split()[0] + " w - - 0 1" if (fen,board.color) in table: return table[(fen,board.color)] # k4it has all 6-men tables except 5 vs. 1 whites = bitLength(board.friends[WHITE]) blacks = bitLength(board.friends[BLACK]) if whites >= 5 or blacks >= 5 or whites+blacks >= 7: return [] # Request the page url = (URL + fen).replace(" ", "%20") try: f = urllib.urlopen(url) except IOError, e: log.warn("Unable to read endgame tablebase from the Internet: %s" % repr(e)) return [] data = f.read() # Parse for color, move_data in enumerate(data.split("\nNEXTCOLOR\n")): try: moves = [] for fcord, tcord, promotion, result in expression.findall(move_data): fcord = int(fcord) tcord = int(tcord) if promotion: flag = PROMOTION_FLAGS[int(promotion)] elif RANK(fcord) != RANK(tcord) and FILE(fcord) != FILE(tcord) and \ board.arBoard[fcord] == PAWN and board.arBoard[tcord] == EMPTY: flag = ENPASSANT else: flag = NORMAL_MOVE move = newMove(fcord, tcord, flag) if result == "Draw": state = DRAW steps = 0 else: s, steps = result.split(" in ") steps = int(steps) if result.startswith("Win"): if color == WHITE: state = (WHITEWON, steps) else: state = (BLACKWON, steps) elif result.startswith("Lose"): if color == WHITE: state = (BLACKWON, steps) else: state = (WHITEWON, steps) moves.append( (move,state,steps) ) if moves: table[(fen,color)] = moves elif color == board.color and board.opIsChecked(): log.warn("Asked endgametable for a won position: %s" % fen) elif color == board.color: log.warn("Couldn't get %s data for position %s.\nData was: %s" % (reprColor[color], fen, repr(data))) except (KeyError, ValueError): log.warn("Couldn't parse %s data for position %s.\nData was: %s" % (reprColor[color], fen, repr(data))) table[(fen, color)] = [] # Don't try again. if (fen,board.color) in table: return table[(fen,board.color)] return [] if __name__ == "__main__": from pychess.Utils.lutils.LBoard import LBoard from pychess.Utils.lutils.lmove import listToSan board = LBoard(NORMALCHESS) board.applyFen("8/k2P4/8/8/8/8/8/4K2R w - - 0 1") moves = probeEndGameTable(board) assert len(moves) == 18, listToSan(board, (move[0] for move in moves)) board.applyFen("8/p7/6kp/3K4/6PP/8/8/8 b - - 0 1") moves = probeEndGameTable(board) assert len(moves) == 7, listToSan(board, (move[0] for move in moves)) board.applyFen("8/p6k/2K5/7R/6PP/8/8/8 b - - 0 66") moves = probeEndGameTable(board) assert len(moves) == 3, listToSan(board, (move[0] for move in moves))
Python
from UserDict import UserDict from pychess.Utils.const import hashfALPHA, hashfBETA, hashfEXACT, hashfBAD, WHITE from ldata import MATE_VALUE from pychess.System.LimitedDict import LimitedDict from types import InstanceType from lmove import TCORD, FCORD class TranspositionTable: def __init__ (self, maxSize): assert maxSize > 0 self.data = {} self.maxSize = maxSize self.krono = [] self.killer1 = [-1]*80 self.killer2 = [-1]*80 self.hashmove = [-1]*80 self.butterfly = [0]*(64*64) def clear (self): self.data.clear() del self.krono[:] self.killer1 = [-1]*80 self.killer2 = [-1]*80 self.hashmove = [-1]*80 self.butterfly = [0]*(64*64) def probe (self, board, depth, alpha, beta): assert type(board) == InstanceType, type(board) try: move, score, hashf, tdepth = self.data[board.hash] if tdepth < depth: return move, -1, hashfBAD if hashf == hashfEXACT: return move, score, hashf if hashf == hashfALPHA and score <= alpha: return move, alpha, hashf if hashf == hashfBETA and score >= beta: return move, beta, hashf except KeyError: return def record (self, board, move, score, hashf, ply): assert type(board) == InstanceType, type(board) if not board.hash in self.data: if len(self.data) >= self.maxSize: try: del self.data[self.krono[0]] except KeyError: pass # Overwritten del self.krono[0] self.data[board.hash] = (move, score, hashf, ply) self.krono.append(board.hash) def addKiller (self, ply, move): if self.killer1[ply] == -1: self.killer1[ply] = move elif move != self.killer1[ply]: self.killer2[ply] = move def isKiller (self, ply, move): if self.killer1[ply] == move: return 10 elif self.killer2[ply] == move: return 8 if ply >= 2: if self.killer1[ply-2] == move: return 6 elif self.killer2[ply-2] == move: return 4 return 0 def setHashMove (self, ply, move): self.hashmove[ply] = move def isHashMove (self, ply, move): return self.hashmove[ply] == move def addButterfly (self, move, depth): self.butterfly[move & 0xfff] += 1 << depth def getButterfly (self, move): return self.butterfly[move & 0xfff]
Python
from pychess.Utils.const import * from pychess.Utils.lutils.attack import isAttacked from pychess.Utils.lutils.bitboard import bitPosArray, clearBit from pychess.Utils.lutils.ldata import moveArray, fromToRay ################################################################################ # Validate move # ################################################################################ def validateMove (board, move): fcord = (move >> 6) & 63 fpiece = board.arBoard[fcord] # Empty from square if fpiece == EMPTY: return False color = board.color friends = board.friends[color] # Piece is not right color if not bitPosArray[fcord] & friends: return False tcord = move & 63 flag = move >> 12 # TO square is a friendly piece, so illegal move if bitPosArray[tcord] & board.friends[color]: if board.variant == FISCHERRANDOMCHESS: if not flag in (KING_CASTLE, QUEEN_CASTLE): return False else: return False # If promotion move, piece must be pawn if (flag in PROMOTIONS or flag == ENPASSANT) and fpiece != PAWN: return False # If enpassant, then the enpassant square must be correct if flag == ENPASSANT and tcord != board.enpassant: return False # If castling, then make sure its the king if flag in (KING_CASTLE, QUEEN_CASTLE) and fpiece != KING: return False blocker = board.blocker tpiece = board.arBoard[tcord] # Pawn moves need to be handled specially if fpiece == PAWN: enemies = board.friends[1-color] if flag == ENPASSANT: enemies |= bitPosArray[board.enpassant] if color == WHITE: if not moveArray[PAWN][fcord] & bitPosArray[tcord] & enemies and \ not (tcord - fcord == 8 and tpiece == EMPTY) and \ not (tcord - fcord == 16 and fcord >> 3 == 1 and \ not fromToRay[fcord][tcord] & blocker): return False else: if not moveArray[BPAWN][fcord] & bitPosArray[tcord] & enemies and \ not (tcord - fcord == -8 and tpiece == EMPTY) and \ not (tcord - fcord == -16 and fcord >> 3 == 6 and \ not fromToRay[fcord][tcord] & blocker): return False # King moves are also special, especially castling elif fpiece == KING: if board.variant == FISCHERRANDOMCHESS: from pychess.Variants.fischerandom import frc_castling_move if not (moveArray[fpiece][fcord] & bitPosArray[tcord] and \ not flag in (KING_CASTLE, QUEEN_CASTLE)) and \ not frc_castling_move(board, fcord, tcord, flag): return False else: if color == WHITE: if not moveArray[fpiece][fcord] & bitPosArray[tcord] and \ \ not (fcord == E1 and tcord == G1 and flag == KING_CASTLE and \ board.castling & W_OO and \ not fromToRay[E1][G1] & blocker and \ not isAttacked (board, E1, BLACK) and \ not isAttacked (board, F1, BLACK) and \ not isAttacked (board, G1, BLACK)) and \ \ not (fcord == E1 and tcord == C1 and flag == QUEEN_CASTLE and \ board.castling & W_OOO and \ not fromToRay[E1][B1] & blocker and \ not isAttacked (board, E1, BLACK) and \ not isAttacked (board, D1, BLACK) and \ not isAttacked (board, C1, BLACK)): return False else: if not moveArray[fpiece][fcord] & bitPosArray[tcord] and \ \ not (fcord == E8 and tcord == G8 and flag == KING_CASTLE and \ board.castling & B_OO and \ not fromToRay[E8][G8] & blocker and \ not isAttacked (board, E8, WHITE) and \ not isAttacked (board, F8, WHITE) and \ not isAttacked (board, G8, WHITE)) and \ \ not (fcord == E8 and tcord == C8 and flag == QUEEN_CASTLE and \ board.castling & B_OOO and \ not fromToRay[E8][B8] & blocker and \ not isAttacked (board, E8, WHITE) and \ not isAttacked (board, D8, WHITE) and \ not isAttacked (board, C8, WHITE)): return False # Other pieces are more easy else: if not moveArray[fpiece][fcord] & bitPosArray[tcord]: return False # If there is a blocker on the path from fcord to tcord, illegal move if sliders [fpiece]: if clearBit(fromToRay[fcord][tcord], tcord) & blocker: return False return True ################################################################################ # Validate board # ################################################################################ def validateBoard (board): """ Check the board to make sure that its valid. Some things to check are a. Both sides have max 1 king and max 8 pawns b. Side not on the move must not be in check. c. If en passant square is set, check it is possible. d. Check if castling status are all correct. """ # # TODO: This functions hasn't yet been translated from C to Python # Not fully at least # # You must place both a Black King and White King on the board if nbits (board.b[WHITE][KING]) != 1: return False if nbits (board.b[BLACK][KING]) != 1: return False # You can't place a pawn on the eight rank if board.b[WHITE][PAWN] & rankBits[7]: return False if board.b[BLACK][PAWN] & rankBits[0]: return False # You can't set up a position in which a side has more than eight pawns if nbits(board.b[WHITE][PAWN]) > 8: return False if nbits(board.b[BLACK][PAWN]) > 8: return False # You can't set up a position in which one side's King is in check and the # other side is to move (otherwise it's a position in which mate has # already been delivered) side = board.side; xside = 1^side; if SqAtakd (board.king[xside], side): return False if board.ep > -1: sq = board.ep + (xside == WHITE and 8 or -8) if not BitPosArray[sq] & board.b[xside][PAWN]: return False # TODO: use self.ini_rooks and self.ini_kings # TODO: instead of hardcoded E1/H1 etc. if board.flag & WKINGCASTLE: if not(BitPosArray[E1] & board.b[WHITE][KING]): return False if not(BitPosArray[H1] & board.b[WHITE][ROOK]): return False if board.flag & WQUEENCASTLE: if not(BitPosArray[E1] & board.b[WHITE][KING]): return False if not(BitPosArray[A1] & board.b[WHITE][ROOK]): return False if board.flag & BKINGCASTLE: if not(BitPosArray[E8] & board.b[BLACK][KING]): return False if not(BitPosArray[H8] & board.b[BLACK][ROOK]): return False if board.flag & BQUEENCASTLE: if not(BitPosArray[E8] & board.b[BLACK][KING]): return False if not(BitPosArray[A8] & board.b[BLACK][ROOK]): return False return True
Python
from array import array from operator import or_ from pychess.Utils.const import * #from pychess.Utils.lutils.lmove import RANK, FILE from bitboard import * def RANK (cord): return cord >> 3 def FILE (cord): return cord & 7 ################################################################################ ################################################################################ ## Evaluating constants ## ################################################################################ ################################################################################ PAWN_VALUE = 100 KNIGHT_VALUE = 300 BISHOP_VALUE = 330 ROOK_VALUE = 500 QUEEN_VALUE = 900 KING_VALUE = 2000 PIECE_VALUES = [0, PAWN_VALUE, KNIGHT_VALUE, BISHOP_VALUE, ROOK_VALUE, QUEEN_VALUE, KING_VALUE] MATE_VALUE = MAXVAL = 99999 # How many points does it give to have the piece standing i cords from the # opponent king pawnTScale = [0, 40, 20, 12, 9, 6, 4, 2, 1, 0] bishopTScale = [0, 50, 25, 15, 7, 5, 3, 2, 2, 1] knightTScale = [0, 100, 50, 35, 10, 3, 2, 2, 1, 1] rookTScale = [0, 50, 40, 15, 5, 2, 1, 1, 1, 0] queenTScale = [0, 100, 60, 20, 10, 7, 5, 4, 3, 2] passedScores = ( ( 0, 48, 48, 120, 144, 192, 240, 0 ), ( 0, 240, 192, 144, 120, 48, 48, 0 ) ) # Penalties for one or more isolated pawns on a given file isolani_normal = ( -8, -10, -12, -14, -14, -12, -10, -8 ) # Penalties if the file is half-open (i.e. no enemy pawns on it) isolani_weaker = ( -22, -24, -26, -28, -28, -26, -24, -22 ) ############################################################################### # Distance boards for different pieces # ############################################################################### taxicab = [[0]*64 for i in range(64)] sdistance = [[0]*64 for i in range(64)] for fcord in xrange(64): for tcord in xrange(fcord+1, 64): fx = FILE(fcord) fy = RANK(fcord) tx = FILE(tcord) ty = RANK(tcord) taxicab[fcord][tcord] = taxicab[fcord][tcord] = abs(fx-tx) + abs(fy-ty) sdistance[fcord][tcord] = sdistance[fcord][tcord] = min(abs(fx-tx), abs(fy-ty)) distance = [[[0]*64 for i in xrange(64)] for j in xrange(KING+1)] distance[EMPTY] = None distance[KING] = sdistance distance[PAWN] = sdistance # Special table for knightdistances knightDistance = [ 6, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 6, 5, 4, 5, 4, 3, 4, 3, 4, 3, 4, 3, 4, 5, 4, 5, 4, 5, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 5, 4, 5, 4, 3, 4, 3, 2, 3, 2, 3, 2, 3, 4, 3, 4, 5, 4, 3, 4, 3, 2, 3, 2, 3, 2, 3, 2, 3, 4, 3, 4, 5, 4, 3, 2, 3, 4, 1, 2, 1, 4, 3, 2, 3, 4, 5, 4, 3, 4, 3, 2, 1, 2, 3, 2, 1, 2, 3, 4, 3, 4, 5, 4, 3, 2, 3, 2, 3, 0, 3, 2, 3, 2, 3, 4, 5, 4, 3, 4, 3, 2, 1, 2, 3, 2, 1, 2, 3, 4, 3, 4, 5, 4, 3, 2, 3, 4, 1, 2, 1, 4, 3, 2, 3, 4, 5, 4, 3, 4, 3, 2, 3, 2, 3, 2, 3, 2, 3, 4, 3, 4, 5, 4, 3, 4, 3, 2, 3, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 5, 4, 5, 4, 5, 4, 3, 4, 3, 4, 3, 4, 3, 4, 5, 4, 5, 6, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 6, ] # Calculate for fcord in xrange(64): frank = RANK(fcord) ffile = FILE(fcord) for tcord in xrange(fcord+1, 64): # Notice, that we skip fcord == tcord, as all fields are zero from # scratch in anyway trank = RANK(tcord) tfile = FILE(tcord) # Knight field = (7-frank+trank)*15 + 7-ffile+tfile distance[KNIGHT][tcord][fcord] = distance[KNIGHT][fcord][tcord] = \ knightDistance[field] # Rook if frank == trank or ffile == tfile: distance[ROOK][tcord][fcord] = distance[ROOK][fcord][tcord] = 1 else: distance[ROOK][tcord][fcord] = distance[ROOK][fcord][tcord] = 2 # Bishop if abs(frank-trank) == abs(ffile-tfile): distance[BISHOP][tcord][fcord] = distance[BISHOP][fcord][tcord] = 1 else: distance[BISHOP][tcord][fcord] = distance[BISHOP][fcord][tcord] = 2 # Queen if frank == trank or ffile == tfile or abs(frank-trank) == abs(ffile-tfile): distance[QUEEN][tcord][fcord] = distance[QUEEN][fcord][tcord] = 1 else: distance[QUEEN][tcord][fcord] = distance[QUEEN][fcord][tcord] = 2 # Special cases for knights in corners distance[KNIGHT][A1][B2] = distance[KNIGHT][B2][A1] = 4 distance[KNIGHT][H1][G2] = distance[KNIGHT][G2][H1] = 4 distance[KNIGHT][A8][B7] = distance[KNIGHT][B7][A8] = 4 distance[KNIGHT][H8][G7] = distance[KNIGHT][G7][H8] = 4 ############################################################################### # Boards used for evaluating ############################################################################### pawnScoreBoard = ( (0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5,-10,-10, 5, 5, 5, -2, -2, -2, 6, 6, -2, -2, -2, 0, 0, 0, 25, 25, 0, 0, 0, 2, 2, 12, 16, 16, 12, 2, 2, 4, 8, 12, 16, 16, 12, 4, 4, 4, 8, 12, 16, 16, 12, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0, 0, 4, 8, 12, 16, 16, 12, 4, 4, 4, 8, 12, 16, 16, 12, 4, 4, 2, 2, 12, 16, 16, 12, 2, 2, 0, 0, 0, 25, 25, 0, 0, 0, -2, -2, -2, 6, 6, -2, -2, -2, 5, 5, 5,-10,-10, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0) ) outpost = ( (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) ) normalKing = ( 24, 24, 24, 16, 16, 0, 32, 32, 24, 20, 16, 12, 12, 16, 20, 24, 16, 12, 8, 4, 4, 8, 12, 16, 12, 8, 4, 0, 0, 4, 8, 12, 12, 8, 4, 0, 0, 4, 8, 12, 16, 12, 8, 4, 4, 8, 12, 16, 24, 20, 16, 12, 12, 16, 20, 24, 24, 24, 24, 16, 16, 0, 32, 32 ) endingKing = ( 0, 6, 12, 18, 18, 12, 6, 0, 6, 12, 18, 24, 24, 18, 12, 6, 12, 18, 24, 32, 32, 24, 18, 12, 18, 24, 32, 48, 48, 32, 24, 18, 18, 24, 32, 48, 48, 32, 24, 18, 12, 18, 24, 32, 32, 24, 18, 12, 6, 12, 18, 24, 24, 18, 12, 6, 0, 6, 12, 18, 18, 12, 6, 0 ) ############################################################################### # Maps for bitboards ############################################################################### d2e2 = (createBoard(0x0018000000000000), createBoard(0x0000000000001800)) brank7 = (createBoard(0x000000000000FF00), createBoard(0x00FF000000000000)) brank8 = (createBoard(0x00000000000000FF), createBoard(0xFF00000000000000)) brank67 = (createBoard(0x0000000000FFFF00), createBoard(0x00FFFF0000000000)) brank58 = (createBoard(0x00000000FFFFFFFF), createBoard(0xFFFFFFFF00000000)) brank48 = (createBoard(0x000000FFFFFFFFFF), createBoard(0xFFFFFFFFFF000000)) # Penalties if the file is half-open (i.e. no enemy pawns on it) isolani_weaker = (-22, -24, -26, -28, -28, -26, -24, -22) stonewall = [createBoard(0), createBoard(0)] # D4, E3, F4 # - - - - - - - - # - - - - - - - - # - - - - - - - - # - - - - - - - - # - - - # - # - - # - - - - # - - - # - - - - - - - - # - - - - - - - - stonewall[WHITE] = createBoard(0x81400000000) # D5, E6, F5 # - - - - - - - - # - - - - - - - - # - - - - # - - - # - - - # - # - - # - - - - - - - - # - - - - - - - - # - - - - - - - - # - - - - - - - - stonewall[BLACK] = createBoard(0x81400000000) # - - - - - - - - # - - - - - - - - # - - - - - - - - # - - - - - - - - # - - - - - - - - # - # - - - - # - # # # - - - - # # # - - - - - - - - qwwingpawns1 = bitPosArray[A2] | bitPosArray[B2] qwwingpawns2 = bitPosArray[A2] | bitPosArray[B3] kwwingpawns1 = bitPosArray[G2] | bitPosArray[H2] kwwingpawns2 = bitPosArray[G3] | bitPosArray[H2] # - - - - - - - - # # # - - - - # # # - # - - - - # - # - - - - - - - - # - - - - - - - - # - - - - - - - - # - - - - - - - - # - - - - - - - - qbwingpawns1 = bitPosArray[A7] | bitPosArray[B7] qbwingpawns2 = bitPosArray[A7] | bitPosArray[B6] kbwingpawns1 = bitPosArray[G7] | bitPosArray[H7] kbwingpawns2 = bitPosArray[G6] | bitPosArray[H7] ################################################################################ # Ranks and files # ################################################################################ rankBits = [createBoard(255 << i*8) for i in xrange(7,-1,-1)] fileBits = [createBoard(0x0101010101010101 << i) for i in xrange(7,-1,-1)] ################################################################################ ################################################################################ ## Bit boards ## ################################################################################ ################################################################################ WHITE_SQUARES = createBoard(0x55AA55AA55AA55AA) BLACK_SQUARES = createBoard(0xAA55AA55AA55AA55) # - - - - - - - - # - - - - - - - - # - - - - - - - - # - - - # # - - - # - - - # # - - - # - - - - - - - - # - - - - - - - - # - - - - - - - - CENTER_FOUR = createBoard(0x0000001818000000) # - - - - - - - - # - - - - - - - - # - - # # # # - - # - - # # # # - - # - - # # # # - - # - - # # # # - - # - - - - - - - - # - - - - - - - - sbox = createBoard(0x00003C3C3C3C0000) # - - - - - - - - # - # # # # # # - # - # # # # # # - # - # # # # # # - # - # # # # # # - # - # # # # # # - # - # # # # # # - # - - - - - - - - lbox = createBoard(0x007E7E7E7E7E7E00) # - - - - - # # # # - - - - - # # # # - - - - - # # # # - - - - - # # # # - - - - - # # # # - - - - - # # # # - - - - - # # # # - - - - - # # # right = fileBits[5] | fileBits[6] | fileBits[7] # # # # - - - - - # # # # - - - - - # # # # - - - - - # # # # - - - - - # # # # - - - - - # # # # - - - - - # # # # - - - - - # # # # - - - - - left = fileBits[0] | fileBits[1] | fileBits[2] ################################################################################ # Generate the move bitboards. For e.g. the bitboard for all # # the moves of a knight on f3 is given by MoveArray[knight][21]. # ################################################################################ dir = [ None, [ 9, 11 ], # Only capture moves are included [ -21, -19, -12, -8, 8, 12, 19, 21 ], [ -11, -9, 9, 11 ], [ -10, -1, 1, 10 ], [ -11, -10, -9, -1, 1, 9, 10, 11 ], [ -11, -10, -9, -1, 1, 9, 10, 11 ], [ -9, -11 ], # Following are for front and back walls. Will be removed from list after # the loop [ 9, 10, 11], [ -9, -10, -11] ] sliders += [False, False] map = [ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, -1, -1, 8, 9, 10, 11, 12, 13, 14, 15, -1, -1, 16, 17, 18, 19, 20, 21, 22, 23, -1, -1, 24, 25, 26, 27, 28, 29, 30, 31, -1, -1, 32, 33, 34, 35, 36, 37, 38, 39, -1, -1, 40, 41, 42, 43, 44, 45, 46, 47, -1, -1, 48, 49, 50, 51, 52, 53, 54, 55, -1, -1, 56, 57, 58, 59, 60, 61, 62, 63, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ] moveArray = [[createBoard(0)]*64 for i in xrange(len(dir))] # moveArray[8][64] for piece in xrange(1,len(dir)): for fcord in xrange(120): f = map[fcord] if f == -1: # We only generate moves for squares inside the board continue # Create a new bitboard b = createBoard(0) for d in dir[piece]: tcord = fcord while True: tcord += d t = map[tcord] if t == -1: # If we landed outside of board, there is no more to look # for break b = setBit (b, t) if not sliders[piece]: # If we are a slider, we should not break, but add the dir # value once again break moveArray[piece][f] = b frontWall = (moveArray[8], moveArray[9]) del moveArray[9]; del moveArray[8] del dir[9]; del dir[8] del sliders[9]; del sliders[8] ################################################################################ # For each square, there are 8 rays. The first 4 rays are diagonals # # for the bishops and the next 4 are file/rank for the rooks. # # The queen uses all 8 rays. # # These rays are used for move generation rather than MoveArray[]. # # Also initialize the directions[][] array. directions[f][t] returns # # the index into rays[f] array allow us to find the ray in that direction. # ################################################################################ directions = [[-1]*64 for i in xrange(64)] # directions[64][64] rays = [[createBoard(0)]*8 for i in xrange(64)] # rays[64][8] for fcord in xrange(120): f = map[fcord] if f == -1: continue ray = -1 for piece in BISHOP, ROOK: for d in dir[piece]: ray += 1 b = 0 tcord = fcord while True: tcord += d t = map[tcord] if t == -1: break rays[f][ray] = setBit (rays[f][ray], t) directions[f][t] = ray ################################################################################ # The FromToRay[b2][f6] gives the diagonal ray from c3 to f6; # # It also produces horizontal/vertical rays as well. If no # # ray is possible, then a 0 is returned. # ################################################################################ fromToRay = [[createBoard(0)]*64 for i in xrange(64)] # fromToRay[64][64] for piece in BISHOP, ROOK: for fcord in xrange (120): f = map[fcord] if f == -1: continue for d in dir[piece]: tcord = fcord t = map[tcord] while True: b = fromToRay[f][t] tcord += d t = map[tcord] if t == -1: break fromToRay[f][t] = setBit (fromToRay[f][t], t) fromToRay[f][t] |= b ################################################################################ # The PassedPawnMask variable is used to determine if a pawn is passed. # # This mask is basically all 1's from the square in front of the pawn to # # the promotion square, also duplicated on both files besides the pawn # # file. Other bits will be set to zero. # # E.g. PassedPawnMask[white][b3] = 1's in a4-c4-c8-a8 rect, 0 otherwise. # ################################################################################ passedPawnMask = [[createBoard(0)]*64, [createBoard(0)]*64] # Do for white pawns first for cord in xrange(64): passedPawnMask[WHITE][cord] = rays[cord][7] passedPawnMask[BLACK][cord] = rays[cord][4] if cord & 7 != 0: # If file is not left most passedPawnMask[WHITE][cord] |= rays[cord-1][7] passedPawnMask[BLACK][cord] |= rays[cord-1][4] if cord & 7 != 7: # If file is not right most passedPawnMask[WHITE][cord] |= rays[cord+1][7] passedPawnMask[BLACK][cord] |= rays[cord+1][4] ################################################################################ # The IsolaniMask variable is used to determine if a pawn is an isolani. # # This mask is basically all 1's on files beside the file the pawn is on. # # Other bits will be set to zero. # # E.g. isolaniMask[d-file] = 1's in c-file & e-file, 0 otherwise. # ################################################################################ isolaniMask = [0]*8 isolaniMask[0] = fileBits[1] isolaniMask[7] = fileBits[6] for i in xrange (1, 7): isolaniMask[i] = fileBits[i-1] | fileBits[i+1] #=============================================================================== # The SquarePawnMask is used to determine if a king is in the square of # the passed pawn and is able to prevent it from queening. # Caveat: Pawns on 2nd rank have the same mask as pawns on the 3rd rank # as they can advance 2 squares. #=============================================================================== squarePawnMask = [[createBoard(0)]*64, [createBoard(0)]*64] for cord in xrange(64): # White mask l = 7 - RANK(cord) i = max(cord & 56, cord-l) j = min(cord | 7, cord+l) for k in xrange(i, j+1): squarePawnMask[WHITE][cord] |= bitPosArray[k] | fromToRay[k][k|56] # Black mask l = RANK(cord) i = max(cord & 56, cord-l) j = min(cord | 7, cord+l) for k in xrange(i, j+1): squarePawnMask[BLACK][cord] |= bitPosArray[k] | fromToRay[k][k&7] # For pawns on 2nd rank, they have same mask as pawns on 3rd rank for cord in xrange(A2, H2+1): squarePawnMask[WHITE][cord] = squarePawnMask[WHITE][cord+8] for cord in xrange(A7, H7+1): squarePawnMask[BLACK][cord] = squarePawnMask[BLACK][cord-8] ################################################################################ # These tables are used to calculate rook, queen and bishop moves # ################################################################################ ray00 = [rays[cord][5] | rays[cord][6] | 1<<(63-cord) for cord in xrange(64)] ray45 = [rays[cord][0] | rays[cord][3] | 1<<(63-cord) for cord in xrange(64)] ray90 = [rays[cord][4] | rays[cord][7] | 1<<(63-cord) for cord in xrange(64)] ray135 = [rays[cord][1] | rays[cord][2] | 1<<(63-cord) for cord in xrange(64)] attack00 = [{} for i in xrange(64)] attack45 = [{} for i in xrange(64)] attack90 = [{} for i in xrange(64)] attack135 = [{} for i in xrange(64)] cmap = [ 128, 64, 32, 16, 8, 4, 2, 1 ] rot1 = [ A1, A2, A3, A4, A5, A6, A7, A8 ] rot2 = [ A1, B2, C3, D4, E5, F6, G7, H8 ] rot3 = [ A8, B7, C6, D5, E4, F3, G2, H1 ] # To save time, we init a main line for each of the four directions, and next # we will translate it for each possible cord for cord in xrange(8): for map in xrange(1, 256): # Skip entries without cord set, as cord will always be set if not map & cmap[cord]: continue # Find limits inclusive cord1 = cord2 = cord while cord1 > 0: cord1 -= 1 if cmap[cord1] & map: break while cord2 < 7: cord2 += 1 if cmap[cord2] & map: break # Remember A1 is the left most bit map00 = createBoard(map << 56) attack00[cord][map00] = \ fromToRay[cord][cord1] | \ fromToRay[cord][cord2] map90 = createBoard(reduce(or_, (1 << 63-rot1[c] for c in iterBits(map00)))) attack90[rot1[cord]][map90] = \ fromToRay[rot1[cord]][rot1[cord1]] | \ fromToRay[rot1[cord]][rot1[cord2]] map45 = createBoard(reduce(or_, (1 << 63-rot2[c] for c in iterBits(map00)))) attack45[rot2[cord]][map45] = \ fromToRay[rot2[cord]][rot2[cord1]] | \ fromToRay[rot2[cord]][rot2[cord2]] map135 = createBoard(reduce(or_, (1 << 63-rot3[c] for c in iterBits(map00)))) attack135[rot3[cord]][map135] = \ fromToRay[rot3[cord]][rot3[cord1]] | \ fromToRay[rot3[cord]][rot3[cord2]] MAXBITBOARD = (1<<64)-1 for r in xrange(A2,A8+1,8): for cord in iterBits(ray00[r]): attack00[cord] = dict((map >> 8, ray >> 8) for map,ray in attack00[cord-8].iteritems()) for r in xrange(B1,H1+1): for cord in iterBits(ray90[r]): attack90[cord] = dict((map >> 1, ray >> 1) for map,ray in attack90[cord-1].iteritems()) # Bottom right for r in xrange(B1,H1+1): for cord in iterBits(ray45[r]): attack45[cord] = dict((map << 8 & MAXBITBOARD, ray << 8 & MAXBITBOARD) for map,ray in attack45[cord+8].iteritems()) # Top left for r in reversed(xrange(A8,H8)): for cord in iterBits(ray45[r]): attack45[cord] = dict((map >> 8, ray >> 8) for map,ray in attack45[cord-8].iteritems()) # Top right for r in xrange(B8,H8+1): for cord in iterBits(ray135[r]): attack135[cord] = dict((map >> 8, ray >> 8) for map,ray in attack135[cord-8].iteritems()) # Bottom left for r in reversed(xrange(A1,H1)): for cord in iterBits(ray135[r]): attack135[cord] = dict((map << 8 & MAXBITBOARD, ray << 8 & MAXBITBOARD) for map,ray in attack135[cord+8].iteritems())
Python
from time import time from random import random from heapq import heappush, heappop from lmovegen import genAllMoves, genCheckEvasions, genCaptures from pychess.Utils.const import * from leval import evaluateComplete from lsort import getCaptureValue, getMoveValue from lmove import toSAN from ldata import MATE_VALUE from TranspositionTable import TranspositionTable import ldraw from pychess.Utils.lutils.egtb_k4it import probeEndGameTable TIMECHECK_FREQ = 500 table = TranspositionTable(5000000) skipPruneChance = 0 searching = False movesearches = 0 nodes = 0 last = 0 endtime = 0 timecheck_counter = TIMECHECK_FREQ useegtb = False def alphaBeta (board, depth, alpha=-MATE_VALUE, beta=MATE_VALUE, ply=0): """ This is a alphabeta/negamax/quiescent/iterativedeepend search algorithm Based on moves found by the validator.py findmoves2 function and evaluated by eval.py. The function recalls itself "depth" times. If the last move in range depth was a capture, it will continue calling itself, only searching for captures. It returns a tuple of * a list of the path it found through the search tree (last item being the deepest) * a score of your standing the the last possition. """ global last, searching, nodes, movesearches, table, endtime, timecheck_counter foundPv = False hashf = hashfALPHA amove = [] ############################################################################ # Look in the end game table ############################################################################ if useegtb: egtb = probeEndGameTable(board) if egtb: move, state, steps = egtb[0] if state == DRAW: score = 0 elif board.color == WHITE: if state == WHITEWON: score = MATE_VALUE-steps+2 else: score = -MATE_VALUE+steps-2 else: if state == WHITEWON: score = -MATE_VALUE+steps-2 else: score = MATE_VALUE-steps+2 last = 1 return [move], score ########################################################################### # We don't save repetition in the table, so we need to test draw before # # table. # ########################################################################### # We don't adjudicate draws. Clients may have different rules for that. if ply > 0: if ldraw.test(board): last = 2 return [], 0 ############################################################################ # Look up transposition table # ############################################################################ table.setHashMove (depth, -1) probe = table.probe (board, depth, alpha, beta) hashmove = None if probe: move, score, hashf = probe hashmove = move table.setHashMove (depth, move) if hashf == hashfEXACT: last = 3 return [move], score elif hashf == hashfBETA: beta = min(score, beta) elif hashf == hashfALPHA: alpha = score if hashf != hashfBAD and alpha >= beta: last = 4 return [move], score ############################################################################ # Cheking the time # ############################################################################ timecheck_counter -= 1 if timecheck_counter == 0: if time() > endtime: searching = False timecheck_counter = TIMECHECK_FREQ ############################################################################ # Break itereation if interupted or if times up # ############################################################################ if not searching: last = 5 return [], -evaluateComplete(board, 1-board.color) ############################################################################ # Go for quiescent search # ############################################################################ isCheck = board.isChecked() if depth <= 0: if isCheck: # Being in check is that serious, that we want to take a deeper look depth += 1 else: last = 6 mvs, val = quiescent(board, alpha, beta, ply) return mvs, val ############################################################################ # Find and sort moves # ############################################################################ movesearches += 1 if isCheck: moves = [(-getMoveValue(board,table,depth,m),m) for m in genCheckEvasions(board)] else: moves = [(-getMoveValue(board,table,depth,m),m) for m in genAllMoves(board)] moves.sort() # This is needed on checkmate catchFailLow = None ############################################################################ # Loop moves # ############################################################################ for moveValue, move in moves: nodes += 1 board.applyMove(move) if not isCheck: if board.opIsChecked(): board.popMove() continue catchFailLow = move if foundPv: mvs, val = alphaBeta (board, depth-1, -alpha-1, -alpha, ply+1) val = -val if val > alpha and val < beta: mvs, val = alphaBeta (board, depth-1, -beta, -alpha, ply+1) val = -val else: mvs, val = alphaBeta (board, depth-1, -beta, -alpha, ply+1) val = -val board.popMove() if val > alpha: if val >= beta: if searching: table.record (board, move, beta, hashfBETA, depth) # We don't want to use our valuable killer move spaces for # captures and promotions, as these are searched early anyways. if board.arBoard[move&63] == EMPTY and \ not move>>12 in PROMOTIONS: table.addKiller (depth, move) table.addButterfly(move, depth) last = 7 return [move]+mvs, beta alpha = val amove = [move]+mvs hashf = hashfEXACT foundPv = True ############################################################################ # Return # ############################################################################ if amove: if searching: table.record (board, amove[0], alpha, hashf, depth) if board.arBoard[amove[0]&63] == EMPTY: table.addKiller (depth, amove[0]) last = 8 return amove, alpha if catchFailLow: if searching: table.record (board, catchFailLow, alpha, hashf, depth) last = 9 return [catchFailLow], alpha # If no moves were found, this must be a mate or stalemate if isCheck: last = 10 return [], -MATE_VALUE+ply-2 last = 11 return [], 0 def quiescent (board, alpha, beta, ply): if skipPruneChance and random() < skipPruneChance: return [], (alpha+beta)/2 global nodes if ldraw.test(board): return [], 0 isCheck = board.isChecked() # Our quiescent search will evaluate the current board, and if value = evaluateComplete(board, board.color) if value >= beta and not isCheck: return [], beta if value > alpha: alpha = value amove = [] heap = [] if isCheck: someMove = False for move in genCheckEvasions(board): someMove = True # Heap.append is fine, as we don't really do sorting on the few moves heap.append((0, move)) if not someMove: return [], -MATE_VALUE+ply-2 else: for move in genCaptures (board): heappush(heap, (-getCaptureValue (board, move), move)) while heap: nodes += 1 v, move = heappop(heap) board.applyMove(move) if board.opIsChecked(): board.popMove() continue mvs, val = quiescent(board, -beta, -alpha, ply+1) val = -val board.popMove() if val >= beta: return [move]+mvs, beta if val > alpha: alpha = val amove = [move]+mvs if amove: return amove, alpha else: return [], alpha
Python
from bitboard import * from ldata import * from pychess.Utils.const import * # # Caveat: Many functions in this module has very similar code. If you fix a # bug, or write a perforance enchace, please update all functions. Apologies # for the inconvenience # def isAttacked (board, cord, color): """ To determine if cord is attacked by any pieces from color. """ pboards = board.boards[color] # Knights if pboards[KNIGHT] & moveArray[KNIGHT][cord]: return True rayto = fromToRay[cord] blocker = board.blocker # Bishops & Queens bisque = (pboards[BISHOP] | pboards[QUEEN]) & moveArray[BISHOP][cord] others = ~bisque & blocker for t in iterBits(bisque): # If there is a path and no other piece stand in our way ray = rayto[t] if ray and not ray & others: return True # Rooks & Queens rooque = (pboards[ROOK] | pboards[QUEEN]) & moveArray[ROOK][cord] others = ~rooque & blocker for t in iterBits(rooque): # If there is a path and no other piece stand in our way ray = rayto[t] if ray and not ray & others: return True # Pawns # Would a pawn of the opposite color, standing at out kings cord, be able # to attack any of our pawns? ptype = color == WHITE and BPAWN or PAWN if pboards[PAWN] & moveArray[ptype][cord]: return True # King if pboards[KING] & moveArray[KING][cord]: return True return False def getAttacks (board, cord, color): """ To create a bitboard of pieces of color, which attacks cord """ pieces = board.boards[color] # Knights bits = pieces[KNIGHT] & moveArray[KNIGHT][cord] # Kings bits |= pieces[KING] & moveArray[KING][cord] # Pawns bits |= pieces[PAWN] & moveArray[color == WHITE and BPAWN or PAWN][cord] rayto = fromToRay[cord] blocker = board.blocker # Bishops and Queens bisque = (pieces[BISHOP] | pieces[QUEEN]) & moveArray[BISHOP][cord] for c in iterBits(bisque): ray = rayto[c] if ray and not clearBit(ray & blocker, c): bits |= bitPosArray[c] # Rooks and queens rooque = (pieces[ROOK] | pieces[QUEEN]) & moveArray[ROOK][cord] for c in iterBits(rooque): ray = rayto[c] if ray and not clearBit(ray & blocker, c): bits |= bitPosArray[c] return bits def getPieceMoves (board, cord, color, piece): """ To create a bitboard of specified pieces of color, which can move to cord """ color = board.color pieces = board.boards[color] if piece == KNIGHT or piece == KING: return pieces[piece] & moveArray[piece][cord] rayto = fromToRay[cord] blocker = board.blocker if sliders[piece]: cords = pieces[piece] & moveArray[piece][cord] bits = 0 for c in iterBits(cords): ray = rayto[c] if ray and not clearBit(ray & blocker, c): bits |= bitPosArray[c] return bits if piece == PAWN: pawns = pieces[PAWN] bits = pawns & moveArray[color == WHITE and BPAWN or PAWN][cord] bits |= pawns & bitPosArray[cord + (color == WHITE and -8 or 8)] if not blocker & bitPosArray[cord + (color == WHITE and -8 or 8)]: bits |= pawns & rankBits[color == WHITE and 1 or 6] return bits def pinnedOnKing (board, cord, color): # Determine if the piece on cord is pinned against its colors king. # In chess, a pin is a situation in which a piece is forced to stay put # because moving it would expose a more valuable piece behind it to # capture. # Caveat: pinnedOnKing should only be called by genCheckEvasions(). kingCord = board.kings[color] dir = directions[kingCord][cord] if dir == -1: return False opcolor = 1 - color blocker = board.blocker # Path from piece to king is blocked, so no pin if clearBit(fromToRay[kingCord][cord], cord) & blocker: return False b = (rays[kingCord][dir] ^ fromToRay[kingCord][cord]) & blocker if not b: return False cord1 = cord > kingCord and firstBit (b) or lastBit (b) # If diagonal if dir <= 3 and bitPosArray[cord1] & \ (board.boards[opcolor][QUEEN] | board.boards[opcolor][BISHOP]): return True # Rank / file if dir >= 4 and bitPosArray[cord1] & \ (board.boards[opcolor][QUEEN] | board.boards[opcolor][ROOK]): return True return False def staticExchangeEvaluate (board, moveOrTcord, color=None): """ The GnuChess Static Exchange Evaluator (or SEE for short). First determine the target square. Create a bitboard of all squares attacking the target square for both sides. Using these 2 bitboards, we take turn making captures from smallest piece to largest piece. When a sliding piece makes a capture, we check behind it to see if another attacker piece has been exposed. If so, add this to the bitboard as well. When performing the "captures", we stop if one side is ahead and doesn't need to capture, a form of pseudo-minimaxing. """ # # Notice: If you use the tcord version, the color is the color attacked, and # the color to witch the score is relative. # swaplist = [0] if color == None: move = moveOrTcord flag = move >> 12 fcord = (move >> 6) & 63 tcord = move & 63 color = board.friends[BLACK] & bitPosArray[fcord] and BLACK or WHITE opcolor = 1-color boards = board.boards[color] opboards = board.boards[opcolor] ours = getAttacks (board, tcord, color) ours = clearBit (ours, fcord) theirs = getAttacks (board, tcord, opcolor) if xray[board.arBoard[fcord]]: ours, theirs = addXrayPiece (board, tcord, fcord, color, ours, theirs) if flag in PROMOTIONS: swaplist = [PIECE_VALUES[flag-3] - PAWN_VALUE] lastval = -PIECE_VALUES[flag-3] else: if flag == ENPASSANT: swaplist = [PAWN_VALUE] else: swaplist = [PIECE_VALUES[board.arBoard[tcord]]] lastval = -PIECE_VALUES[board.arBoard[fcord]] else: tcord = moveOrTcord opcolor = 1-color boards = board.boards[color] opboards = board.boards[opcolor] ours = getAttacks (board, tcord, color) theirs = getAttacks (board, tcord, opcolor) lastval = -PIECE_VALUES[board.arBoard[tcord]] while theirs: for piece in range(PAWN, KING+1): r = theirs & opboards[piece] if r: cord = firstBit(r) theirs = clearBit(theirs, cord) if xray[piece]: ours, theirs = addXrayPiece (board, tcord, cord, color, ours, theirs) swaplist.append(swaplist[-1] + lastval) lastval = PIECE_VALUES[piece] break if not ours: break for piece in range(PAWN, KING+1): r = ours & boards[piece] if r: cord = firstBit(r) ours = clearBit(ours, cord) if xray[piece]: ours, theirs = addXrayPiece (board, tcord, cord, color, ours, theirs) swaplist.append(swaplist[-1] + lastval) lastval = -PIECE_VALUES[piece] break # At this stage, we have the swap scores in a list. We just need to # mini-max the scores from the bottom up to the top of the list. for n in xrange(len(swaplist)-1, 0, -1): if n & 1: if swaplist[n] <= swaplist[n-1]: swaplist[n-1] = swaplist[n] else: if swaplist[n] >= swaplist[n-1]: swaplist[n-1] = swaplist[n] return swaplist[0] xray = (False, True, False, True, True, True, False) def addXrayPiece (board, tcord, fcord, color, ours, theirs): """ This is used by swapOff. The purpose of this routine is to find a piece which attack through another piece (e.g. two rooks, Q+B, B+P, etc.) Color is the side attacking the square where the swapping is to be done. """ dir = directions[tcord][fcord] a = rays[fcord][dir] & board.blocker if not a: return ours, theirs if tcord < fcord: ncord = firstBit(a) else: ncord = lastBit(a) piece = board.arBoard[ncord] if piece == QUEEN or (piece == ROOK and dir > 3) or \ (piece == BISHOP and dir < 4): bit = bitPosArray[ncord] if bit & board.friends[color]: ours |= bit else: theirs |= bit return ours, theirs def defends (board, fcord, tcord): """ Could fcord attack tcord if the piece on tcord wasn't on the team of fcord? Doesn't test check. """ # Work on a board copy, as we are going to change some stuff board = board.clone() if board.friends[WHITE] & bitPosArray[fcord]: color = WHITE else: color = BLACK opcolor = 1-color boards = board.boards[color] opboards = board.boards[opcolor] # To see if we now defend the piece, we have to "give" it to the other team piece = board.arBoard[tcord] #backup = boards[piece] #opbackup = opboards[piece] boards[piece] &= notBitPosArray[tcord] opboards[piece] |= bitPosArray[tcord] board.friends[color] &= notBitPosArray[tcord] board.friends[opcolor] |= bitPosArray[tcord] # Can we "attack" the piece now? backupColor = board.color board.setColor(color) from lmove import newMove from validator import validateMove islegal = validateMove (board, newMove(fcord, tcord)) board.setColor(backupColor) # We don't need to set the board back, as we work on a copy #boards[piece] = backup #opboards[piece] = opbackup #board.friends[color] |= bitPosArray[tcord] #board.friends[opcolor] &= notBitPosArray[tcord] return islegal
Python
################################################################################ # The purpose of this module, is to give a certain position a score. The # # greater the score, the better the position # ################################################################################ from pychess.Utils.const import * from ldata import * from LBoard import LBoard from lsort import staticExchangeEvaluate from lmove import newMove #from random import randint randomval = 0 #randint(8,12)/10. def evaluateComplete (board, color, balanced=False): """ A detailed evaluation function, taking into account several positional factors """ s, phase = evalMaterial (board, color) s += evalKingTropism (board, color, phase) s += evalKnights (board, color, phase) s += evalBishops (board, color, phase) s += evalTrappedBishops (board, color, phase) s += evalRooks (board, color, phase) s += evalKing (board, color, phase) s += evalDev (board, color, phase) s += evalPawnStructure (board, color, phase) s += evalDoubleQR7 (board, color, phase) s += randomval if balanced: s -= evalKingTropism (board, 1-color, phase) s -= evalKnights (board, 1-color, phase) s -= evalPawnStructure (board, 1-color, phase) s -= evalBishops (board, 1-color, phase) s -= evalTrappedBishops (board, 1-color, phase) s -= evalRooks (board, 1-color, phase) return s ################################################################################ # evalMaterial # ################################################################################ def evalMaterial (board, color): pieces = board.boards opcolor = 1-color material = [0, 0] for piece in range(PAWN, KING): material[WHITE] += PIECE_VALUES[piece] * bitLength(pieces[WHITE][piece]) material[BLACK] += PIECE_VALUES[piece] * bitLength(pieces[BLACK][piece]) phase = max(1, round(8 - (material[WHITE] + material[BLACK]) / 1150)) # If both sides are equal, we don't need to compute anything! if material[BLACK] == material[WHITE]: return 0, phase matTotal = sum(material) # Who is leading the game, material-wise? if material[color] > material[opcolor]: leading = color else: leading = opcolor pawns = bitLength(pieces[leading][PAWN]) matDiff = material[leading] - material[1-leading] val = min(2400, matDiff) + \ (matDiff * (12000-matTotal) * pawns) / (6400 * (pawns+1)) if leading == color: return val, phase return -val, phase #if color == WHITE: #return val, phase #else: return -val, phase ################################################################################ # evalKingTropism # ################################################################################ pawnTropism = [[0]*64 for i in xrange(64)] bishopTropism = [[0]*64 for i in xrange(64)] knightTropism = [[0]*64 for i in xrange(64)] rookTropism = [[0]*64 for i in xrange(64)] queenTropism = [[0]*64 for i in xrange(64)] for pcord in xrange(64): for kcord in xrange(pcord+1, 64): pawnTropism[pcord][kcord] = pawnTropism[kcord][pcord] = \ (14 - taxicab[pcord][kcord])**2 * 10/169 # 0 - 10 knightTropism[pcord][kcord] = knightTropism[kcord][pcord] = \ (6-distance[KNIGHT][pcord][kcord])**2 * 2 # 0 - 50 bishopTropism[pcord][kcord] = bishopTropism[kcord][pcord] = \ (14 - distance[BISHOP][pcord][kcord] * sdistance[pcord][kcord])**2 * 30/169 # 0 - 30 rookTropism[pcord][kcord] = rookTropism[kcord][pcord] = \ (14 - distance[ROOK][pcord][kcord] * sdistance[pcord][kcord])**2 * 40/169 # 0 - 40 queenTropism[pcord][kcord] = queenTropism[kcord][pcord] = \ (14 - distance[QUEEN][pcord][kcord] * sdistance[pcord][kcord])**2 * 50/169 # 0 - 50 def evalKingTropism (board, color, phase): """ All other things being equal, having your Knights, Queens and Rooks close to the opponent's king is a good thing """ opcolor = 1-color pieces = board.boards[color] oppieces = board.boards[opcolor] if phase >= 4 or not oppieces[QUEEN]: opking = board.kings[opcolor] else: opking = firstBit(oppieces[QUEEN]) score = 0 for cord in iterBits(pieces[PAWN]): score += pawnTropism[cord][opking] for cord in iterBits(pieces[KNIGHT]): score += knightTropism[cord][opking] for cord in iterBits(pieces[BISHOP]): score += bishopTropism[cord][opking] for cord in iterBits(pieces[ROOK]): score += rookTropism[cord][opking] for cord in iterBits(pieces[QUEEN]): score += queenTropism[cord][opking] return score ################################################################################ # evalPawnStructure # ################################################################################ pawntable = {} def evalPawnStructure (board, color, phase): """ Pawn evaluation is based on the following factors: 1. Pawn square tables. 2. Passed pawns. 3. Backward pawns. 4. Pawn base under attack. 5. Doubled pawns 6. Isolated pawns 7. Connected passed pawns on 6/7th rank. 8. Unmoved & blocked d, e pawn 9. Passed pawn which cannot be caught. 10. Pawn storms. Notice: The function has better precicion for current player """ boards = board.boards[color] if not boards[PAWN]: return 0 king = board.kings[color] pawns = boards[PAWN] opcolor = 1-color opking = board.kings[opcolor] opboards = board.boards[opcolor] oppawns = opboards[PAWN] #ptable = PawnTab[color] + (PawnHashKey & PHashMask) #if ptable->phase == phase and ptable->pkey == KEY(PawnHashKey): if board.pawnhash in pawntable: score, passed, weaked = pawntable[board.pawnhash] else: score = 0 passed = createBoard(0) weaked = createBoard(0) nfile = [0]*8 pScoreBoard = pawnScoreBoard[color] for cord in iterBits(pawns): score += pScoreBoard[cord] * 2 # Passed pawns if not oppawns & passedPawnMask[color][cord]: if (color == WHITE and not fromToRay[cord][cord|56] & pawns) or\ (color == BLACK and not fromToRay[cord][cord&7] & pawns): passed |= bitPosArray[cord] score += (passedScores[color][cord>>3] * phase) / 12 # Backward pawns backward = False if color == WHITE: i = cord + 8 else: i = cord - 8 ptype = color == WHITE and PAWN or BPAWN opptype = color == BLACK and PAWN or BPAWN if not 0 <= i <= 63: print toString(pawns) print board if not (passedPawnMask[opcolor][i] & ~fileBits[cord&7] & pawns) and\ board.arBoard[i] != PAWN: n1 = bitLength (pawns & moveArray[opptype][i]) n2 = bitLength (oppawns & moveArray[ptype][i]) if n1 < n2: backward = True if not backward and bitPosArray[cord] & brank7[opcolor]: i = i + (color == WHITE and 8 or -8) if not (passedPawnMask[opcolor][i] & ~fileBits[1] & pawns): n1 = bitLength (pawns & moveArray[opptype][i]) n2 = bitLength (oppawns & moveArray[ptype][i]) if n1 < n2: backward = True if backward: weaked |= bitPosArray[cord] score += -(8+phase) # Backward pawn penalty # Pawn base under attack if moveArray[ptype][cord] & oppawns and \ moveArray[ptype][cord] & pawns: score += -18 # Increment file count for isolani & doubled pawn evaluation nfile[cord&7] += 1 for i in xrange(8): # Doubled pawns if nfile[i] > 1: score += -(8+phase) # Isolated pawns if nfile[i] and not pawns & isolaniMask[i]: if not fileBits[i] & oppawns: # Isolated on a half-open file score += isolani_weaker[i] * nfile[i] else: # Normal isolated pawn score += isolani_normal[i] * nfile[i] weaked |= pawns & fileBits[i] # Penalize having eight pawns if bitLength(pawns) == 8: score -= 10 # Detect stonewall formation in enemy if stonewall[opcolor] & oppawns == stonewall[opcolor]: score -= 10 # Detect stonewall formation in our pawns if stonewall[color] & pawns == stonewall[color]: score += 10 # Penalize Locked pawns n = bitLength((pawns >> 8) & oppawns & lbox) score -= n * 10 # Opposite for opponent n = bitLength((oppawns << 8) & pawns & lbox) score += n * 10 # Save the score into the pawn hash table */ pawntable[board.pawnhash] = (score, passed, weaked) ############################################################################ # This section of the pawn code cannot be saved into the pawn hash as # # they depend on the position of other pieces. So they have to be # # calculated again. # ############################################################################ # Pawn on f6/c6 with Queen against castled king is very strong if boards[QUEEN] and opking > H6: if pawns & bitPosArray[F6] and distance[KING][opking][G7] <= 1: score += 40 if pawns & bitPosArray[C6] and distance[KING][opking][B7] <= 1: score += 40 if opboards[QUEEN] and king < A3: if oppawns & bitPosArray[F3] and distance[KING][king][G2] <= 1: score -= 20 if oppawns & bitPosArray[C3] and distance[KING][king][B2] <= 1: score -= 20 # Connected passed pawns on 6th or 7th rank t = passed & brank67[color] opMajorCount = sum(bitLength(opboards[p]) for p in xrange(KNIGHT, KING)) if t and opMajorCount == 1: n1 = FILE(opking) n2 = RANK(opking) for f in xrange(7): if t & fileBits[f] and t & fileBits[f+1] and \ (n1 < f-1 or n1 > f+1 or (color == WHITE and n2 < 4) or \ (color == BLACK and n2 > 3)): score += 50 # Penalize Pawn on d2,e2/d7,e7 is blocked blocker = board.blocker if color == WHITE and ((pawns & d2e2[WHITE]) >> 8) & blocker: score -= 48 elif color == BLACK and ((pawns & d2e2[BLACK]) << 8) & blocker: score -= 48 # Enemy has no pieces & King is outcolor of passed pawn square if passed and not opMajorCount: for cord in iterBits(passed): if board.color == color: if not squarePawnMask[color][cord] & opboards[KING]: score += passedScores[color][RANK(cord)] else: if not moveArray[KING][opking] & squarePawnMask[color][cord]: score += passedScores[color][RANK(cord)] # Estimate if any majors are able to hunt us down for pawn in iterBits(passed): found_hunter = False if color == WHITE: prom_cord = 7 << 3 | FILE(pawn) else: prom_cord = FILE(pawn) distance_to_promotion = distance[PAWN][pawn][prom_cord] for piece in xrange(KNIGHT, KING+1): for cord in iterBits(opboards[piece]): hunter_distance = distance[piece][cord][prom_cord] if hunter_distance <= distance_to_promotion: found_hunter = True break if found_hunter: break if not found_hunter: score += passedScores[color][RANK(pawn)] / 5 # If both colors are castled on different colors, bonus for pawn storms if abs(FILE(king)-FILE(opking)) >= 4 and phase < 6: n1 = FILE(opking) p = (isolaniMask[n1] | fileBits[n1]) & pawns score += sum(10 * (5 - distance[KING][c][opking]) for c in iterBits(p)) return score ################################################################################ # evalBateries # ################################################################################ def evalDoubleQR7 (board, color, phase): """ Tests for QR, RR, QB and BB combos on the 7th rank. These are dangerous to kings, and good at killing pawns """ opcolor = 1-board.color boards = board.boards[color] opboards = board.boards[opcolor] if bitLength((boards[QUEEN] | boards[ROOK]) & brank7[color]) >= 2 and \ (opboards[KING] & brank8[color] or opboards[PAWN] & brank7[color]): return 30 return 0 def evalKing (board, color, phase): # Should avoid situations like those: # r - - - n K - - # which makes forks more easy # and # R - - - K - - - # and # - - - - - - - - # - - - K - - - - # - - - - - - - - # - - - - - - - - # - - - - - - B - # which might turn bad # Also being check should be avoided, like # - q - - - K - r # and # - - - - - n - - # - - - K - - - R king = board.kings[color] opking = board.kings[1-color] # If we are in endgame, we want our king in the center, and theirs far away if phase >= 6: return endingKing[king] - endingKing[opking] # else if castled, prefer having some pawns in front elif FILE(king) not in (3,4) and RANK(king) in (0,8): if color == WHITE: if FILE(king) < 3: wall1 = frontWall[color][B1] else: wall1 = frontWall[color][G1] wall2 = wall1 >> 8 else: if FILE(king) < 3: wall1 = frontWall[color][B8] else: wall1 = frontWall[color][G8] wall2 = wall1 << 8 pawns = board.boards[color][PAWN] total_in_front = bitLength(wall1|wall2&pawns) numbermod = (0,1,2,3,2.33,1.67,1)[total_in_front] s = bitLength(wall1&pawns) + bitLength(wall2&pawns)/2. return s * numbermod * 5 return 0 def evalKnights (board, color, phase): outerring = ~lbox outer_count = bitLength (board.boards[color][KNIGHT] & outerring) return -max(15-phase,0)*outer_count def evalDev (board, color, phase): """ Calculate the development score for side (for opening only). Penalize the following. . Uncastled and cannot castled . Early queen move. - bad wing pawns """ # If we are castled or beyond the 20th move, no more evalDev if len(board.history) >= 38: return 0 score = 0 if not board.hasCastled[WHITE]: wboards = board.boards[WHITE] pawns = wboards[PAWN] # We don't encourage castling, but it should always be possible if not board.castling & W_OOO: score -= 40 if not board.castling & W_OO: score -= 50 # Should keep queen home cord = firstBit(wboards[QUEEN]) if cord != D1: score -= 30 qpawns = max(qwwingpawns1 & pawns, qwwingpawns2 & pawns) kpawns = max(kwwingpawns1 & pawns, kwwingpawns2 & pawns) if qpawns != 2 and kpawns != 2: # Structure destroyed in both sides score -= 35 else: # Discourage any wing pawn moves score += (qpawns+kpawns) *6 if not board.hasCastled[BLACK]: bboards = board.boards[BLACK] pawns = bboards[PAWN] if not board.castling & B_OOO: score += 40 if not board.castling & B_OO: score += 50 cord = firstBit(bboards[QUEEN]) if cord != D8: score += 30 qpawns = max(qbwingpawns1 & pawns, qbwingpawns2 & pawns) kpawns = max(kbwingpawns1 & pawns, kbwingpawns2 & pawns) if qpawns != 2 and kpawns != 2: # Structure destroyed in both sides score += 35 else: # Discourage any wing pawn moves score -= (qpawns+kpawns) *6 if color == BLACK: score = -score return score def evalBishops (board, color, phase): opcolor = 1-color pawns = board.boards[color][PAWN] bishops = board.boards[color][BISHOP] opbishops = board.boards[opcolor][BISHOP] oppawns = board.boards[opcolor][PAWN] arBoard = board.arBoard score = 0 # Avoid having too many pawns on you bishops color if bitLength (bishops) == 1: if bishops & WHITE_SQUARES: s = bitLength(pawns & WHITE_SQUARES) \ + bitLength(oppawns & WHITE_SQUARES)/2 else: s = bitLength(pawns & BLACK_SQUARES) \ + bitLength(oppawns & BLACK_SQUARES)/2 score -= s # In later games, try to get your pices away from opponent bishop colos if phase > 6 and bitLength (opbishops) == 1: if opbishops & WHITE_SQUARES: s = bitLength(board.friends[color] & WHITE_SQUARES) else: s = bitLength(board.friends[color] & BLACK_SQUARES) score -= s # Avoid wasted moves if color == WHITE: if bishops & bitPosArray[B5] and arBoard[C6] == EMPTY and \ oppawns & bitPosArray[B7] and oppawns & bitPosArray[C7]: score -= 50 if bishops & bitPosArray[G5] and arBoard[F6] == EMPTY and \ oppawns & bitPosArray[F7] and oppawns & bitPosArray[G7]: score -= 50 else: if bishops & bitPosArray[B4] and arBoard[C3] == EMPTY and \ oppawns & bitPosArray[B2] and oppawns & bitPosArray[C2]: score -= 50 if bishops & bitPosArray[G4] and arBoard[F3] == EMPTY and \ oppawns & bitPosArray[F2] and oppawns & bitPosArray[G2]: score -= 50 return score def evalTrappedBishops (board, color, phase): """ Check for bishops trapped at A2/H2/A7/H7 """ opcolor = 1-color opbishops = board.boards[opcolor][BISHOP] pawns = board.boards[color][PAWN] score = 0 # Don't waste time if not opbishops: return 0 if color == WHITE: if opbishops & bitPosArray[A2] and pawns & bitPosArray[B3]: see = staticExchangeEvaluate(board, newMove(A2,B3)) if see < 0: score += see if opbishops & bitPosArray[H2] and pawns & bitPosArray[G3]: see = staticExchangeEvaluate(board, newMove(H2,G3)) if see < 0: score += see else: if opbishops & bitPosArray[A7] and pawns & bitPosArray[B6]: see = staticExchangeEvaluate(board, newMove(A7,B6)) if see < 0: score += see if opbishops & bitPosArray[H7] and pawns & bitPosArray[G6]: see = staticExchangeEvaluate(board, newMove(H7,G6)) if see < 0: score += see return score def evalRooks (board, color, phase): """ rooks on open/half-open files """ opcolor = 1-color boards = board.boards[color] rooks = boards[ROOK] if not rooks: return 0 opboards = board.boards[opcolor] opking = board.kings[opcolor] score = 0 for cord in iterBits(rooks): file = cord & 7 if phase < 7: if not boards[PAWN] & fileBits[file]: if file == 5 and opking & 7 >= 4: score += 40 score += 5 if not boards[PAWN] & fileBits[file]: score += 6 return score
Python
""" This module differs from leval in that it is not optimized for speed. It checks differences between last and current board, and returns not scores, but strings describing the differences. Can be used for commenting on board changes. """ from gettext import ngettext from ldata import * from pychess.Utils.const import * from pychess.Utils.lutils.attack import staticExchangeEvaluate, getAttacks, \ defends from pychess.Utils.lutils.lmove import TCORD, FCORD, FLAG, PROMOTE_PIECE, toSAN, \ newMove from pychess.Utils.lutils.lmovegen import genCaptures, genAllMoves from pychess.Utils.lutils.validator import validateMove from pychess.Utils.repr import reprColor, reprPiece import leval def join(items): if len(items) == 1: return items[0] else: s = "%s %s %s" % (items[-2], _("and"), items[-1]) if len(items) > 2: s = ", ".join(items[:-2]+[s]) return s # # Functions can be of types: # * Final: Will be shown alone: "mates", "draws" # * Moves (s): Will always be shown: "put into *" # * Prefix: Will always be shown: "castles", "promotes" # * Attack: Will always be shown: "threaten", "preassures", "defendes" # * Simple: (s) Max one will be shown: "develops", "activity" # * State: (s) Will always be shown: "new *" # * Tip: (s) Will sometimes be shown: "pawn storm", "cramped position" # def final_status (model, ply, phase): if ply == model.ply: if model.status == DRAW: yield _("draws") elif model.status in (WHITEWON,BLACKWON): yield _("mates") def offencive_moves_check (model, ply, phase): if model.getBoardAtPly(ply).board.isChecked(): yield _("puts opponent in check") def defencive_moves_safety (model, ply, phase): board = model.getBoardAtPly(ply).board oldboard = model.getBoardAtPly(ply-1).board if board.arBoard[TCORD(model.getMoveAtPly(ply-1).move)] != KING: return color = oldboard.color opcolor = 1-color delta_eval_king = leval.evalKing(board, color, phase) - \ leval.evalKing(oldboard, color, phase) # PyChess points tropism to queen for phase <= 3. Thus we set a high phase delta_eval_tropism = leval.evalKingTropism(board, opcolor, 10) - \ leval.evalKingTropism(oldboard, opcolor, 10) # Notice, that tropism was negative delta_score = delta_eval_king - delta_eval_tropism/2 if delta_score > 35: yield _("improves king safety") elif delta_score > 15: yield _("slightly improves king safety") def offencive_moves_rook (model, ply, phase): move = model.getMoveAtPly(ply-1).move fcord = FCORD(move) tcord = TCORD(move) board = model.getBoardAtPly(ply).board color = 1-board.color opcolor = 1-color # We also detect rook-to-open castlings if board.arBoard[tcord] == KING: if FLAG(move) == QUEEN_CASTLE: fcord = board.ini_rooks[color][0] tcord = tcord+1 elif FLAG(move) == KING_CASTLE: fcord = board.ini_rooks[color][1] tcord = tcord-1 if board.arBoard[tcord] != ROOK: return color = 1-board.color opcolor = 1-color pawns = board.boards[color][PAWN] oppawns = board.boards[opcolor][PAWN] ffile = fileBits[FILE(FCORD(move))] tfile = fileBits[FILE(tcord)] if ffile & pawns and not tfile & pawns and bitLength(pawns) >= 3: if not tfile & oppawns: yield _("moves a rook to an open file") else: yield _("moves an rook to a half-open file") def offencive_moves_fianchetto (model, ply, phase): board = model.getBoardAtPly(ply).board tcord = TCORD(model.getMoveAtPly(ply-1).move) movingcolor = 1-board.color if movingcolor == WHITE: if board.castling & W_OO and tcord == G2: yield _("moves bishop into fianchetto: %s") % "g2" elif board.castling & W_OOO and tcord == B2: yield _("moves bishop into fianchetto: %s") % "b2" else: if board.castling & B_OO and tcord == G7: yield _("moves bishop into fianchetto: %s") % "g7" elif board.castling & B_OOO and tcord == B7: yield _("moves bishop into fianchetto: %s") % "b7" def prefix_type (model, ply, phase): flag = FLAG(model.getMoveAtPly(ply-1).move) if flag in PROMOTIONS: yield _("promotes a Pawn to a %s") % reprPiece[PROMOTE_PIECE(flag)] elif flag in (KING_CASTLE, QUEEN_CASTLE): yield _("castles") def attack_type (model, ply, phase): # We set bishop value down to knight value, as it is what most people expect bishopBackup = PIECE_VALUES[BISHOP] PIECE_VALUES[BISHOP] = PIECE_VALUES[KNIGHT] board = model.getBoardAtPly(ply).board oldboard = model.getBoardAtPly(ply-1).board if ply - model.lowply >= 2: oldmove = model.getMoveAtPly(ply-2).move oldboard3 = model.getBoardAtPly(ply-2).board else: oldmove = None move = model.getMoveAtPly(ply-1).move tcord = TCORD(move) if oldboard.arBoard[tcord] != EMPTY: if not (board.variant == FISCHERRANDOMCHESS and \ FLAG(move) in (KING_CASTLE, QUEEN_CASTLE)): if oldmove and oldboard3.arBoard[TCORD(oldmove)] != EMPTY and \ TCORD(oldmove) == tcord: yield _("takes back material") else: see = staticExchangeEvaluate(oldboard, move) if see < 0: yield _("sacrifies material") elif see == 0: yield _("exchanges material") elif see > 0: yield _("captures material") PIECE_VALUES[BISHOP] = bishopBackup def defencive_moves_tactic (model, ply, phase): # ------------------------------------------------------------------------ # # Test if we threat something, or at least put more pressure on it # # ------------------------------------------------------------------------ # # We set bishop value down to knight value, as it is what most people expect bishopBackup = PIECE_VALUES[BISHOP] PIECE_VALUES[BISHOP] = PIECE_VALUES[KNIGHT] board = model.getBoardAtPly(ply).board oldboard = model.getBoardAtPly(ply-1).board move = model.getMoveAtPly(ply-1).move fcord = FCORD(move) tcord = TCORD(move) piece = board.arBoard[tcord] found_threatens = [] found_increases = [] # What do we attack now? board.setColor(1-board.color) for ncap in genCaptures(board): # getCaptures also generate promotions if FLAG(ncap) in PROMOTIONS: continue # We are only interested in the attacks of the piece we just moved if FCORD(ncap) != TCORD (move): continue # We don't want to move back if TCORD(ncap) == FCORD(move): continue # We don't thread the king. We check him! (in another function) if board.arBoard[TCORD(ncap)] == KING: continue # If we also was able to attack that cord last time, we don't care if validateMove(oldboard, newMove(FCORD(move), TCORD(ncap))): continue # Test if we threats our enemy, at least more than before see0 = staticExchangeEvaluate(oldboard, TCORD(ncap), 1-oldboard.color) see1 = staticExchangeEvaluate(board, TCORD(ncap), 1-oldboard.color) if see1 > see0: # If a new winning capture has been created if see1 > 0: # Find the easiest attack attacks = getAttacks (board, TCORD(ncap), board.color) v, cord = min((PIECE_VALUES[board.arBoard[fc]],fc) for fc in iterBits(attacks)) easiestAttack = newMove(cord, TCORD(ncap)) found_threatens.append(toSAN(board,easiestAttack, True)) # Even though we might not yet be strong enough, we might still # have strengthened another friendly attack else: found_increases.append(reprCord[TCORD(ncap)]) board.setColor(1-board.color) # -------------------------------------------------------------------- # # Test if we defend a one of our pieces # # -------------------------------------------------------------------- # found_defends = [] # Test which pieces were under attack used = [] for ncap in genCaptures(board): # getCaptures also generate promotions if FLAG(ncap) in PROMOTIONS: continue # We don't want to know about the same cord more than once if TCORD(ncap) in used: continue used.append(TCORD(ncap)) # If the attack was poining on the piece we just moved, we ignore it if TCORD(ncap) == FCORD(move) or TCORD(ncap) == TCORD(move): continue # If we were already defending the piece, we don't send a new # message if defends(oldboard, FCORD(move), TCORD(ncap)): continue # If the attack was not strong, we ignore it see = staticExchangeEvaluate(oldboard, ncap) if see < 0: continue v = defends(board, TCORD(move), TCORD(ncap)) # If the defend didn't help, it doesn't matter. Like defending a # bishop, threatened by a pawn, with a queen. # But on the other hand - it might still be a defend... # newsee = staticExchangeEvaluate(board, ncap) # if newsee <= see: continue if v: found_defends.append(reprCord[TCORD(ncap)]) # ------------------------------------------------------------------------ # # Test if we are rescuing an otherwise exposed piece # # ------------------------------------------------------------------------ # # Rescuing is only an option, if our own move wasn't an attack if oldboard.arBoard[tcord] == EMPTY: see0 = staticExchangeEvaluate(oldboard, fcord, oldboard.color) see1 = staticExchangeEvaluate(board, tcord, oldboard.color) if see1 > see0 and see1 > 0: yield _("rescues a %s") % reprPiece[board.arBoard[tcord]].lower() if found_threatens: yield _("threatens to win material by %s") % join(found_threatens) if found_increases: yield _("increases the pressure on %s") % join(found_increases) if found_defends: yield _("defends %s") % join(found_defends) PIECE_VALUES[BISHOP] = bishopBackup def offencive_moves_pin (model, ply, phase): board = model.getBoardAtPly(ply).board move = model.getMoveAtPly(ply-1).move fcord = FCORD(move) tcord = TCORD(move) piece = board.arBoard[tcord] ray = createBoard(0) if piece in (BISHOP, QUEEN): ray |= (ray45[tcord] | ray135[tcord]) & ~(ray45[fcord] | ray135[fcord]) if piece in (ROOK, QUEEN): ray |= (ray00[tcord] | ray90[tcord]) & ~(ray00[fcord] | ray90[fcord]) if ray: for c in iterBits(ray & board.friends[board.color]): # We don't pin on pieces that are less worth than us if not PIECE_VALUES[piece] < PIECE_VALUES[board.arBoard[c]]: continue # There should be zero friendly pieces in between ray = fromToRay[tcord][c] if ray & board.friends[1-board.color]: continue # There should be exactly one opponent piece in between op = clearBit(ray & board.friends[board.color], c) if bitLength(op) != 1: continue # The king can't be pinned pinned = lastBit(op) oppiece = board.arBoard[pinned] if oppiece == KING: continue # Yield yield _("pins an enemy %(oppiece)s on the %(piece)s at %(cord)s") % { 'oppiece': reprPiece[oppiece].lower(), 'piece': reprPiece[board.arBoard[c]].lower(), 'cord': reprCord[c]} def state_outpost (model, ply, phase): if phase >= 6: # Doesn't make sense in endgame return board = model.getBoardAtPly(ply).board oldboard = model.getBoardAtPly(ply-1).board color = 1-board.color opcolor = 1-color wpawns = board.boards[WHITE][PAWN] oldwpawns = oldboard.boards[WHITE][PAWN] bpawns = board.boards[BLACK][PAWN] oldbpawns = oldboard.boards[BLACK][PAWN] wpieces = board.boards[WHITE][BISHOP] | board.boards[WHITE][KNIGHT] oldwpieces = oldboard.boards[WHITE][BISHOP] | oldboard.boards[WHITE][KNIGHT] bpieces = board.boards[BLACK][BISHOP] | board.boards[BLACK][KNIGHT] oldbpieces = oldboard.boards[BLACK][BISHOP] | oldboard.boards[BLACK][KNIGHT] for cord in iterBits(wpieces): sides = isolaniMask[FILE(cord)] front = passedPawnMask[WHITE][cord] if outpost[WHITE][cord] and not bpawns & sides & front and \ (not oldwpieces & bitPosArray[cord] or \ oldbpawns & sides & front): yield 35, _("White has a new piece in outpost: %s") % reprCord[cord] for cord in iterBits(bpieces): sides = isolaniMask[FILE(cord)] front = passedPawnMask[BLACK][cord] if outpost[BLACK][cord] and not wpawns & sides & front and \ (not oldbpieces & bitPosArray[cord] or \ oldwpawns & sides & front): yield 35, _("Black has a new piece in outpost: %s") % reprCord[cord] def state_pawn (model, ply, phase): board = model.getBoardAtPly(ply).board oldboard = model.getBoardAtPly(ply-1).board color = 1-board.color opcolor = 1-color move = model.getMoveAtPly(ply-1).move pawns = board.boards[color][PAWN] oppawns = board.boards[opcolor][PAWN] oldpawns = oldboard.boards[color][PAWN] oldoppawns = oldboard.boards[opcolor][PAWN] # Passed pawns for cord in iterBits(pawns): if not oppawns & passedPawnMask[color][cord]: if color == WHITE: frontCords = fromToRay[cord][cord|56] else: frontCords = fromToRay[cord][cord&7] if frontCords & pawns: continue # Was this a passed pawn before? if oldpawns & bitPosArray[cord] and \ not oldoppawns & passedPawnMask[color][cord] and \ not frontCords & oldpawns: continue # Is this just a passed pawn that has been moved? if TCORD(move) == cord: frontCords |= bitPosArray[cord] if not frontCords & oldpawns and \ not oldoppawns & passedPawnMask[color][FCORD(move)]: continue score = (passedScores[color][cord>>3] * phase) yield score, _("%(color)s has a new passed pawn on %(cord)s") % { 'color': reprColor[color], 'cord': reprCord[cord]} # Double pawns found_doubles = [] found_halfopen_doubles = [] found_white_isolates = [] found_black_isolates = [] for file in range(8): bits = fileBits[file] count = bitLength(pawns & bits) oldcount = bitLength(oldpawns & bits) opcount = bitLength(oppawns & bits) oldopcount = bitLength(oldoppawns & bits) # Single pawn -> double pawns if count > oldcount >= 1: if not opcount: found_halfopen_doubles.append(reprFile[file]) else: found_doubles.append(reprFile[file]) # Closed file double pawn -> half-open file double pawn elif count > 1 and opcount == 0 and oldopcount > 0: found_halfopen_doubles.append(reprFile[file]) # Isolated pawns if color == WHITE: wpawns = pawns oldwpawns = oldpawns bpawns = oppawns oldbpawns = oldoppawns else: bpawns = pawns oldbpawns = oldpawns wpawns = oppawns oldwpawns = oldoppawns if wpawns & bits and not wpawns & isolaniMask[file] and \ (not oldwpawns & bits or oldwpawns & isolaniMask[file]): found_white_isolates.append(reprFile[file]) if bpawns & bits and not bpawns & isolaniMask[file] and \ (not oldbpawns & bits or oldbpawns & isolaniMask[file]): found_black_isolates.append(reprFile[file]) # We need to take care of 'worstcases' like: "got new double pawns in the a # file, in the half-open b, c and d files and in the open e and f files" doubles_count = len(found_doubles) + len(found_halfopen_doubles) if doubles_count > 0: parts = [] for type_, list_ in (("", found_doubles), (_("half-open")+" ", found_halfopen_doubles)): if len(list_) == 1: parts.append(_("in the %(x)s%(y)s file") % {'x': type_, 'y': list_[0]}) elif len(list_) >= 2: parts.append(_("in the %(x)s%(y)s files") % {'x': type_, 'y': join(list_)}) if doubles_count == 1: s = _("%(color)s got a double pawn %(place)s") else: s = _("%(color)s got new double pawns %(place)s") yield (8+phase)*2*doubles_count, s % {'color': reprColor[color], 'place': join(parts)} for (color_, list_) in ((WHITE, found_white_isolates), (BLACK, found_black_isolates)): if list_: yield 20*len(list_), ngettext("%(color)s got an isolated pawn in the %(x)s file", "%(color)s got isolated pawns in the %(x)s files", len(list_)) % {'color': reprColor[color_], 'x': join(list_)} # Stone wall if stonewall[color] & pawns == stonewall[color] and \ stonewall[color] & oldpawns != stonewall[color]: yield 10, _("%s moves pawns into stonewall formation") % reprColor[color] def state_destroysCastling (model, ply, phase): """ Does the move destroy the castling ability of the opponent """ # If the move is a castling, nobody will every care if the castling # possibilities has changed if FLAG(model.getMoveAtPly(ply-1).move) in (QUEEN_CASTLE, KING_CASTLE): return oldcastling = model.getBoardAtPly(ply-1).board.castling castling = model.getBoardAtPly(ply).board.castling if oldcastling & W_OOO and not castling & W_OOO: if oldcastling & W_OO and not castling & W_OO: yield 900/phase, _("%s can no longer castle") % reprColor[WHITE] else: yield 400/phase, _("%s can no longer castle in queenside") % reprColor[WHITE] elif oldcastling & W_OO and not castling & W_OO: yield 500/phase, _("%s can no longer castle in kingside") % reprColor[WHITE] if oldcastling & B_OOO and not castling & B_OOO: if oldcastling & B_OO and not castling & B_OO: yield 900/phase, _("%s can no longer castle") % reprColor[BLACK] else: yield 400/phase, _("%s can no longer castle in queenside") % reprColor[BLACK] elif oldcastling & B_OO and not castling & B_OO: yield 500/phase, _("%s can no longer castle in kingside") % reprColor[BLACK] def state_trappedBishops (model, ply, phase): """ Check for bishops trapped at A2/H2/A7/H7 """ board = model.getBoardAtPly(ply).board oldboard = model.getBoardAtPly(ply-1).board opcolor = board.color color = 1-opcolor move = model.getMoveAtPly(ply-1).move tcord = TCORD(move) # Only a pawn is able to trap a bishop if board.arBoard[tcord] != PAWN: return if tcord == B3: cord = A2 elif tcord == G3: cord = H2 elif tcord == B6: cord = A7 elif tcord == G6: cord = H7 else: return s = leval.evalTrappedBishops (board, opcolor, phase) olds = leval.evalTrappedBishops (oldboard, opcolor, phase) # We have got more points -> We have trapped a bishop if s > olds: yield 300/phase, _("%(opcolor)s has a new trapped bishop on %(cord)s") % { 'opcolor': reprColor[opcolor], 'cord': reprCord[cord]} def simple_tropism (model, ply, phase): board = model.getBoardAtPly(ply).board oldboard = model.getBoardAtPly(ply-1).board color = oldboard.color move = model.getMoveAtPly(ply-1).move fcord = FCORD(move) tcord = TCORD(move) arBoard = board.arBoard if arBoard[tcord] != PAWN: score = leval.evalKingTropism(board, color, phase) oldscore = leval.evalKingTropism(oldboard, color, phase) else: if color == WHITE: rank23 = brank67[BLACK] else: rank23 = brank67[WHITE] if bitPosArray[fcord] & rank23: yield 2, _("develops a pawn: %s") % reprCord[tcord] else: yield 1, _("brings a pawn closer to the backrow: %s") % \ reprCord[tcord] return king = board.kings[color] opking = board.kings[1-color] if score > oldscore: # in FISCHERRANDOMCHESS unusual casting case the tcord is # the involved rook's position, not the king's destination! flag = move >> 12 if flag in (KING_CASTLE, QUEEN_CASTLE): piece = KING else: piece = arBoard[tcord] if phase >= 5 or distance[piece][fcord][opking] < \ distance[piece][fcord][king]: yield score-oldscore, _("brings a %(piece)s closer to enemy king: %(cord)s") % { 'piece': reprPiece[piece], 'cord': reprCord[tcord]} else: yield (score-oldscore)*2, _("develops a %(piece)s: %(cord)s") % { 'piece': reprPiece[piece].lower(), 'cord': reprCord[tcord]} def simple_activity (model, ply, phase): board = model.getBoardAtPly(ply).board oldboard = model.getBoardAtPly(ply-1).board color = 1-board.color move = model.getMoveAtPly(ply-1).move fcord = FCORD(move) tcord = TCORD(move) board.setColor(1-board.color) moves = len([m for m in genAllMoves(board) if FCORD(m) == tcord]) board.setColor(1-board.color) oldmoves = len([m for m in genAllMoves(oldboard) if FCORD(m) == fcord]) if moves > oldmoves: yield (moves-oldmoves)/2, _("places a %(piece)s more active: %(cord)s") % { 'piece': reprPiece[board.arBoard[tcord]].lower(), 'cord': reprCord[tcord]} def tip_pawnStorm (model, ply, phase): """ If players are castled in different directions we should storm in opponent side """ if phase >= 6: # We don't use this in endgame return board = model.getBoardAtPly(ply).board #if not board.hasCastled[WHITE] or not board.hasCastled[BLACK]: # # Only applies after castling for both sides # return wking = board.boards[WHITE][KING] bking = board.boards[BLACK][KING] wleft = bitLength(board.boards[WHITE][PAWN] & left) wright = bitLength(board.boards[WHITE][PAWN] & right) bleft = bitLength(board.boards[BLACK][PAWN] & left) bright = bitLength(board.boards[BLACK][PAWN] & right) if wking & left and bking & right: if wright > bright: yield (wright+3-bright)*10, _("White should do pawn storm in right") elif bleft > wleft: yield (bright+3-wright)*10, _("Black should do pawn storm in left") if wking & right and bking & left: if wleft > bleft: yield (wleft+3-bleft)*10, _("White should do pawn storm in left") if bright > wright: yield (bleft+3-wleft)*10, _("Black should do pawn storm in right") def tip_mobility (model, ply, phase): board = model.getBoardAtPly(ply).board colorBackup = board.color # People need a chance to get developed #if model.ply < 16: # return board.setColor(WHITE) wmoves = len([move for move in genAllMoves(board) if \ KNIGHT <= board.arBoard[FCORD(move)] <= QUEEN and \ bitPosArray[TCORD(move)] & brank48[WHITE] and \ staticExchangeEvaluate(board, move) >= 0]) board.setColor(BLACK) bmoves = len([move for move in genAllMoves(board) if \ KNIGHT <= board.arBoard[FCORD(move)] <= QUEEN and \ bitPosArray[TCORD(move)] & brank48[BLACK] and \ staticExchangeEvaluate(board, move) >= 0]) board.setColor(colorBackup) #print wmoves, bmoves, phase #wb = board.boards[WHITE] #print float(wmoves)/bitLength(wb[KNIGHT]|wb[BISHOP]|wb[ROOK]|wb[QUEEN]) #bb = board.boards[WHITE] #print float(bmoves)/bitLength(bb[KNIGHT]|bb[BISHOP]|bb[ROOK]|bb[QUEEN]) if wmoves-phase >= (bmoves+1)*7: yield wmoves-bmoves, _("Black has a rather cramped position") elif wmoves-phase >= (bmoves+1)*3: yield wmoves-bmoves, _("Black has a slightly cramped position") elif bmoves-phase >= (wmoves+1)*7: yield wmoves-bmoves, _("White has a rather cramped position") elif bmoves-phase >= (wmoves+1)*3: yield wmoves-bmoves, _("White has a slightly cramped position")
Python
from bitboard import bitLength from ldata import BLACK_SQUARES from pychess.Utils.const import * def repetitionCount (board, drawThreshold=3): rc = 1 for ply in xrange(4, 1+min(len(board.history), board.fifty), 2): if board.history[-ply] is None: break # Game started from a position; early history is unavailable. if board.history[-ply][4] == board.hash: rc += 1 if rc >= drawThreshold: break return rc def testFifty (board): if board.fifty >= 100: return True return False drawSet = set(( (0, 0, 0, 0, 0, 0, 0, 0), #KK (0, 1, 0, 0, 0, 0, 0, 0), #KBK (1, 0, 0, 0, 0, 0, 0, 0), #KNK (0, 0, 0, 0, 0, 1, 0, 0), #KKB (0, 0, 0, 0, 1, 0, 0, 0), #KNK (1, 0, 0, 0, 0, 1, 0, 0), #KNKB (0, 1, 0, 0, 1, 0, 0, 0), #KBKN )) # Contains not 100% sure ones drawSet2 = set(( (2, 0, 0, 0, 0, 0, 0, 0), #KNNK (0, 0, 0, 0, 2, 0, 0, 0), #KKNN (2, 0, 0, 0, 1, 0, 0, 0), #KNNKN (1, 0, 0, 0, 2, 0, 0, 0), #KNKNN (2, 0, 0, 0, 0, 1, 0, 0), #KNNKB (0, 1, 0, 0, 2, 0, 0, 0), #KBKNN (2, 0, 0, 0, 0, 0, 1, 0), #KNNKR (0, 0, 1, 0, 2, 0, 0, 0) #KRKNN )) def testMaterial (board): """ Tests if no players are able to win the game from the current position """ whiteBoards = board.boards[WHITE] blackBoards = board.boards[BLACK] if bitLength(whiteBoards[PAWN]) or bitLength(blackBoards[PAWN]): return False if bitLength(whiteBoards[QUEEN]) or bitLength(blackBoards[QUEEN]): return False wn = bitLength(whiteBoards[KNIGHT]) wb = bitLength(whiteBoards[BISHOP]) wr = bitLength(whiteBoards[ROOK]) bn = bitLength(blackBoards[KNIGHT]) bb = bitLength(blackBoards[BISHOP]) br = bitLength(blackBoards[ROOK]) if (wn, wb, wr, 0, bn, bb, br, 0) in drawSet: return True # Tests KBKB. Draw if bishops are of same color if not wn + wr + bn + wr and wb == 1 and bb == 1: if whiteBoards[BISHOP] & BLACK_SQUARES and True != \ blackBoards[BISHOP] & BLACK_SQUARES and True: return True def testPlayerMatingMaterial (board, color): """ Tests if given color has enough material to mate on board """ boards = board.boards[color] if bitLength(boards[PAWN]) or bitLength(boards[QUEEN]) \ or bitLength(boards[ROOK]) \ or (bitLength(boards[KNIGHT]) + bitLength(boards[BISHOP]) > 1): return True return False # This could be expanded by the fruit kpk draw function, which can test if a # certain king verus king and pawn posistion is winable. def test (board): """ Test if the position is drawn. Two-fold repetitions are counted. """ return repetitionCount (board, drawThreshold=2) > 1 or \ testFifty (board) or \ testMaterial (board)
Python
# -*- coding: UTF-8 -*- import string from ldata import * from validator import validateMove from pychess.Utils.const import * from pychess.Utils.repr import reprPiece, localReprSign def RANK (cord): return cord >> 3 def FILE (cord): return cord & 7 def TCORD (move): return move & 63 def FCORD (move): return move >> 6 & 63 def FLAG (move): return move >> 12 def PROMOTE_PIECE (flag): return flag -2 def FLAG_PIECE (piece): return piece +2 ################################################################################ # The format of a move is as follows - from left: # # 4 bits: Descriping the type of the move # # 6 bits: cord to move from # # 6 bits: cord to move to # ################################################################################ shiftedFromCords = [] for i in range(64): shiftedFromCords.append(i << 6) shiftedFlags = [] for i in NORMAL_MOVE, QUEEN_CASTLE, KING_CASTLE, ENPASSANT, \ KNIGHT_PROMOTION, BISHOP_PROMOTION, ROOK_PROMOTION, QUEEN_PROMOTION: shiftedFlags.append(i << 12) def newMove (fromcord, tocord, flag=NORMAL_MOVE): return shiftedFlags[flag] + shiftedFromCords[fromcord] + tocord class ParsingError (Exception): """ Please raise this with a 3-tupple: (move, reason, board.asFen()) The reason should be usable in the context: 'Move was not parseable because %s' % reason """ pass ################################################################################ # parseAny # ################################################################################ def parseAny (board, algnot): type = determineAlgebraicNotation (algnot) if type == SAN: return parseSAN (board, algnot) if type == AN: return parseAN (board, algnot) if type == LAN: return parseLAN (board, algnot) return parseFAN (board, algnot) def determineAlgebraicNotation (algnot): upnot = algnot.upper() if upnot in ("O-O", "O-O-O", "0-0", "0-0-0"): return SAN # Test for e2-e4 if "-" in algnot: return LAN # Test for b4xc5 if "x" in algnot and algnot.split('x')[0] in cordDic: return LAN # Test for e2e4 or a7a8q or a7a8=q if algnot[:2] in cordDic and algnot[2:4] in cordDic: return AN if algnot[0] in FAN_PIECES[WHITE] or algnot[0] in FAN_PIECES[BLACK]: return FAN return SAN ################################################################################ # listToSan # ################################################################################ def listToSan (board, moves): # Work on a copy to ensure we don't break things board = board.clone() sanmoves = [] for move in moves: san = toSAN (board, move) sanmoves.append(san) board.applyMove(move) return sanmoves ################################################################################ # listToMoves # ################################################################################ def listToMoves (board, movstrs, type=None, testvalidate=False, ignoreErrors=False): # Work on a copy to ensure we don't break things board = board.clone() moves = [] for mstr in movstrs: try: if type == None: move = parseAny (board, mstr) elif type == SAN: move = parseSAN (board, mstr) elif type == AN: move = parseAN (board, mstr) elif type == LAN: move = parseLAN (board, mstr) except ParsingError: if ignoreErrors: break raise if testvalidate: if not validateMove (board, move): if not ignoreErrors: raise ParsingError, (mstr, 'Validation', board.asFen()) break moves.append(move) board.applyMove(move) return moves ################################################################################ # toSan # ################################################################################ def toSAN (board, move, localRepr=False): """ Returns a Short/Abbreviated Algebraic Notation string of a move The board should be prior to the move """ # Has to be importet at calltime, as lmovegen imports lmove from lmovegen import genAllMoves def check_or_mate(): board_clone = board.clone() board_clone.applyMove(move) sign = "" if board_clone.isChecked(): for altmove in genAllMoves (board_clone): board_clone.applyMove(altmove) if board_clone.opIsChecked(): board_clone.popMove() continue sign = "+" break else: sign = "#" return sign flag = move >> 12 if flag == KING_CASTLE: return "O-O%s" % check_or_mate() elif flag == QUEEN_CASTLE: return "O-O-O%s" % check_or_mate() fcord = (move >> 6) & 63 tcord = move & 63 fpiece = board.arBoard[fcord] tpiece = board.arBoard[tcord] part0 = "" part1 = "" if fpiece != PAWN: if localRepr: part0 += localReprSign[fpiece] else: part0 += reprSign[fpiece] part1 = reprCord[tcord] if not fpiece in (PAWN, KING): xs = [] ys = [] board_clone = board.clone() for altmove in genAllMoves(board_clone): mfcord = FCORD(altmove) if board_clone.arBoard[mfcord] == fpiece and \ mfcord != fcord and \ TCORD(altmove) == tcord: board_clone.applyMove(altmove) if not board_clone.opIsChecked(): xs.append(FILE(mfcord)) ys.append(RANK(mfcord)) board_clone.popMove() x = FILE(fcord) y = RANK(fcord) if ys or xs: if y in ys and not x in xs: # If we share rank with another piece, but not file part0 += reprFile[x] elif x in xs and not y in ys: # If we share file with another piece, but not rank part0 += reprRank[y] elif x in xs and y in ys: # If we share both file and rank with other pieces part0 += reprFile[x] + reprRank[y] else: # If we doesn't share anything, it is standard to put file part0 += reprFile[x] if tpiece != EMPTY or flag == ENPASSANT: part1 = "x" + part1 if fpiece == PAWN: part0 += reprFile[FILE(fcord)] notat = part0 + part1 if flag in PROMOTIONS: if localRepr: notat += "="+localReprSign[PROMOTE_PIECE(flag)] else: notat += "="+reprSign[PROMOTE_PIECE(flag)] return "%s%s" % (notat, check_or_mate()) ################################################################################ # parseSan # ################################################################################ def parseSAN (board, san): """ Parse a Short/Abbreviated Algebraic Notation string """ if not san: raise ParsingError, (san, _("the move is an empty string"), board.asFen()) elif len(san) < 2: raise ParsingError, (san, _("the move is too short"), board.asFen()) notat = san if notat[-1] in ("+", "#"): notat = notat[:-1] flag = NORMAL_MOVE # If last char is a piece char, we assue it the promote char c = notat[-1].lower() if c in chr2Sign: flag = chr2Sign[c] + 2 if notat[-2] == "=": notat = notat[:-2] else: notat = notat[:-1] if len(notat) < 2: raise ParsingError, (san, _("the move needs a piece and a cord"), board.asFen()) notat = notat.replace("0","O").replace("o","O") if notat.startswith("O-O"): if board.color == WHITE: fcord = board.ini_kings[0] #E1 if notat == "O-O": flag = KING_CASTLE if board.variant == FISCHERRANDOMCHESS: tcord = board.ini_rooks[0][1] else: tcord = G1 else: flag = QUEEN_CASTLE if board.variant == FISCHERRANDOMCHESS: tcord = board.ini_rooks[0][0] else: tcord = C1 else: fcord = board.ini_kings[1] #E8 if notat == "O-O": flag = KING_CASTLE if board.variant == FISCHERRANDOMCHESS: tcord = board.ini_rooks[1][1] else: tcord = G8 else: flag = QUEEN_CASTLE if board.variant == FISCHERRANDOMCHESS: tcord = board.ini_rooks[1][0] else: tcord = C8 return newMove (fcord, tcord, flag) if notat[0] in ("Q", "R", "B", "K", "N"): piece = chr2Sign[notat[0].lower()] notat = notat[1:] else: piece = PAWN if "x" in notat: notat, tcord = notat.split("x") if not tcord in cordDic: raise ParsingError, ( san, _("the captured cord (%s) is incorrect") % tcord, board.asFen()) tcord = cordDic[tcord] if piece == PAWN: # If a pawn is attacking an empty cord, we assue it an enpassant if board.arBoard[tcord] == EMPTY: flag = ENPASSANT else: if not notat[-2:] in cordDic: raise ParsingError, ( san, "the end cord (%s) is incorrect" % notat[-2:], board.asFen()) tcord = cordDic[notat[-2:]] notat = notat[:-2] # If there is any extra location info, like in the move Bexd1 or Nh3f4 we # want to know frank = None ffile = None if notat and notat[0] in reprRank: frank = int(notat[0])-1 notat = notat[1:] if notat and notat[0] in reprFile: ffile = ord(notat[0]) - ord("a") notat = notat[1:] if notat and notat[0] in reprRank: frank = int(notat[0])-1 notat = notat[1:] # We find all pieces who could have done it. (If san was legal, there should # never be more than one) from lmovegen import genAllMoves for move in genAllMoves(board): if TCORD(move) != tcord: continue f = FCORD(move) if board.arBoard[f] != piece: continue if frank != None and frank != RANK(f): continue if ffile != None and ffile != FILE(f): continue if flag in PROMOTIONS and FLAG(move) != flag: continue board_clone = board.clone() board_clone.applyMove(move) if board_clone.opIsChecked(): continue return move errstring = "no %s is able to move to %s" % (reprPiece[piece], reprCord[tcord]) raise ParsingError, (san, errstring, board.asFen()) ################################################################################ # toLan # ################################################################################ def toLAN (board, move): """ Returns a Long/Expanded Algebraic Notation string of a move board should be prior to the move """ fcord = FCORD(move) tcord = TCORD(move) s = "" if board.arBoard[fcord] != PAWN: s = reprSign[board.arBoard[fcord]] s += reprCord[FCORD(move)] if board.arBoard[tcord] == EMPTY: s += "-" else: s += "x" s += reprCord[tcord] flag = FLAG(move) if flag in PROMOTIONS: s += "=" + reprSign[PROMOTE_PIECE(flag)] return s ################################################################################ # parseLan # ################################################################################ def parseLAN (board, lan): """ Parse a Long/Expanded Algebraic Notation string """ # To parse LAN pawn moves like "e2-e4" as SAN moves, we have to remove a few # fields if len(lan) == 5: if "x" in lan: # e4xd5 -> exd5 return parseSAN (board, lan[0]+lan[3:]) else: # e2-e4 -> e4 return parseSAN (board, lan[3:]) # We want to use the SAN parser for LAN moves like "Nb1-c3" or "Rd3xd7" # The san parser should be able to handle most stuff, as long as we remove # the slash if not lan.upper().startswith("O-O"): lan = lan.replace("-","") return parseSAN (board, lan) ################################################################################ # toAN # ################################################################################ def toAN (board, move, short=False): """ Returns a Algebraic Notation string of a move board should be prior to the move short -- returns the short variant, e.g. f7f8q rather than f7f8=Q """ s = reprCord[FCORD(move)] + reprCord[TCORD(move)] if board.variant == FISCHERRANDOMCHESS: flag = move >> 12 if flag == KING_CASTLE: return "O-O" elif flag == QUEEN_CASTLE: return "O-O-O" if FLAG(move) in PROMOTIONS: if short: s += reprSign[PROMOTE_PIECE(FLAG(move))].lower() else: s += "=" + reprSign[PROMOTE_PIECE(FLAG(move))] return s ################################################################################ # parseAN # ################################################################################ def parseAN (board, an): """ Parse an Algebraic Notation string """ if not 4 <= len(an) <= 6: raise ParsingError, (an, "the move must be 4 or 6 chars long", board.asFen()) try: fcord = cordDic[an[:2]] tcord = cordDic[an[2:4]] except KeyError, e: raise ParsingError, (an, "the cord (%s) is incorrect" % e.args[0], board.asFen()) flag = NORMAL_MOVE if len(an) == 5: #The a7a8q variant flag = chr2Sign[an[4].lower()] + 2 elif len(an) == 6: #The a7a8=q variant flag = chr2Sign[an[5].lower()] + 2 elif board.arBoard[fcord] == KING: if board.variant == FISCHERRANDOMCHESS and board.arBoard[tcord] == ROOK: color = board.color friends = board.friends[color] if bitPosArray[tcord] & friends: if board.ini_rooks[color][0] == tcord: flag = QUEEN_CASTLE else: flag = KING_CASTLE elif fcord - tcord == 2: flag = QUEEN_CASTLE elif fcord - tcord == -2: flag = KING_CASTLE else: flag = NORMAL_MOVE elif board.arBoard[fcord] == PAWN and board.arBoard[tcord] == EMPTY and \ FILE(fcord) != FILE(tcord) and RANK(fcord) != RANK(tcord): flag = ENPASSANT return newMove (fcord, tcord, flag) ################################################################################ # toFAN # ################################################################################ san2WhiteFanDic = { ord(u"K"): FAN_PIECES[WHITE][KING], ord(u"Q"): FAN_PIECES[WHITE][QUEEN], ord(u"R"): FAN_PIECES[WHITE][ROOK], ord(u"B"): FAN_PIECES[WHITE][BISHOP], ord(u"N"): FAN_PIECES[WHITE][KNIGHT], ord(u"+"): u"†", ord(u"#"): u"‡" } san2BlackFanDic = { ord(u"K"): FAN_PIECES[BLACK][KING], ord(u"Q"): FAN_PIECES[BLACK][QUEEN], ord(u"R"): FAN_PIECES[BLACK][ROOK], ord(u"B"): FAN_PIECES[BLACK][BISHOP], ord(u"N"): FAN_PIECES[BLACK][KNIGHT], ord(u"+"): u"†", ord(u"#"): u"‡" } def toFAN (board, move): """ Returns a Figurine Algebraic Notation string of a move """ san = unicode(toSAN (board, move)) if board.color == WHITE: return san.translate(san2WhiteFanDic) else: return san.translate(san2BlackFanDic) ################################################################################ # parseFAN # ################################################################################ fan2SanDic = {} for k, v in san2WhiteFanDic.iteritems(): fan2SanDic[ord(v)] = unichr(k) for k, v in san2BlackFanDic.iteritems(): fan2SanDic[ord(v)] = unichr(k) def parseFAN (board, fan): """ Parse a Figurine Algebraic Notation string """ san = fan.translate(fan2SanDic) return parseSAN (board, san)
Python
try: from gmpy import mpz uselp = False except ImportError: uselp = True from array import array #=============================================================================== # createBoard returns a new bitboard in the format preferred by this module #=============================================================================== def createBoard (number): return mpz(number) if uselp: def createBoard (number): return number #=============================================================================== # clearBit returns a bitboard with the ith bit set #=============================================================================== def setBit (bitboard, i): return bitboard.setbit(63-i) if True or uselp: def setBit (bitboard, i): return bitboard | bitPosArray[i] bitPosArray = [2**(63-i) for i in xrange(64)] #=============================================================================== # clearBit returns the bitboard with the ith bit unset #=============================================================================== def clearBit (bitboard, i): return bitboard & notBitPosArray[i] notBitPosArray = [~2**(63-i) for i in xrange(64)] #=============================================================================== # firstBit returns the bit closest to 0 (A4) that is set in the board #=============================================================================== def firstBit (bitboard): return 64-bitboard.numdigits(2) if uselp: def firstBit (bitboard): """ Returns the index of the first non-zero bit from left """ if (bitboard >> 48): return lzArray[bitboard >> 48] if (bitboard >> 32): return lzArray[bitboard >> 32] + 16 if (bitboard >> 16): return lzArray[bitboard >> 16] + 32 return lzArray[bitboard] + 48 # The bitCount array returns the leading non-zero bit in the 16 bit # input argument. lzArray = array('B',[0]*65536) s = n = 1 for i in range(16): for j in range (s, s + n): lzArray[j] = 16 - 1 - i s += n n += n #=============================================================================== # lastBit returns the bit closest to 63 (H8) that is set in the board #=============================================================================== def lastBit (bitboard): return 63-bitboard.scan1(0) if uselp: def lastBit (bitboard): return lsb [bitboard & -bitboard] lsb = {} for i in xrange(64): lsb[2**i] = 63-i #=============================================================================== # bitLength returns the number of set bits in a bitboard. This can be used to # count the number of pieces, or calculate mobility #=============================================================================== def bitLength (bitboard): return bitboard.popcount() if uselp: def bitLength (bitboard): return bitCount [ bitboard >> 48 ] + \ bitCount [ ( bitboard >> 32) & 0xffff] + \ bitCount [ ( bitboard >> 16) & 0xffff] + \ bitCount [ bitboard & 0xffff ] # The bitCount array returns the no. of bits present in the 16 bit # input argument. bitCount = array('H',[0]*65536) bitCount[0] = 0 bitCount[1] = 1 i = 1 for n in range(2,17): i <<= 1 for j in range (i, i*2): bitCount[j] = 1 + bitCount[j-i] #=============================================================================== # iterBits yields, or returns a list of, the positions of all set bits in a # bitboard. There is no guarantee of the order. #=============================================================================== def iterBits (bitboard): scan = bitboard.scan1 last = -1 for i in xrange(bitboard.popcount()): last = scan(last+1) yield 63-last if uselp: def iterBits (bitboard): while bitboard: bit = bitboard & -bitboard yield lsb[bit] bitboard -= bit #=============================================================================== # toString returns a representation of the bitboard for debugging #=============================================================================== def toString (bitboard): chars = bitboard.digits(2).zfill(64) chars = chars.replace("0", "- ").replace("1", "# ") return "\n".join(chars[i:i+16] for i in xrange(0,128,16)) if uselp: def toString (bitboard): s = [] last = -1 while bitboard: cord = firstBit (bitboard) bitboard = clearBit (bitboard, cord) for c in range(cord-last-1): s.append(" -") s.append(" #") last = cord while len(s) < 64: s.append(" -") s2 = "" for i in range(64,0,-8): a = s[i-8:i] s2 += "".join(a) + "\n" return s2
Python
### DEPRECATED ### SHOULD ONLY BE USED AS A REFERENCE TO MAKE leval pieceValues = [0, 900, 500, 350, 300, 100] from array import array from pychess.Utils.const import * # these tables will be used for positional bonuses: # whiteknight = array('b', [ -20, -35,-10, -10, -10,-10, -35, -20, -10, 0, 0, 3, 3, 0, 0, -10, -10, 0, 15, 15, 15, 15, 0, -10, -10, 0, 20, 20, 20, 20, 0, -10, -10, 10, 25, 20, 25, 25, 10, -10, -10, 15, 25, 35, 35, 35, 15, -10, -10, 15, 25, 25, 25, 25, 15, -10, -20, -10,-10, -10, -10,-10, -10, -20 ]) blackknight = array('b', [ -20,-10,-10,-10,-10, -10,-10,-20, -10, 15, 25, 25, 25, 25, 15,-10, -10, 15, 25, 35, 35 , 35, 15,-10, -10, 10, 25, 20, 25, 25, 10,-10, -10, 0, 20, 20, 20, 20, 0,-10, -10, 0, 15, 15, 15, 15, 0,-10, -10, 0, 0, 3, 3, 0, 0,-10, -20,-35,-10,-10,-10, -10,-35,-20 ]) whitepawn = array('b', [ 0, 0, 0, 0, 0, 0, 0, 0, 25, 25, 35, 5, 5, 50, 45, 30, 0, 0, 0, 7, 7, 5, 5, 0, 0, 0, 0, 14, 14, 0, 0, 0, 0, 0, 10, 20, 20, 10, 5, 5, 12, 18, 18, 27, 27, 18, 18, 18, 25, 30, 30, 35, 35, 35, 30, 25, 0, 0, 0, 0, 0, 0, 0, 0 ]) blackpawn = array('b', [ 0, 0, 0, 0, 0, 0, 0, 0, 30, 30, 30, 35, 35, 35, 30, 25, 12, 18, 18, 27, 27, 18, 18, 18, 0, 0, 10, 20, 20, 10, 5, 5, 0, 0, 0, 14, 14, 0, 0, 0, 0, 0, 0, 7, 7, 5, 5, 0, 25, 25, 35, 5, 5, 50, 45, 30, 0, 0, 0, 0, 0, 0, 0, 0]) whiteking = array('h', [ -100, 15, 15, -20, 10, 4, 15, -100, -250, -200, -150, -100, -100, -150, -200, -250, -350, -300, -300, -250, -250, -300, -300, -350, -400, -400, -400, -350, -350, -400, -400, -400, -450, -450, -450, -450, -450, -450, -450, -450, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500 ]) blackking = array('h', [ -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -450, -450, -450, -450, -450, -450, -450, -450, -400, -400, -400, -350, -350, -400, -400, -400, -350, -300, -300, -250, -250, -300, -300, -350, -250, -200, -150, -100, -100, -150, -200, -250, -100, 7, 15, -20, 10, 4, 15, -100 ]) whitequeen = array('b', [ 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 7, 10, 5, 0, 0, -15, -15, -15, -10, -10, -15, -15, -15, -40, -40, -40, -40, -40, -40, -40, -40, -60, -40, -40, -60, -60, -40, -40, -60, -30, -30, -30, -30, -30, -30, -30, -30, 0, 0, 3, 3, 3, 3, 3, 0, 5, 5, 5, 10, 10, 7, 5, 5 ]) blackqueen = array('b', [ 5, 5, 5, 10, 10, 7, 5, 5, 0, 0, 3, 3, 3, 3, 3, 0, -30, -30, -30, -30, -30, -30, -30, -30, -60, -40, -40, -60, -60, -40, -40, -60, -40, -40, -40, -40, -40, -40, -40, -40, -15, -15, -15, -10, -10, -15, -15, -15, 0, 0, 0, 7, 10, 5, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0 ]) whiterook = array('b', [ 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 7, 10, 0, 0, 0, -15, -15, -15, -10, -10, -15, -15, -15, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -30, -30, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, 0, 10, 15, 20, 20, 15, 10, 0, 10, 15, 20, 25, 25, 20, 15, 10 ]) blackrook = array('b', [ 10 , 15, 20, 25, 25, 20, 15, 10, 0 , 10, 15, 20, 20, 15, 10, 0, -20 ,-20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -30, -30, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -15, -15, -15, -10, -10, -15, -15, -15, 0, 0, 0, 7, 10, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2 ]) whitebishop = array('b', [ -5, -5, -10, -5, -5, -10, -5, -5, -5, 10, 5, 10, 10, 5, 10, -5, -5, 5, 6, 15, 15, 6, 5, -5, -5, 3, 15, 10, 10, 15, 3, -5, -5, 3, 15, 10, 10, 15, 3, -5, -5, 5, 6, 15, 15, 6, 5, -5, -5, 10, 5, 10, 10, 5, 10, -5, -5, -5, -10, -5, -5, -10, -5, -5 ]) blackbishop = array('b', [ -5, -5, -10, -5, -5, -10, -5, -5, -5, 10, 5, 10, 10, 5, 10, -5, -5, 5, 6, 15, 15, 6, 5, -5, -5, 3, 15, 10, 10, 15, 3, -5, -5, 3, 15, 10, 10, 15, 3, -5, -5, 5, 6, 15, 15, 6, 5, -5, -5, 10, 5, 10, 10, 5, 10, -5, -5, -5, -10, -5, -5, -10, -5, -5 ]) pos = { KNIGHT: { BLACK: array('b', [ -20,-10,-10,-10,-10, -10,-10,-20, -10, 15, 25, 25, 25, 25, 15,-10, -10, 15, 25, 35, 35 , 35, 15,-10, -10, 10, 25, 20, 25, 25, 10,-10, -10, 0, 20, 20, 20, 20, 0,-10, -10, 0, 15, 15, 15, 15, 0,-10, -10, 0, 0, 3, 3, 0, 0,-10, -20,-35,-10,-10,-10, -10,-35,-20 ]), WHITE: array('b', [ -20, -35,-10, -10, -10,-10, -35, -20, -10, 0, 0, 3, 3, 0, 0, -10, -10, 0, 15, 15, 15, 15, 0, -10, -10, 0, 20, 20, 20, 20, 0, -10, -10, 10, 25, 20, 25, 25, 10, -10, -10, 15, 25, 35, 35, 35, 15, -10, -10, 15, 25, 25, 25, 25, 15, -10, -20, -10,-10, -10, -10,-10, -10, -20 ]) }, PAWN: { WHITE: array('b', [ 0, 0, 0, 0, 0, 0, 0, 0, 25, 25, 35, 5, 5, 50, 45, 30, 0, 0, 0, 7, 7, 5, 5, 0, 0, 0, 0, 14, 14, 0, 0, 0, 0, 0, 10, 20, 20, 10, 5, 5, 12, 18, 18, 27, 27, 18, 18, 18, 25, 30, 30, 35, 35, 35, 30, 25, 0, 0, 0, 0, 0, 0, 0, 0 ]), BLACK: array('b', [ 0, 0, 0, 0, 0, 0, 0, 0, 30, 30, 30, 35, 35, 35, 30, 25, 12, 18, 18, 27, 27, 18, 18, 18, 0, 0, 10, 20, 20, 10, 5, 5, 0, 0, 0, 14, 14, 0, 0, 0, 0, 0, 0, 7, 7, 5, 5, 0, 25, 25, 35, 5, 5, 50, 45, 30, 0, 0, 0, 0, 0, 0, 0, 0]) }, KING: { WHITE: array('h', [ -100, 15, 15, -20, 10, 4, 15, -100, -250, -200, -150, -100, -100, -150, -200, -250, -350, -300, -300, -250, -250, -300, -300, -350, -400, -400, -400, -350, -350, -400, -400, -400, -450, -450, -450, -450, -450, -450, -450, -450, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500 ]), BLACK: array('h', [ -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -500, -450, -450, -450, -450, -450, -450, -450, -450, -400, -400, -400, -350, -350, -400, -400, -400, -350, -300, -300, -250, -250, -300, -300, -350, -250, -200, -150, -100, -100, -150, -200, -250, -100, 7, 15, -20, 10, 4, 15, -100 ]) }, QUEEN: { BLACK: array('b', [ 5, 5, 5, 10, 10, 7, 5, 5, 0, 0, 3, 3, 3, 3, 3, 0, -30, -30, -30, -30, -30, -30, -30, -30, -60, -40, -40, -60, -60, -40, -40, -60, -40, -40, -40, -40, -40, -40, -40, -40, -15, -15, -15, -10, -10, -15, -15, -15, 0, 0, 0, 7, 10, 5, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0 ]), WHITE: array('b', [ 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 7, 10, 5, 0, 0, -15, -15, -15, -10, -10, -15, -15, -15, -40, -40, -40, -40, -40, -40, -40, -40, -60, -40, -40, -60, -60, -40, -40, -60, -30, -30, -30, -30, -30, -30, -30, -30, 0, 0, 3, 3, 3, 3, 3, 0, 5, 5, 5, 10, 10, 7, 5, 5 ]) }, ROOK: { WHITE: array('b', [ 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 7, 10, 0, 0, 0, -15, -15, -15, -10, -10, -15, -15, -15, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -30, -30, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, 0, 10, 15, 20, 20, 15, 10, 0, 10, 15, 20, 25, 25, 20, 15, 10 ]), BLACK: array('b', [ 10 , 15, 20, 25, 25, 20, 15, 10, 0 , 10, 15, 20, 20, 15, 10, 0, -20 ,-20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -30, -30, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -15, -15, -15, -10, -10, -15, -15, -15, 0, 0, 0, 7, 10, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2 ]) }, BISHOP: { WHITE: array('b', [ -5, -5, -10, -5, -5, -10, -5, -5, -5, 10, 5, 10, 10, 5, 10, -5, -5, 5, 6, 15, 15, 6, 5, -5, -5, 3, 15, 10, 10, 15, 3, -5, -5, 3, 15, 10, 10, 15, 3, -5, -5, 5, 6, 15, 15, 6, 5, -5, -5, 10, 5, 10, 10, 5, 10, -5, -5, -5, -10, -5, -5, -10, -5, -5 ]), BLACK: array('b', [ -5, -5, -10, -5, -5, -10, -5, -5, -5, 10, 5, 10, 10, 5, 10, -5, -5, 5, 6, 15, 15, 6, 5, -5, -5, 3, 15, 10, 10, 15, 3, -5, -5, 3, 15, 10, 10, 15, 3, -5, -5, 5, 6, 15, 15, 6, 5, -5, -5, 10, 5, 10, 10, 5, 10, -5, -5, -5, -10, -5, -5, -10, -5, -5 ]) } } endking = array('b', [ -5, -3, -1, 0, 0, -1, -3, -5, -3, 10, 10, 10, 10, 10, 10, -3, -1, 10, 25, 25, 25, 25, 10, -1, 0, 10, 25, 30, 30, 25, 10, 0, 0, 10, 25, 30, 30, 25, 10, 0, -1, 10, 25, 25, 25, 25, 10, -1, -3, 10, 10, 10, 10, 10, 10, -3, -5, -3, -1, 0, 0, -1, -3, -5 ]) # Init KingTropism table # Sjeng uses max instead of min.. tropismTable = [] for px in range(8): for py in range(8): for kx in range(8): for ky in range(8): knight = abs(ky-py) + abs(kx-px) rook = min(abs(ky-py), abs(kx-px)) *2 +5 queen = min(abs(ky-py), abs(kx-px)) +5 tropismTable.append(knight + rook*20 + queen*20*20) tropismArray = array('I',tropismTable) def lookUpTropism (px, py, kx, ky, piece): value = tropismArray[ky + kx*8 + py*8*8 + px*8*8*8] knight = value % 20 rook = (value-knight)/20 % 20 queen = (value-knight-rook*20)/20/20 if piece == knight: return knight-5 if piece == rook: return rook-5 return queen-5 def evaluateComplete (board, color=WHITE): """ A detailed evaluation function, taking into account several positional factors """ if board.status == RUNNING: analyzePawnStructure (board) s = evalMaterial (board) + \ evalPawnStructure (board) + \ evalBadBishops (board) + \ evalDevelopment (board) + \ evalCastling (board) + \ evalRookBonus (board) + \ evalKingTropism (board) elif board.status == DRAW: s = 0 elif board.status == WHITEWON: s = 9999 else: s = -9999 return (color == WHITE and [s] or [-s])[0] def evalMaterial (board): materialValue = [0, 0] numPawns = [0, 0] for row in board.data: for piece in row: if not piece: continue materialValue[piece.color] += pieceValues[piece.sign] if piece.sign == PAWN: numPawns[piece.color] += 1 # If both sides are equal, no need to compute anything! if materialValue[BLACK] == materialValue[WHITE]: return 0 matTotal = materialValue[BLACK] + materialValue[WHITE] # Who is leading the game, material-wise? if materialValue[BLACK] > materialValue[WHITE]: # Black leading matDiff = materialValue[BLACK] - materialValue[WHITE] val = min( 2400, matDiff ) + \ ( matDiff * ( 12000 - matTotal ) * numPawns[BLACK] ) \ / ( 6400 * ( numPawns[BLACK] + 1 ) ) return -val else: # White leading matDiff = materialValue[WHITE] - materialValue[BLACK] val = min( 2400, matDiff ) + \ ( matDiff * ( 12000 - matTotal ) * numPawns[WHITE] ) \ / ( 6400 * ( numPawns[WHITE] + 1 ) ) return val def evalKingTropism (board): """ All other things being equal, having your Knights, Queens and Rooks close to the opponent's king is a good thing """ score = 0 try: wking, bking = board.kings wky, wkx = wking.cords bky, bkx = bking.cords except: return 0 for py, row in enumerate(board.data): for px, piece in enumerate(row): if piece and piece.color == WHITE: if piece.sign == KNIGHT: score += lookUpTropism(px,py,bkx,bky,KNIGHT) elif piece.sign == ROOK: score += lookUpTropism(px,py,bkx,bky,ROOK) elif piece.sign == QUEEN: score += lookUpTropism(px,py,bkx,bky,QUEEN) elif piece and piece.color == BLACK: if piece.sign == KNIGHT: score -= lookUpTropism(px,py,wkx,wky,KNIGHT) elif piece.sign == ROOK: score -= lookUpTropism(px,py,wkx,wky,ROOK) elif piece.sign == QUEEN: score -= lookUpTropism(px,py,wkx,wky,QUEEN) return score def evalRookBonus (board): """ Rooks are more effective on the seventh rank and on open files """ score = 0 for y, row in enumerate(board.data): for x, piece in enumerate(row): if not piece or not piece.sign == ROOK: continue if pieceCount <= 6: # We should try to keep the rooks at the back lines if y in (0,7): score += piece.color == WHITE and 12 or -12 # Is this rook on a semi- or completely open file? noblack = blackPawnFileBins[x] == 0 and 1 or 0 nowhite = whitePawnFileBins[x] == 0 and 1 or 0 if piece.color == WHITE: if noblack: score += (noblack+nowhite)*6 else: score += nowhite*8 else: if nowhite: score -= (noblack+nowhite)*6 else: score -= nowhite*8 return score def evalDevelopment (board): """ Mostly useful in the opening, this term encourages the machine to move its bishops and knights into play, to control the center with its queen's and king's pawns """ score = 0 # Test endgame if pieceCount <= 8: wking, bking = board.kings score += endking[wking.y*8+wking.x] score -= endking[bking.y*8+bking.x] return score for y, row in enumerate(board.data): for x, piece in enumerate(row): if not piece: continue #s = pos[piece.sign][piece.color][y*8+x] if piece.color == WHITE: if piece.sign == PAWN: score += whitepawn[x+y*8] elif piece.sign == KNIGHT: score += whiteknight[x+y*8] elif piece.sign == BISHOP: score += whitebishop[x+y*8] elif piece.sign == ROOK: score += whiterook[x+y*8] elif piece.sign == QUEEN: score += whitequeen[x+y*8] elif piece.sign == KING: score += whiteking[x+y*8] else: if piece.sign == PAWN: score -= blackpawn[x+y*8] elif piece.sign == KNIGHT: score -= blackknight[x+y*8] elif piece.sign == BISHOP: score -= blackbishop[x+y*8] elif piece.sign == ROOK: score -= blackrook[x+y*8] elif piece.sign == QUEEN: score -= blackqueen[x+y*8] elif piece.sign == KING: score -= blackking[x+y*8] return score def evalCastling (board): """ Used to encourage castling """ if pieceCount <= 6: return 0 score = 0 for color, mod in ((WHITE,1),(BLACK,-1)): mainrow = board.data[int(3.5-3.5*mod)] # It is good to have a pawn in the king column for x, p in enumerate(mainrow): if p and p.sign == KING and p.color == color: bin = color == WHITE and whitePawnFileBins or blackPawnFileBins if not bin[x]: score -= 10*mod break kside = color == BLACK and B_OO or W_OO qside = color == BLACK and B_OOO or W_OOO # Being castled deserves a bonus if board.hasCastled[color]: score += 15*mod continue # Biggest penalty if you can't castle at all if not board.castling & (qside|kside): score -= 60*mod # Penalty if you can only castle kingside elif not board.castling & qside: score -= 30*mod # Bigger penalty if you can only castle queenside elif not board.castling & kside: score -= 45*mod return score def evalBadBishops (board): """ Bishops may be limited in their movement if there are too many pawns on squares of their color """ score = 0 for y, row in enumerate(board.data): for x, piece in enumerate(row): if not piece or not piece.sign == BISHOP: continue mod = piece.color == WHITE and 1 or -1 # What is the bishop's square color? lightsq = x % 2 + y % 2 == 1 if lightsq: score -= pawnColorBins[0]*7 * mod else: score -= pawnColorBins[1]*7 * mod return score def evalPawnStructure (board) : """ Given the pawn formations, penalize or bonify the position according to the features it contains """ score = 0 for x in range (8): # First, look for doubled pawns # In chess, two or more pawns on the same file usually hinder each other, # so we assign a penalty if whitePawnFileBins[x] > 1: score -= 10 if blackPawnFileBins[x] > 1: score += 10 # Now, look for an isolated pawn, i.e., one which has no neighbor pawns # capable of protecting it from attack at some point in the future if x == 0 and whitePawnFileBins[x] > 0 and whitePawnFileBins[1] == 0: score -= 15 elif x == 7 and whitePawnFileBins[x] > 0 and whitePawnFileBins[6] == 0: score -= 15 elif whitePawnFileBins[x] > 0 and whitePawnFileBins[x-1] == 0 and \ whitePawnFileBins[x+1] == 0: score -= 15 if x == 0 and blackPawnFileBins[x] > 0 and blackPawnFileBins[1] == 0: score += 15 elif x == 7 and blackPawnFileBins[x] > 0 and blackPawnFileBins[6] == 0: score += 15 elif blackPawnFileBins[x] > 0 and blackPawnFileBins[x-1] == 0 and \ blackPawnFileBins[x+1] == 0: score += 15 # Penalize pawn rams, because they restrict movement score -= 8 * pawnRams return score whitePawnFileBins = [0]*8 pawnColorBins = [0]*2 pawnRams = 0 blackPawnFileBins = [0]*8 def analyzePawnStructure (board): """ Look at pawn positions to be able to detect features such as doubled, isolated or passed pawns """ global whitePawnFileBins, blackPawnFileBins, pawnColorBins, pawnRams whitePawnFileBins = [0]*8 blackPawnFileBins = [0]*8 pawnColorBins[0] = 0 pawnColorBins[1] = 0 # Whiterams-Blackrams pawnRams = 0 global pieceCount pieceCount = 0 data = board.data for y, row in enumerate(data[::-1]): for x, piece in enumerate(row): if not piece: continue if piece.sign == PAWN and y not in (0,7): if piece.color == WHITE: whitePawnFileBins[x] += 1 else: blackPawnFileBins[x] += 1 # Is this pawn on a white or a black square? if y % 2 == x % 2: pawnColorBins[ 0 ] += 1 else: pawnColorBins[ 1 ] += 1 # Look for a "pawn ram", i.e., a situation where a black pawn # is located in the square immediately ahead of this one. if piece.color == WHITE: ahead = data[y+1][x] else: ahead = data[y-1][x] if ahead and ahead.sign == PAWN and ahead.color == piece.color: if piece.color == WHITE: pawnRams += 1 else: pawnRams -= 1 elif piece: pieceCount += 1
Python
from copy import copy from lutils.LBoard import LBoard from lutils.bitboard import iterBits from lutils.lmove import RANK, FILE, FLAG, PROMOTE_PIECE, toAN from Piece import Piece from Cord import Cord from const import * class Board: """ Board is a thin layer above LBoard, adding the Piece objects, which are needed for animation in BoardView. In contrast to LBoard, Board is immutable, which means it will clone itself each time you apply a move to it. Caveat: As the only objects, the Piece objects in the self.data lists will not be cloned, to make animation state preserve between moves """ variant = NORMALCHESS def __init__ (self, setup=False): self.data = [[None]*8 for i in xrange(8)] self.board = LBoard(self.variant) self.movecount = "" self.nags = [] # children can contain comments and variations self.children = [] self.next = None self.prev = None if setup: if setup == True: self.board.applyFen(FEN_START) else: self.board.applyFen(setup) arBoard = self.board.arBoard wpieces = self.board.boards[WHITE] bpieces = self.board.boards[BLACK] for cord in iterBits(wpieces[PAWN]): self.data[RANK(cord)][FILE(cord)] = Piece(WHITE, PAWN) for cord in iterBits(wpieces[KNIGHT]): self.data[RANK(cord)][FILE(cord)] = Piece(WHITE, KNIGHT) for cord in iterBits(wpieces[BISHOP]): self.data[RANK(cord)][FILE(cord)] = Piece(WHITE, BISHOP) for cord in iterBits(wpieces[ROOK]): self.data[RANK(cord)][FILE(cord)] = Piece(WHITE, ROOK) for cord in iterBits(wpieces[QUEEN]): self.data[RANK(cord)][FILE(cord)] = Piece(WHITE, QUEEN) if self.board.kings[WHITE] != -1: self[Cord(self.board.kings[WHITE])] = Piece(WHITE, KING) for cord in iterBits(bpieces[PAWN]): self.data[RANK(cord)][FILE(cord)] = Piece(BLACK, PAWN) for cord in iterBits(bpieces[KNIGHT]): self.data[RANK(cord)][FILE(cord)] = Piece(BLACK, KNIGHT) for cord in iterBits(bpieces[BISHOP]): self.data[RANK(cord)][FILE(cord)] = Piece(BLACK, BISHOP) for cord in iterBits(bpieces[ROOK]): self.data[RANK(cord)][FILE(cord)] = Piece(BLACK, ROOK) for cord in iterBits(bpieces[QUEEN]): self.data[RANK(cord)][FILE(cord)] = Piece(BLACK, QUEEN) if self.board.kings[BLACK] != -1: self[Cord(self.board.kings[BLACK])] = Piece(BLACK, KING) def addPiece (self, cord, piece): self[cord] = piece self.board._addPiece(cord.cord, piece.piece, piece.color) self.board.updateBoard() def simulateMove (self, board1, move): moved = [] new = [] dead = [] cord0, cord1 = move.cords moved.append( (self[cord0], cord0) ) if self[cord1]: dead.append( self[cord1] ) if move.flag == QUEEN_CASTLE: if self.color == WHITE: moved.append( (self[Cord(A1)], Cord(A1)) ) else: moved.append( (self[Cord(A8)], Cord(A8)) ) elif move.flag == KING_CASTLE: if self.color == WHITE: moved.append( (self[Cord(H1)], Cord(H1)) ) else: moved.append( (self[Cord(H8)], Cord(H8)) ) elif move.flag in PROMOTIONS: newPiece = board1[cord1] moved.append( (newPiece, cord0) ) new.append( newPiece ) newPiece.opacity=1 dead.append( self[cord0] ) elif move.flag == ENPASSANT: if self.color == WHITE: dead.append( self[Cord(cord1.x, cord1.y-1)] ) else: dead.append( self[Cord(cord1.x, cord1.y+1)] ) return moved, new, dead def simulateUnmove (self, board1, move): moved = [] new = [] dead = [] cord0, cord1 = move.cords moved.append( (self[cord1], cord1) ) if board1[cord1]: dead.append( board1[cord1] ) if move.flag == QUEEN_CASTLE: if board1.color == WHITE: moved.append( (self[Cord(D1)], Cord(D1)) ) else: moved.append( (self[Cord(D8)], Cord(D8)) ) elif move.flag == KING_CASTLE: if board1.color == WHITE: moved.append( (self[Cord(F1)], Cord(F1)) ) else: moved.append( (self[Cord(F8)], Cord(F8)) ) elif move.flag in PROMOTIONS: newPiece = board1[cord0] moved.append( (newPiece, cord1) ) new.append( newPiece ) newPiece.opacity=1 dead.append( self[cord1] ) elif move.flag == ENPASSANT: if board1.color == WHITE: new.append( board1[Cord(cord1.x, cord1.y-1)] ) else: new.append( board1[Cord(cord1.x, cord1.y+1)] ) return moved, new, dead def move (self, move): assert self[move.cord0], "%s %s" % (move, self.asFen()) newBoard = self.clone() newBoard.board.applyMove (move.move) cord0, cord1 = move.cords flag = FLAG(move.move) newBoard[cord1] = newBoard[cord0] newBoard[cord0] = None if self.color == WHITE: if flag == QUEEN_CASTLE: newBoard[Cord(D1)] = newBoard[Cord(A1)] newBoard[Cord(A1)] = None elif flag == KING_CASTLE: newBoard[Cord(F1)] = newBoard[Cord(H1)] newBoard[Cord(H1)] = None else: if flag == QUEEN_CASTLE: newBoard[Cord(D8)] = newBoard[Cord(A8)] newBoard[Cord(A8)] = None elif flag == KING_CASTLE: newBoard[Cord(F8)] = newBoard[Cord(H8)] newBoard[Cord(H8)] = None if flag in PROMOTIONS: newBoard[cord1] = Piece(self.color, PROMOTE_PIECE(flag)) elif flag == ENPASSANT: newBoard[Cord(cord1.x, cord0.y)] = None return newBoard def willLeaveInCheck (self, move): board_clone = self.board.clone() board_clone.applyMove(move.move) return board_clone.opIsChecked() def switchColor (self): """ Switches the current color to move and unsets the enpassant cord. Mostly to be used by inversed analyzers """ return self.setColor(1-self.color) def _get_enpassant (self): if self.board.enpassant != None: return Cord(self.board.enpassant) return None enpassant = property(_get_enpassant) def setColor (self, color): newBoard = self.clone() newBoard.board.setColor(color) newBoard.board.setEnpassant(None) return newBoard def _get_color (self): return self.board.color color = property(_get_color) def _get_ply (self): return len(self.board.history) ply = property(_get_ply) def asFen (self): return self.board.asFen() def asXFen (self): return self.board.asFen(useXFen=True) def __repr__ (self): return str(self.board) def __getitem__ (self, cord): return self.data[cord.y][cord.x] def __setitem__ (self, cord, piece): self.data[cord.y][cord.x] = piece def clone (self): lboard = self.board.clone() if self.variant != NORMALCHESS: from pychess.Variants import variants newBoard = variants[self.variant].board() else: newBoard = Board() newBoard.board = lboard for y, row in enumerate(self.data): for x, piece in enumerate(row): newBoard.data[y][x] = piece return newBoard def __eq__ (self, other): if type(self) != type(other): return False return self.board == other.board
Python
# -*- coding: UTF-8 -*- ################################################################################ # PyChess information # ################################################################################ NAME = "PyChess" ENGINES_XML_API_VERSION = "0.10.1" ################################################################################ # Player info # ################################################################################ # Player types LOCAL, ARTIFICIAL, REMOTE = range(3) # Engine strengths EASY, INTERMEDIATE, EXPERT = range(3) # Player colors WHITE, BLACK = range(2) ################################################################################ # Game values # ################################################################################ # Game states WAITING_TO_START, PAUSED, RUNNING, DRAW, WHITEWON, BLACKWON, KILLED, \ ADJOURNED, ABORTED, UNKNOWN_STATE = range(10) reprResult = ["*", "*", "*", "1/2-1/2", "1-0", "0-1", "?", "*", "?", "?"] UNDOABLE_STATES = (DRAW, WHITEWON, BLACKWON) UNFINISHED_STATES = (WAITING_TO_START, PAUSED, RUNNING, UNKNOWN_STATE) # Chess variants NORMALCHESS, CORNERCHESS, SHUFFLECHESS, FISCHERRANDOMCHESS, RANDOMCHESS, \ ASYMMETRICRANDOMCHESS, UPSIDEDOWNCHESS, PAWNSPUSHEDCHESS, PAWNSPASSEDCHESS, \ LOSERSCHESS, PAWNODDSCHESS, KNIGHTODDSCHESS, ROOKODDSCHESS, \ QUEENODDSCHESS = range(14) # Chess variant groups VARIANTS_BLINDFOLD, VARIANTS_ODDS, VARIANTS_SHUFFLE, VARIANTS_OTHER = range(4) # Action errors ACTION_ERROR_NOT_OUT_OF_TIME, \ ACTION_ERROR_CLOCK_NOT_STARTED, ACTION_ERROR_SWITCH_UNDERWAY, \ ACTION_ERROR_CLOCK_NOT_PAUSED, ACTION_ERROR_TOO_LARGE_UNDO, \ ACTION_ERROR_NONE_TO_ACCEPT, ACTION_ERROR_NONE_TO_WITHDRAW, \ ACTION_ERROR_NONE_TO_DECLINE, = range(8) # Game state reasons ABORTED_ADJUDICATION, ABORTED_AGREEMENT, ABORTED_COURTESY, ABORTED_EARLY, \ ABORTED_SERVER_SHUTDOWN, ADJOURNED_COURTESY, \ ADJOURNED_AGREEMENT, ADJOURNED_LOST_CONNECTION, ADJOURNED_SERVER_SHUTDOWN, \ ADJOURNED_COURTESY_WHITE, ADJOURNED_COURTESY_BLACK, \ ADJOURNED_LOST_CONNECTION_WHITE, ADJOURNED_LOST_CONNECTION_BLACK, \ DRAW_50MOVES, DRAW_ADJUDICATION, DRAW_AGREE, DRAW_CALLFLAG, DRAW_INSUFFICIENT, \ DRAW_LENGTH, DRAW_REPITITION, DRAW_STALEMATE, \ DRAW_BLACKINSUFFICIENTANDWHITETIME, DRAW_WHITEINSUFFICIENTANDBLACKTIME, \ WON_ADJUDICATION, WON_CALLFLAG, WON_DISCONNECTION, WON_MATE, WON_RESIGN, \ WON_NOMATERIAL, \ WHITE_ENGINE_DIED, BLACK_ENGINE_DIED, DISCONNECTED, UNKNOWN_REASON = range(33) UNDOABLE_REASONS = (DRAW_50MOVES, DRAW_INSUFFICIENT, DRAW_LENGTH, DRAW_REPITITION, DRAW_STALEMATE, DRAW_AGREE, DRAW_CALLFLAG, \ DRAW_BLACKINSUFFICIENTANDWHITETIME, \ DRAW_WHITEINSUFFICIENTANDBLACKTIME, \ WON_MATE, WON_NOMATERIAL, WON_CALLFLAG, WON_RESIGN) UNRESUMEABLE_REASONS = (DRAW_50MOVES, DRAW_INSUFFICIENT, DRAW_LENGTH, \ DRAW_REPITITION, DRAW_STALEMATE, WON_MATE, WON_NOMATERIAL) # Player actions RESIGNATION = "resignation" FLAG_CALL = "flag call" DRAW_OFFER = "draw offer" ABORT_OFFER = "abort offer" ADJOURN_OFFER = "adjourn offer" PAUSE_OFFER = "pause offer" RESUME_OFFER = "resume offer" SWITCH_OFFER = "switch offer" TAKEBACK_OFFER = "takeback offer" MATCH_OFFER = "match offer" HURRY_ACTION = "hurry action" CHAT_ACTION = "chat action" ACTIONS = (RESIGNATION, FLAG_CALL, DRAW_OFFER, ABORT_OFFER, ADJOURN_OFFER, \ PAUSE_OFFER, RESUME_OFFER, SWITCH_OFFER, TAKEBACK_OFFER, \ MATCH_OFFER, HURRY_ACTION, CHAT_ACTION) OFFERS = (DRAW_OFFER, ABORT_OFFER, ADJOURN_OFFER, PAUSE_OFFER, \ RESUME_OFFER, SWITCH_OFFER, TAKEBACK_OFFER, MATCH_OFFER) INGAME_ACTIONS = (RESIGNATION, FLAG_CALL, DRAW_OFFER, ABORT_OFFER, \ ADJOURN_OFFER, PAUSE_OFFER, SWITCH_OFFER, HURRY_ACTION) # A few nice to have boards FEN_EMPTY = "4k3/8/8/8/8/8/8/4K3 w - - 0 1" FEN_START = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" ################################################################################ # Search values # ################################################################################ hashfALPHA, hashfBETA, hashfEXACT, hashfBAD = range(4) # Engine modes NORMAL, ANALYZING, INVERSE_ANALYZING = range(3) ################################################################################ # Piece types # ################################################################################ # BPAWN is a pawn that moves in the opposite direction EMPTY, PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING, BPAWN = range(8) # Is sliding piece sliders = [ False, False, False, True, True, True, False, False ] # Piece signs reprSign = ["", "P", "N", "B", "R", "Q", "K"] chr2Sign = {"k":KING, "q": QUEEN, "r": ROOK, "b": BISHOP, "n": KNIGHT, "p":PAWN} ################################################################################ # Move values # ################################################################################ NORMAL_MOVE, QUEEN_CASTLE, KING_CASTLE, ENPASSANT, \ KNIGHT_PROMOTION, BISHOP_PROMOTION, ROOK_PROMOTION, QUEEN_PROMOTION = range(8) PROMOTIONS = (QUEEN_PROMOTION, ROOK_PROMOTION, BISHOP_PROMOTION, KNIGHT_PROMOTION) # Algebraic notation types: Short, Long, Figure and Simpe SAN, LAN, FAN, AN = range(4) FAN_PIECES = [ ["", u"♙", u"♘", u"♗", u"♖", u"♕", u"♔", ""], ["", u"♟", u"♞", u"♝", u"♜", u"♛", u"♚", ""] ] ################################################################################ # Castling values # ################################################################################ W_OO, W_OOO, B_OO, B_OOO = [2**i for i in range(4)] W_CASTLED, B_CASTLED = [2**i for i in range(2)] ################################################################################ # Cords types # ################################################################################ A1, B1, C1, D1, E1, F1, G1, H1, \ A2, B2, C2, D2, E2, F2, G2, H2, \ A3, B3, C3, D3, E3, F3, G3, H3, \ A4, B4, C4, D4, E4, F4, G4, H4, \ A5, B5, C5, D5, E5, F5, G5, H5, \ A6, B6, C6, D6, E6, F6, G6, H6, \ A7, B7, C7, D7, E7, F7, G7, H7, \ A8, B8, C8, D8, E8, F8, G8, H8 = range (64) reprCord = [ "a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1", "a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2", "a3", "b3", "c3", "d3", "e3", "f3", "g3", "h3", "a4", "b4", "c4", "d4", "e4", "f4", "g4", "h4", "a5", "b5", "c5", "d5", "e5", "f5", "g5", "h5", "a6", "b6", "c6", "d6", "e6", "f6", "g6", "h6", "a7", "b7", "c7", "d7", "e7", "f7", "g7", "h7", "a8", "b8", "c8", "d8", "e8", "f8", "g8", "h8" ] reprFile = ["a", "b", "c", "d", "e", "f", "g", "h"] reprRank = ["1", "2", "3", "4", "5", "6", "7", "8"] cordDic = {} for cord, name in enumerate(reprCord): cordDic[name] = cord ################################################################################ # Internet Chess # ################################################################################ IC_CONNECTED, IC_DISCONNECTED = range(2) IC_POS_ISOLATED, IC_POS_OBSERVING_EXAMINATION, IC_POS_EXAMINATING, \ IC_POS_OP_TO_MOVE, IC_POS_ME_TO_MOVE, IC_POS_OBSERVING, IC_POS_INITIAL = range(7) # Rating deviations DEVIATION_NONE, DEVIATION_ESTIMATED, DEVIATION_PROVISIONAL = range(3) IC_STATUS_PLAYING, IC_STATUS_ACTIVE, IC_STATUS_BUSY, IC_STATUS_OFFLINE, \ IC_STATUS_AVAILABLE, IC_STATUS_NOT_AVAILABLE, IC_STATUS_EXAMINING, \ IC_STATUS_IDLE, IC_STATUS_IN_TOURNAMENT, IC_STATUS_RUNNING_SIMUL_MATCH, \ IC_STATUS_UNKNOWN = range(11) ################################################################################ # User interface # ################################################################################ # Hint modes HINT, SPY = ["hint", "spy"] # Sound settings SOUND_MUTE, SOUND_BEEP, SOUND_SELECT, SOUND_URI = range(4) # Brush types. Send piece object for Piece brush CLEAR, ENPAS = range(2) # Main menu items GAME_MENU_ITEMS = ("save_game1", "save_game_as1", "properties1", "close1") ACTION_MENU_ITEMS = ("abort", "adjourn", "draw", "pause1", "resume1", "undo1", "call_flag", "resign", "ask_to_move") VIEW_MENU_ITEMS = ("rotate_board1", "show_sidepanels", "hint_mode", "spy_mode") MENU_ITEMS = GAME_MENU_ITEMS + ACTION_MENU_ITEMS + VIEW_MENU_ITEMS # Main menu items GAME_MENU_ITEMS = ("save_game1", "save_game_as1", "properties1", "close1") ACTION_MENU_ITEMS = ("abort", "adjourn", "draw", "pause1", "resume1", "undo1", "call_flag", "resign", "ask_to_move") VIEW_MENU_ITEMS = ("rotate_board1", "show_sidepanels", "hint_mode", "spy_mode") MENU_ITEMS = GAME_MENU_ITEMS + ACTION_MENU_ITEMS + VIEW_MENU_ITEMS ################################################################################ # Subprocess # ################################################################################ SUBPROCESS_PTY, SUBPROCESS_SUBPROCESS, SUBPROCESS_FORK = range(3) LOG_DEBUG, LOG_LOG, LOG_WARNING, LOG_ERROR = range(4)
Python
from pychess.Utils.const import KING, QUEEN, ROOK, BISHOP, KNIGHT, PAWN from pychess.Utils.repr import reprSign, reprColor, reprPiece class Piece: def __init__ (self, color, piece): self.color = color self.piece = piece self.opacity = 1.0 self.x = None self.y = None # Sign is a deprecated synonym for piece def _set_sign (self, sign): self.piece = sign def _get_sign (self): return self.piece sign = property(_get_sign, _set_sign) def __repr__ (self): represen = "<%s %s" % (reprColor[self.color], reprPiece[self.piece]) if self.opacity != 1.0: represen += " Op:%0.1f" % self.opacity if self.x != None or self.y != None: if self.x != None: represen += " X:%0.1f" % self.x else: represen += " X:None" if self.y != None: represen += " Y:%0.1f" % self.y else: represen += " Y:None" represen += ">" return represen
Python
import heapq from time import time from gobject import SIGNAL_RUN_FIRST, TYPE_NONE, GObject from pychess.Utils.const import WHITE, BLACK from pychess.System import repeat from pychess.System.Log import log class TimeModel (GObject): __gsignals__ = { "player_changed": (SIGNAL_RUN_FIRST, TYPE_NONE, ()), "time_changed": (SIGNAL_RUN_FIRST, TYPE_NONE, ()), "zero_reached": (SIGNAL_RUN_FIRST, TYPE_NONE, (int,)), "pause_changed": (SIGNAL_RUN_FIRST, TYPE_NONE, (bool,)) } ############################################################################ # Initing # ############################################################################ def __init__ (self, secs, gain, bsecs=-1, minutes=-1): GObject.__init__(self) if bsecs < 0: bsecs = secs if minutes < 0: minutes = secs / 60 self.minutes = minutes # The number of minutes for the original starting # time control (not necessarily where the game was resumed, # i.e. self.intervals[0][0]) self.intervals = [[secs],[bsecs]] self.gain = gain self.paused = False # The left number of secconds at the time pause was turned on self.pauseInterval = 0 self.counter = None self.started = False self.ended = False self.movingColor = WHITE self.connect('time_changed', self.__zerolistener, 'time_changed') self.connect('player_changed', self.__zerolistener, 'player_changed') self.connect('pause_changed', self.__zerolistener, 'pause_changed') self.heap = [] def __repr__ (self): s = "<TimeModel object at %s (White: %s Black: %s)>" % \ (id(self), str(self.getPlayerTime(WHITE)), str(self.getPlayerTime(BLACK))) return s def __zerolistener(self, *args): # If we are called by a sleeper (rather than a signal) we need to pop # at least one time, as we might otherwise end up with items in the # heap, but no sleepers. if len(args) == 0 and self.heap: self.heap.pop() # Pop others (could this give a problem where too many are popped?) # No I don't think so. If a sleeper is too slow, so a later sleeper # comes before him and pops him, then it is most secure not to rely on # mr late, and start a new one. # We won't be 'one behind' always, because the previous pop doesnt # happen if the heap is empty. while self.heap and self.heap[-1] <= time(): self.heap.pop() if self.getPlayerTime(WHITE) <= 0: #print 'emit for white' self.emit('zero_reached', WHITE) if self.getPlayerTime(BLACK) <= 0: #print 'emit for black' self.emit('zero_reached', BLACK) #print 'heap is now', self.heap t1 = time() + self.getPlayerTime(WHITE) t2 = time() + self.getPlayerTime(BLACK) t = min(t1,t2) if not self.heap or t < self.heap[-1]: s = t-time()+0.01 if s > 0: self.heap.append(t) # Because of recur, we wont get callback more than once. repeat.repeat_sleep(self.__zerolistener, s, recur=True) #print 'repeat on', s ############################################################################ # Interacting # ############################################################################ def setMovingColor (self, movingColor): self.movingColor = movingColor self.emit("player_changed") def tap (self): if self.paused: return if self.started: t = self.intervals[self.movingColor][-1] + self.gain if self.counter != None: t -= time() - self.counter self.intervals[self.movingColor].append(t) else: self.intervals[self.movingColor].append ( self.intervals[self.movingColor][-1] ) if len(self.intervals[0]) + len(self.intervals[1]) >= 4: self.started = True self.movingColor = 1-self.movingColor if self.started: self.counter = time() self.emit("time_changed") self.emit("player_changed") def start (self): if self.started: return self.started = True self.counter = time() self.emit("time_changed") def end (self): self.pause() self.ended = True def pause (self): log.debug("TimeModel.pause: self=%s\n" % self) if self.paused: return self.paused = True if self.counter != None: self.pauseInterval = time()-self.counter self.counter = None self.emit("time_changed") self.emit("pause_changed", True) def resume (self): log.debug("TimeModel.resume: self=%s\n" % self) if not self.paused: return self.paused = False self.counter = time() - self.pauseInterval self.emit("pause_changed", False) ############################################################################ # Undo and redo in TimeModel # ############################################################################ def undoMoves (self, moves): """ Sets time and color to move, to the values they were having in the beginning of the ply before the current. his move. Example: White intervals (is thinking): [120, 130, ...] Black intervals: [120, 115] Is undoed to: White intervals: [120, 130] Black intervals (is thinking): [120, ...] """ if not self.started: self.start() for i in xrange(moves): self.movingColor = 1-self.movingColor del self.intervals[self.movingColor][-1] if len(self.intervals[0]) + len(self.intervals[1]) >= 4: self.counter = time() else: self.started = False self.counter = None self.emit("time_changed") self.emit("player_changed") ############################################################################ # Updating # ############################################################################ def updatePlayer (self, color, secs): if color == self.movingColor and self.started: self.counter = secs + time() - self.intervals[color][-1] else: self.intervals[color][-1] = secs self.emit("time_changed") def syncClock (self, wsecs, bsecs): """ Syncronize clock to e.g. fics time """ if self.movingColor == WHITE: if self.started: self.counter = wsecs + time() - self.intervals[WHITE][-1] else: self.intervals[WHITE][-1] = wsecs self.intervals[BLACK][-1] = bsecs else: if self.started: self.counter = bsecs + time() - self.intervals[BLACK][-1] else: self.intervals[BLACK][-1] = bsecs self.intervals[WHITE][-1] = wsecs self.emit("time_changed") ############################################################################ # Info # ############################################################################ def getPlayerTime (self, color): if color == self.movingColor and self.started: if self.paused: return self.intervals[color][-1] - self.pauseInterval elif self.counter: return self.intervals[color][-1] - (time() - self.counter) return self.intervals[color][-1] def getInitialTime (self): return self.intervals[WHITE][0] @property def display_text (self): t = ("%d " % self.minutes) + _("min") if self.gain != 0: t += (" + %d " % self.gain) + _("sec") return t
Python
import datetime from pychess.Utils.const import RUNNING class LoadingError (Exception): pass class ChessFile: """ This class descripes an opened chessfile. It is lazy in the sense of not parsing any games, that the user don't request. It has no catching. """ def __init__ (self, games): """ Games should be a list of the raw file data, splitted such that games[0] is used for game 0 etc. SourceUri must be the """ self.games = games self.sourceUri = None def loadToModel (self, gameno, position, model=None, quick_parse=True): """ Load the data of game "gameno" into the gamemodel If no model is specified, a new one will be created, loaded and returned """ raise NotImplementedError def __len__ (self): return len(self.games) def get_player_names (self, gameno): """ Returns the a tuple of the players names Default is ("Unknown", "Unknown") if nothing is specified """ return ("Unknown", "Unknown") def get_elo (self, gameno): """ Returns the a tuple of the players rating in ELO format Default is 1600 if nothing is specified in the file """ return (1600, 1600) def get_date (self, gameno): """ Returns the a tuple (year,month,day) of the game date Default is current time if nothing is specified in the file """ today = datetime.date.today() return today.timetuple()[:3] def get_site (self, gameno): """ Returns the a location at which the game took place Default is "?" if nothing is specified in the file """ return "?" def get_event (self, gameno): """ Returns the event at which the game took place Could be "World Chess Cup" or "My local tournament" Default is "?" if nothing is specified in the file """ return "?" def get_round (self, gameno): """ Returns the round of the event at which the game took place Pgn supports having subrounds like 2.1.5, but as of writing, only the first int is returned. Default is 1 if nothing is specified in the file """ return 1 def get_result (self, gameno): """ Returns the result of the game Can be any of: RUNNING, DRAW, WHITEWON or BLACKWON Default is RUNNING if nothing is specified in the file """ return RUNNING
Python
from ChessFile import ChessFile, LoadingError from pychess.Utils.GameModel import GameModel from pychess.Utils.const import * from pychess.Utils.logic import getStatus, repetitionCount from pychess.Utils.lutils.leval import evaluateComplete __label__ = _("Chess Position") __endings__ = "epd", __append__ = True def save (file, model): """Saves game to file in fen format""" color = model.boards[-1].color fen = model.boards[-1].asFen().split(" ") # First four parts of fen are the same in epd file.write(" ".join(fen[:4])) ############################################################################ # Repetition count # ############################################################################ rc = repetitionCount(model.boards[-1]) ############################################################################ # Centipawn evaluation # ############################################################################ if model.status == WHITEWON: if color == WHITE: ce = 32766 else: ce = -32766 elif model.status == BLACKWON: if color == WHITE: ce = -32766 else: ce = 32766 elif model.status == DRAW: ce = 0 else: ce = evaluateComplete(model.boards[-1].board, model.boards[-1].color) ############################################################################ # Opcodes # ############################################################################ opcodes = ( ("fmvn", fen[5]), # In fen full move number is the 6th field ("hmvc", fen[4]), # In fen halfmove clock is the 5th field # Email and name of reciever and sender. We don't know the email. ("tcri", "?@?.? %s" % repr(model.players[color]).replace(";","")), ("tcsi", "?@?.? %s" % repr(model.players[1-color]).replace(";","")), ("ce", ce), #("rc", rc) Rc is kinda broken ) for key, value in opcodes: file.write(" %s %s;" % (key, value)) ############################################################################ # Resign opcode # ############################################################################ if model.status in (WHITEWON, BLACKWON) and model.reason == WON_RESIGN: file.write(" resign;") print >> file file.close() def load (file): return EpdFile ([line for line in map(str.strip, file) if line]) class EpdFile (ChessFile): def loadToModel (self, gameno, position, model=None, quick_parse=True): if not model: model = GameModel() fieldlist = self.games[gameno].split(" ") if len(fieldlist) == 4: fen = self.games[gameno] opcodestr = "" elif len(fieldlist) > 4: fen = " ".join(fieldlist[:4]) opcodestr = " ".join(fieldlist[4:]) else: raise LoadingError, "EPD string can not have less than 4 field" opcodes = {} for opcode in map(str.strip, opcodestr.split(";")): space = opcode.find(" ") if space == -1: opcodes[opcode] = True else: opcodes[opcode[:space]] = opcode[space+1:] if "hmvc" in opcodes: fen += " " + opcodes["hmvc"] else: fen += " 0" if "fmvn" in opcodes: fen += " " + opcodes["fmvn"] else: fen += " 1" model.boards = [model.variant.board(setup=fen)] model.status = WAITING_TO_START # rc is kinda broken #if "rc" in opcodes: # model.boards[0].board.rc = int(opcodes["rc"]) if "resign" in opcodes: if fieldlist[1] == "w": model.status = BLACKWON else: model.status = WHITEWON model.reason = WON_RESIGN if model.status == WAITING_TO_START: model.status, model.reason = getStatus(model.boards[-1]) return model def get_player_names (self, gameno): data = self.games[gameno] names = {} for key in "tcri", "tcsi": keyindex = data.find(key) if keyindex == -1: names[key] = _("Unknown") else: sem = data.find(";", keyindex) if sem == -1: opcode = data[keyindex+len(key)+1:] else: opcode = data[keyindex+len(key)+1:sem] email, name = opcode.split(" ", 1) names[key] = name color = data.split(" ")[1] == "b" and BLACK or WHITE if color == WHITE: return (names["tcri"], names["tcsi"]) else: return (names["tcsi"], names["tcri"])
Python
# -*- coding: UTF-8 -*- import re from datetime import date from pychess.System.Log import log from pychess.Utils.Board import Board from pychess.Utils.GameModel import GameModel from pychess.Utils.Move import parseAny, toSAN, Move from pychess.Utils.const import * from pychess.Utils.logic import getStatus from pychess.Utils.lutils.lmove import ParsingError from pychess.Variants.fischerandom import FischerRandomChess from ChessFile import ChessFile, LoadingError __label__ = _("Chess Game") __endings__ = "pgn", __append__ = True def wrap (string, length): lines = [] last = 0 while True: if len(string)-last <= length: lines.append(string[last:]) break i = string[last:length+last].rfind(" ") lines.append(string[last:i+last]) last += i + 1 return "\n".join(lines) def msToClockTimeTag (ms): """ Converts milliseconds to a chess clock time string in 'WhiteClock'/ 'BlackClock' PGN header format """ msec = ms % 1000 sec = ((ms - msec) % (1000 * 60)) / 1000 min = ((ms - sec*1000 - msec) % (1000*60*60)) / (1000*60) hour = ((ms - min*1000*60 - sec*1000 - msec) % (1000*60*60*24)) / (1000*60*60) return "%01d:%02d:%02d.%03d" % (hour, min, sec, msec) def parseClockTimeTag (tag): """ Parses 'WhiteClock'/'BlackClock' PGN headers and returns the time the player playing that color has left on their clock in milliseconds """ match = re.match("(\d{1,2}).(\d\d).(\d\d).(\d\d\d)", tag) if match: hour, min, sec, msec = match.groups() return int(msec) + int(sec)*1000 + int(min)*60*1000 + int(hour)*60*60*1000 def save (file, model): status = reprResult[model.status] print >> file, '[Event "%s"]' % model.tags["Event"] print >> file, '[Site "%s"]' % model.tags["Site"] print >> file, '[Date "%04d.%02d.%02d"]' % \ (int(model.tags["Year"]), int(model.tags["Month"]), int(model.tags["Day"])) print >> file, '[Round "%s"]' % model.tags["Round"] print >> file, '[White "%s"]' % repr(model.players[WHITE]) print >> file, '[Black "%s"]' % repr(model.players[BLACK]) print >> file, '[Result "%s"]' % status if "ECO" in model.tags: print >> file, '[ECO "%s"]' % model.tags["ECO"] if "WhiteElo" in model.tags: print >> file, '[WhiteElo "%s"]' % model.tags["WhiteElo"] if "BlackElo" in model.tags: print >> file, '[BlackElo "%s"]' % model.tags["BlackElo"] if "TimeControl" in model.tags: print >> file, '[TimeControl "%s"]' % model.tags["TimeControl"] if "Time" in model.tags: print >> file, '[Time "%s"]' % str(model.tags["Time"]) if model.timemodel: print >> file, '[WhiteClock "%s"]' % \ msToClockTimeTag(int(model.timemodel.getPlayerTime(WHITE) * 1000)) print >> file, '[BlackClock "%s"]' % \ msToClockTimeTag(int(model.timemodel.getPlayerTime(BLACK) * 1000)) if issubclass(model.variant, FischerRandomChess): print >> file, '[Variant "Fischerandom"]' if model.boards[0].asFen() != FEN_START: print >> file, '[SetUp "1"]' print >> file, '[FEN "%s"]' % model.boards[0].asFen() print >> file, '[PlyCount "%s"]' % (model.ply-model.lowply) if "EventDate" in model.tags: print >> file, '[EventDate "%s"]' % model.tags["EventDate"] if "Annotator" in model.tags: print >> file, '[Annotator "%s"]' % model.tags["Annotator"] print >> file result = [] walk(model.boards[0], result) result = " ".join(result) result = wrap(result, 80) print >> file, result, status file.close() def walk(node, result): def store(text): if len(result) > 1 and result[-1] == "(": result[-1] = "(%s" % text elif text == ")": result[-1] = "%s)" % result[-1] else: result.append(text) while True: if node is None: break # Initial game or variation comment if node.prev is None: for child in node.children: if isinstance(child, basestring): store("{%s}" % child) node = node.next continue move = Move(node.board.history[-1][0]) movestr = toSAN(node.prev, move) if node.movecount: store(node.movecount) store(movestr) for nag in node.nags: if nag: store(nag) for child in node.children: if isinstance(child, basestring): # comment store("{%s}" % child) else: # variations store("(") walk(child[0], result) store(")") if node.next: node = node.next else: break def stripBrackets (string): brackets = 0 end = 0 result = "" for i, c in enumerate(string): if c == '(': if brackets == 0: result += string[end:i] brackets += 1 elif c == ')': brackets -= 1 if brackets == 0: end = i+1 result += string[end:] return result tagre = re.compile(r"\[([a-zA-Z]+)[ \t]+\"(.*?)\"\]") comre = re.compile(r"(?:\{.*?\})|(?:;.*?[\n\r])|(?:\$[0-9]+)", re.DOTALL) movre = re.compile(r""" ( # group start (?: # non grouping parenthesis start [KQRBN]? # piece [a-h]?[1-8]? # unambiguous column or line x? # capture [a-h][1-8] # destination square =?[QRBN]? # promotion |O\-O(?:\-O)? # castling |0\-0(?:\-0)? # castling ) # non grouping parenthesis end [+#]? # check/mate ) # group end [\?!]* # traditional suffix annotations \s* # any whitespace """, re.VERBOSE) # token categories COMMENT_REST, COMMENT_BRACE, COMMENT_NAG, \ VARIATION_START, VARIATION_END, \ RESULT, FULL_MOVE, MOVE_COUNT, MOVE, MOVE_COMMENT = range(1,11) pattern = re.compile(r""" (\;.*?[\n\r]) # comment, rest of line style |(\{.*?\}) # comment, between {} |(\$[0-9]+) # comment, Numeric Annotation Glyph |(\() # variation start |(\)) # variation end |(\*|1-0|0-1|1/2) # result (spec requires 1/2-1/2 for draw, but we want to tolerate simple 1/2 too) |( ([0-9]{1,3}\s*[.]*\s*)? ([a-hxOoKQRBN1-8+#=]{2,7} |O\-O(?:\-O)? |0\-0(?:\-0)?) ([\?!]{1,2})* ) # move (full, count, move with ?!, ?!) """, re.VERBOSE | re.DOTALL) def load (file): files = [] inTags = False for line in file: line = line.lstrip() if not line: continue elif line.startswith("%"): continue if line.startswith("["): if tagre.match(line) is not None: if not inTags: files.append(["",""]) inTags = True files[-1][0] += line.decode("latin_1") else: if not inTags: files[-1][1] += line.decode('latin_1') else: print "Warning: ignored invalid tag pair %s" % line else: inTags = False if not files: # In rare cases there might not be any tags at all. It's not # legal, but we support it anyways. files.append(["",""]) files[-1][1] += line.decode('latin_1') return PGNFile (files) def parse_string(string, model, board, position, variation=False): boards = [] board = board.clone() last_board = board boards.append(board) error = None parenthesis = 0 v_string = "" prev_group = -1 for i, m in enumerate(re.finditer(pattern, string)): group, text = m.lastindex, m.group(m.lastindex) if parenthesis > 0: v_string += ' '+text if group == VARIATION_END: parenthesis -= 1 if parenthesis == 0: v_last_board.children.append(parse_string(v_string[:-1], model, board.prev, position, variation=True)) v_string = "" prev_group = VARIATION_END continue elif group == VARIATION_START: parenthesis += 1 if parenthesis == 1: v_last_board = last_board if parenthesis == 0: if group == FULL_MOVE: if not variation: if position != -1 and board.ply >= position: break mstr = m.group(MOVE) try: move = parseAny (boards[-1], mstr) except ParsingError, e: notation, reason, boardfen = e.args ply = boards[-1].ply if ply % 2 == 0: moveno = "%d." % (ply/2+1) else: moveno = "%d..." % (ply/2+1) errstr1 = _("The game can't be read to end, because of an error parsing move %(moveno)s '%(notation)s'.") % { 'moveno': moveno, 'notation': notation} errstr2 = _("The move failed because %s.") % reason error = LoadingError (errstr1, errstr2) break board = boards[-1].move(move) #if m.group(MOVE_COUNT): ply = boards[-1].ply if ply % 2 == 0: mvcount = "%d." % (ply/2+1) elif prev_group != FULL_MOVE: mvcount = "%d..." % (ply/2+1) else: mvcount = "" board.movecount = mvcount if m.group(MOVE_COMMENT): board.nags.append(symbol2nag(m.group(MOVE_COMMENT))) if last_board: board.prev = last_board last_board.next = board boards.append(board) last_board = board if not variation: model.moves.append(move) elif group == COMMENT_REST: last_board.children.append(text[1:]) elif group == COMMENT_BRACE: comm = text.replace('{\r\n', '{').replace('\r\n}', '}') comm = comm[1:-1].splitlines() comment = ' '.join([line.strip() for line in comm]) last_board.children.append(comment) elif group == COMMENT_NAG: board.nags.append(text) elif group == RESULT: if text == "1/2": model.status = reprResult.index("1/2-1/2") else: model.status = reprResult.index(text) break else: print "Unknown:",text if group != COMMENT_NAG: prev_group = group if error: raise error return boards class PGNFile (ChessFile): def __init__ (self, games): ChessFile.__init__(self, games) self.expect = None self.tagcache = {} def _getMoves (self, gameno): if not self.games: return [] moves = comre.sub("", self.games[gameno][1]) moves = stripBrackets(moves) moves = movre.findall(moves+" ") if moves and moves[-1] in ("*", "1/2-1/2", "1-0", "0-1"): del moves[-1] return moves def loadToModel (self, gameno, position=-1, model=None, quick_parse=True): if not model: model = GameModel() # the seven mandatory PGN headers model.tags['Event'] = self._getTag(gameno, 'Event') model.tags['Site'] = self._getTag(gameno, 'Site') model.tags['Date'] = self._getTag(gameno, 'Date') model.tags['Round'] = self.get_round(gameno) model.tags['White'], model.tags['Black'] = self.get_player_names(gameno) model.tags['Result'] = reprResult[self.get_result(gameno)] pgnHasYearMonthDay = True for tag in ('Year', 'Month', 'Day'): if not self._getTag(gameno, tag): pgnHasYearMonthDay = False break if model.tags['Date'] and not pgnHasYearMonthDay: date_match = re.match(".*(\d{4}).(\d{2}).(\d{2}).*", model.tags['Date']) if date_match: year, month, day = date_match.groups() model.tags['Year'] = year model.tags['Month'] = month model.tags['Day'] = day # non-mandatory headers for tag in ('Annotator', 'ECO', 'EventDate', 'Time', 'WhiteElo', 'BlackElo', 'TimeControl'): if self._getTag(gameno, tag): model.tags[tag] = self._getTag(gameno, tag) # TODO: enable this when NewGameDialog is altered to give user option of # whether to use PGN's clock time, or their own custom time. Also, # dialog should set+insensitize variant based on the variant of the # game selected in the dialog # if model.timemodel: # for tag, color in (('WhiteClock', WHITE), ('BlackClock', BLACK)): # if self._getTag(gameno, tag): # try: # ms = parseClockTimeTag(self._getTag(gameno, tag)) # model.timemodel.intervals[color][0] = ms / 1000 # except ValueError: # raise LoadingError( \ # "Error parsing '%s' Header for gameno %s" % (tag, gameno)) # if model.tags['TimeControl']: # minutes, gain = parseTimeControlTag(model.tags['TimeControl']) # model.timemodel.minutes = minutes # model.timemodel.gain = gain fenstr = self._getTag(gameno, "FEN") variant = self._getTag(gameno, "Variant") if variant and ("fischer" in variant.lower() or "960" in variant): from pychess.Variants.fischerandom import FRCBoard model.variant = FischerRandomChess model.boards = [FRCBoard(fenstr)] else: if fenstr: model.boards = [Board(fenstr)] else: model.boards = [Board(setup=True)] del model.moves[:] del model.variations[:] error = None if quick_parse: movstrs = self._getMoves (gameno) for i, mstr in enumerate(movstrs): if position != -1 and model.ply >= position: break try: move = parseAny (model.boards[-1], mstr) except ParsingError, e: notation, reason, boardfen = e.args ply = model.boards[-1].ply if ply % 2 == 0: moveno = "%d." % (i/2+1) else: moveno = "%d..." % (i/2+1) errstr1 = _("The game can't be read to end, because of an error parsing move %(moveno)s '%(notation)s'.") % { 'moveno': moveno, 'notation': notation} errstr2 = _("The move failed because %s.") % reason error = LoadingError (errstr1, errstr2) break model.moves.append(move) model.boards.append(model.boards[-1].move(move)) else: notation_string = self.games[gameno][1] model.boards = parse_string(notation_string, model, model.boards[-1], position) def walk(node, path): if node.next is None: model.variations.append(path+[node]) else: walk(node.next, path+[node]) if node.children: for child in node.children: if isinstance(child, list): if len(child) > 1: walk(child[1], list(path)) # Collect all variation paths into a list of board lists # where the first one will be the boards of mainline game. # model.boards will allways point to the current shown variation # which will be model.variations[0] when we are in the mainline. walk(model.boards[0], []) if model.timemodel: if quick_parse: blacks = len(movstrs)/2 whites = len(movstrs)-blacks else: blacks = len(model.moves)/2 whites = len(model.moves)-blacks model.timemodel.intervals = [ [model.timemodel.intervals[0][0]]*(whites+1), [model.timemodel.intervals[1][0]]*(blacks+1), ] log.debug("pgn.loadToModel: intervals %s\n" % model.timemodel.intervals) # Find the physical status of the game model.status, model.reason = getStatus(model.boards[-1]) # Apply result from .pgn if the last position was loaded if position == -1 or len(model.moves) == position - model.lowply: status = self.get_result(gameno) if status in (WHITEWON, BLACKWON) and status != model.status: model.status = status model.reason = WON_RESIGN elif status == DRAW: model.status = DRAW model.reason = DRAW_AGREE # If parsing gave an error we throw it now, to enlarge our possibility # of being able to continue the game from where it failed. if error: raise error return model def _getTag (self, gameno, tagkey): if gameno in self.tagcache: if tagkey in self.tagcache[gameno]: return self.tagcache[gameno][tagkey] else: return None else: if self.games: self.tagcache[gameno] = dict(tagre.findall(self.games[gameno][0])) return self._getTag(gameno, tagkey) else: return None def get_player_names (self, no): p1 = self._getTag(no,"White") and self._getTag(no,"White") or "Unknown" p2 = self._getTag(no,"Black") and self._getTag(no,"Black") or "Unknown" return (p1, p2) def get_elo (self, no): p1 = self._getTag(no,"WhiteElo") and self._getTag(no,"WhiteElo") or "1600" p2 = self._getTag(no,"BlackElo") and self._getTag(no,"BlackElo") or "1600" p1 = p1.isdigit() and int(p1) or 1600 p2 = p2.isdigit() and int(p2) or 1600 return (p1, p2) def get_date (self, no): the_date = self._getTag(no,"Date") today = date.today() if not the_date: return today.timetuple()[:3] return [ s.isdigit() and int(s) or today.timetuple()[i] \ for i,s in enumerate(the_date.split(".")) ] def get_site (self, no): return self._getTag(no,"Site") and self._getTag(no,"Site") or "?" def get_event (self, no): return self._getTag(no,"Event") and self._getTag(no,"Event") or "?" def get_round (self, no): round = self._getTag(no,"Round") if not round: return 1 if round.find(".") >= 1: round = round[:round.find(".")] if not round.isdigit(): return 1 return int(round) def get_result (self, no): pgn2Const = {"*":RUNNING, "1/2-1/2":DRAW, "1/2":DRAW, "1-0":WHITEWON, "0-1":BLACKWON} if self._getTag(no,"Result") in pgn2Const: return pgn2Const[self._getTag(no,"Result")] return RUNNING nag2symbolDict = { "$0": "", "$1": "!", "$2": "?", "$3": "!!", "$4": "??", "$5": "!?", "$6": "?!", "$7": "□", "$8": "□", "$9": "??", "$10": "=", "$11": "=", "$12": "=", "$13": "∞", "$14": "+=", "$15": "=+", "$16": "±", "$17": "∓", "$18": "+-", "$19": "-+", "$20": "+--", "$21": "--+", "$22": "⨀", "$23": "⨀", } symbol2nagDict = {} for k, v in nag2symbolDict.iteritems(): if v not in symbol2nagDict: symbol2nagDict[v] = k def nag2symbol(nag): return nag2symbolDict.get(nag, nag) def symbol2nag(symbol): return symbol2nagDict[symbol]
Python
__all__ = ["fen", "epd", "pgn",'chessalpha2']
Python
# -*- coding: utf-8 -*- from ChessFile import ChessFile, LoadingError from htmlentitydefs import entitydefs from pychess.Utils import Cord from pychess.Utils.GameModel import GameModel from pychess.Utils.Move import toFAN from pychess.Utils.Piece import Piece from pychess.Utils.const import * from pychess.Utils.logic import getStatus import re group = lambda l, s: [l[i:i+s] for i in xrange(0,len(l),s)] __label__ = _("Chess Alpha 2 Diagram") __endings__ = "html", __append__ = True #table[background][color][piece] diaPieces = ((('\'','Ê','Â','À','Ä','Æ','È'), ('\'','ê','â','à','ä','æ','è')), (('#','Ë','Ã','Á','Å','Ç','É'), ('#','ë','ã','á','å','ç','é'))) borderNums = ('¬','"','£','$','%','^','&','*') lisPieces = ((FAN_PIECES[BLACK][KNIGHT],'K'), (FAN_PIECES[BLACK][BISHOP],'J'), (FAN_PIECES[BLACK][ROOK],'L'), (FAN_PIECES[BLACK][QUEEN],'M'), (FAN_PIECES[BLACK][KING],'N'), (FAN_PIECES[WHITE][KNIGHT],'k'), (FAN_PIECES[WHITE][BISHOP],'j'), (FAN_PIECES[WHITE][ROOK],'l'), (FAN_PIECES[WHITE][QUEEN],'m'), (FAN_PIECES[WHITE][KING],'n'), ('†', '+'), ('‡', '+'), ('1/2', 'Z')) def fanconv(fan): for f,r in lisPieces: fan = fan.replace(f,r) return fan # Dictionaries and expressions for parsing diagrams entitydefs = dict(("&%s;"%a,unichr(ord(b)).encode('utf-8')) for a,b in entitydefs.iteritems() if len(b)==1) def2entity = dict((b, a) for a,b in entitydefs.iteritems()) flatPieces = [c for a in diaPieces for b in a for c in b] piecesDia = dict((c,(col,pie)) for a in diaPieces for col,b in enumerate(a) for pie,c in enumerate(b)) pat = "%s|%s" % ("|".join(flatPieces), "|".join(def2entity[a] for a in flatPieces if a in def2entity)) reg1 = re.compile("(?:%s){8}"%pat, re.IGNORECASE) reg2 = re.compile(pat, re.IGNORECASE) style = """ table.pychess {display:inline-block; vertical-align:top} table.pychess td {margin:0; padding:0; font-size:10pt; font-family:"Chess Alpha 2"; padding-left:.5em} table.pychess td.numa {width:0; text-align:right} table.pychess td.numa {width:0; text-align:right; padding-left:1em} table.pychess td.status {text-align:center; font-size:12pt; padding-right:2em} table.pychess pre {margin:0; padding:0; font-family:"Chess Alpha 2"; font-size:16pt; text-align:center; line-height:1}""" def save (file, model): """Saves the position as a diagram using chess fonts""" print >> file, "<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'>" print >> file, "<style type='text/css'>%s</style>"%style print >> file, "<table cellspacing='0' cellpadding='0' class='pychess'><tr><td colspan='6'><pre>" writeDiagram(file, model) print >> file, "</pre></td></tr>" sanmvs = map(toFAN, model.boards[:-1], model.moves) sanmvs = map(fanconv, sanmvs) if model.lowply & 1: sanmvs = ["&gt;"]+sanmvs if model.status in (DRAW, WHITEWON, BLACKWON): sanmvs.extend(['']*(-len(sanmvs)%2)) sanmvs.append(fanconv(reprResult[model.status])) sanmvs.extend(['']*(-len(sanmvs)%4)) sanmvs = group(sanmvs, 2) for i in xrange((len(sanmvs)+1)/2): left = i+1+model.lowply/2 writeMoves(file, str(i+1+model.lowply/2), sanmvs[i], str(left+len(sanmvs)/2), sanmvs[i+len(sanmvs)/2]) print >> file, "</table>" file.close() def writeMoves(file, m1, movepair1, m2, movepair2): m1 += '.'; m2 += '.' if not movepair2[0]: m2 = '' print >> file, "<tr><td class='numa'>%s</td><td>%s</td><td>%s</td>" % (m1, movepair1[0], movepair1[1]) if not movepair2[1] and movepair2[0] in map(fanconv, reprResult): print >> file, "<td class='status' colspan='3'>%s</td></tr>" % movepair2[0] else: print >> file, "<td class='numb'>%s</td><td>%s</td><td>%s</td></tr>" % (m2, movepair2[0], movepair2[1]) def writeDiagram(file, model, border = True, whitetop = False): data = model.boards[-1].data[:] if not whitetop: data.reverse() if border: print >> file, "[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]" for y,row in enumerate(data): if whitetop: file.write(borderNums(y)) else: file.write(borderNums[7-y]) for x,piece in enumerate(row): bg = y%2==x%2 if piece == None: color = WHITE piece = EMPTY else: color = piece.color piece = piece.piece c = diaPieces[bg][color][piece] if c in def2entity: c = def2entity[c] file.write(c) file.write('\\\n') if border: print >> file, "{ABCDEFGH}" def load (file): lines = reg1.findall(file.read().encode('utf-8')) return AlphaFile(group(lines, 8)) class AlphaFile (ChessFile): def loadToModel (self, gameno, position, model=None): if not model: model = GameModel() board = model.variant.board() for y,row in enumerate(self.games[gameno]): for x,letter in enumerate(reg2.findall(row)): if letter in entitydefs: letter = entitydefs[letter] if letter not in piecesDia: raise LoadingError (_("Couldn't load the diagram '%s'")%repr(letter)) col, pie = piecesDia[letter] if pie != EMPTY: board.addPiece(Cord(x,7-y), Piece(col,pie)) model.boards = [board] if model.status == WAITING_TO_START: model.status, model.reason = getStatus(model.boards[-1]) return model
Python
from pychess.Utils.GameModel import GameModel from pychess.Utils.const import WAITING_TO_START from pychess.Utils.logic import getStatus __label__ = _("Simple Chess Position") __endings__ = "fen", __append__ = True def save (file, model): """Saves game to file in fen format""" print >> file, model.boards[-1].asFen() file.close() def load (file): return FenFile ([line for line in map(str.strip, file) if line]) from ChessFile import ChessFile class FenFile (ChessFile): def loadToModel (self, gameno, position, model=None, quick_parse=True): if not model: model = GameModel() # We have to set full move number to 1 to make sure LBoard and GameModel # are synchronized. #fenlist = self.games[gameno].split(" ") #if len(fenlist) == 6: # fen = " ".join(fenlist[:5]) + " 1" fen = self.games[gameno] model.boards = [model.variant.board(setup=fen)] if model.status == WAITING_TO_START: model.status, model.reason = getStatus(model.boards[-1]) return model
Python
VERSION = "0.10" VERSION_NAME = "Staunton"
Python
import os import webbrowser import math import atexit import signal import gobject, gtk from gtk import DEST_DEFAULT_MOTION, DEST_DEFAULT_HIGHLIGHT, DEST_DEFAULT_DROP from pychess.System import conf, glock, uistuff, prefix, SubProcess, Log from pychess.System.uistuff import POSITION_NONE, POSITION_CENTER, POSITION_GOLDEN from pychess.System.Log import log, start_thread_dump from pychess.Utils.const import HINT, NAME, SPY from pychess.Utils import book # Kills pychess if no sqlite available from pychess.widgets import newGameDialog from pychess.widgets import tipOfTheDay from pychess.widgets import LogDialog from pychess.widgets.discovererDialog import DiscovererDialog from pychess.widgets import gamewidget from pychess.widgets import gamenanny from pychess.widgets import ionest from pychess.widgets import preferencesDialog, gameinfoDialog, playerinfoDialog from pychess.widgets.TaskerManager import TaskerManager from pychess.widgets.TaskerManager import NewGameTasker from pychess.widgets.TaskerManager import InternetGameTasker from pychess.Players.engineNest import discoverer from pychess.ic import ICLogon from pychess import VERSION, VERSION_NAME ################################################################################ # gameDic - containing the gamewidget:gamemodel of all open games # ################################################################################ gameDic = {} class GladeHandlers: def on_window_key_press (window, event): # Tabbing related shortcuts if not gamewidget.getheadbook(): pagecount = 0 else: pagecount = gamewidget.getheadbook().get_n_pages() if pagecount > 1: if event.state & gtk.gdk.CONTROL_MASK: page_num = gamewidget.getheadbook().get_current_page() # Move selected if event.state & gtk.gdk.SHIFT_MASK: child = gamewidget.getheadbook().get_nth_page(page_num) if event.keyval == gtk.keysyms.Page_Up: gamewidget.getheadbook().reorder_child(child, (page_num-1)%pagecount) elif event.keyval == gtk.keysyms.Page_Down: gamewidget.getheadbook().reorder_child(child, (page_num+1)%pagecount) # Change selected else: if event.keyval == gtk.keysyms.Page_Up: gamewidget.getheadbook().set_current_page((page_num-1)%pagecount) elif event.keyval == gtk.keysyms.Page_Down: gamewidget.getheadbook().set_current_page((page_num+1)%pagecount) # Other pass def on_gmwidg_created (handler, gmwidg, gamemodel): gameDic[gmwidg] = gamemodel # Bring playing window to the front gamewidget.getWidgets()["window1"].present() # Make sure we can remove gamewidgets from gameDic later gmwidg.connect("closed", GladeHandlers.__dict__["on_gmwidg_closed"]) def on_gmwidg_closed (gmwidg): del gameDic[gmwidg] if not gameDic: for widget in gamewidget.MENU_ITEMS: gamewidget.getWidgets()[widget].set_property('sensitive', False) # Drag 'n' Drop # def on_drag_received (wi, context, x, y, selection, target_type, timestamp): uri = selection.data.strip() uris = uri.split() if len(uris) > 1: log.warn("%d files were dropped. Only loading the first" % len(uris)) uri = uris[0] newGameDialog.LoadFileExtension.run(uri) # Game Menu # def on_new_game1_activate (widget): newGameDialog.NewGameMode.run() def on_play_internet_chess_activate (widget): ICLogon.run() def on_load_game1_activate (widget): newGameDialog.LoadFileExtension.run(None) def on_set_up_position_activate (widget): # Not implemented pass def on_enter_game_notation_activate (widget): newGameDialog.EnterNotationExtension.run() def on_save_game1_activate (widget): ionest.saveGame (gameDic[gamewidget.cur_gmwidg()]) def on_save_game_as1_activate (widget): ionest.saveGameAs (gameDic[gamewidget.cur_gmwidg()]) def on_properties1_activate (widget): gameinfoDialog.run(gamewidget.getWidgets(), gameDic) def on_player_rating1_activate (widget): playerinfoDialog.run(gamewidget.getWidgets()) def on_close1_activate (widget): gmwidg = gamewidget.cur_gmwidg() response = ionest.closeGame(gmwidg, gameDic[gmwidg]) def on_quit1_activate (widget, *args): if ionest.closeAllGames(gameDic.items()) in (gtk.RESPONSE_OK, gtk.RESPONSE_YES): gtk.main_quit() else: return True # View Menu # def on_rotate_board1_activate (widget): gmwidg = gamewidget.cur_gmwidg() if gmwidg.board.view.rotation: gmwidg.board.view.rotation = 0 else: gmwidg.board.view.rotation = math.pi def on_fullscreen1_activate (widget): gamewidget.getWidgets()["window1"].fullscreen() gamewidget.getWidgets()["fullscreen1"].hide() gamewidget.getWidgets()["leave_fullscreen1"].show() def on_leave_fullscreen1_activate (widget): gamewidget.getWidgets()["window1"].unfullscreen() gamewidget.getWidgets()["leave_fullscreen1"].hide() gamewidget.getWidgets()["fullscreen1"].show() def on_about1_activate (widget): gamewidget.getWidgets()["aboutdialog1"].show() def on_log_viewer1_activate (widget): if widget.get_active(): LogDialog.show() else: LogDialog.hide() def on_show_sidepanels_activate (widget): gamewidget.zoomToBoard(not widget.get_active()) def on_hint_mode_activate (widget): for gmwidg in gameDic.keys(): gamenanny.setAnalyzerEnabled(gmwidg, HINT, widget.get_active()) def on_spy_mode_activate (widget): for gmwidg in gameDic.keys(): print "setting spymode for", gmwidg, "to", widget.get_active() gamenanny.setAnalyzerEnabled(gmwidg, SPY, widget.get_active()) # Settings menu # def on_preferences_activate (widget): preferencesDialog.run(gamewidget.getWidgets()) # Help menu # def on_about_chess1_activate (widget): webbrowser.open(_("http://en.wikipedia.org/wiki/Chess")) def on_how_to_play1_activate (widget): webbrowser.open(_("http://en.wikipedia.org/wiki/Rules_of_chess")) def translate_this_application_activate(widget): webbrowser.open("http://code.google.com/p/pychess/wiki/RosettaTranslates") def on_TipOfTheDayMenuItem_activate (widget): tipOfTheDay.TipOfTheDay.show() # Other # def on_notebook2_switch_page (widget, page, page_num): gamewidget.getWidgets()["notebook3"].set_current_page(page_num) dnd_list = [ ('application/x-chess-pgn', 0, 0xbadbeef), ('application/da-chess-pgn', 0, 0xbadbeef), ('text/plain', 0, 0xbadbeef) ] class PyChess: def __init__(self, chess_file): self.initGlade() self.handleArgs(chess_file) def initGlade(self): #======================================================================= # Init glade and the 'GladeHandlers' #======================================================================= gtk.glade.set_custom_handler(self.widgetHandler) gtk.about_dialog_set_url_hook(self.website) widgets = uistuff.GladeWidgets("PyChess.glade") widgets.getGlade().signal_autoconnect(GladeHandlers.__dict__) #------------------------------------------------------ Redirect widgets gamewidget.setWidgets(widgets) #-------------------------- Main.py still needs a minimum of information ionest.handler.connect("gmwidg_created", GladeHandlers.__dict__["on_gmwidg_created"]) #---------------------- The only menuitems that need special initing for widget in ("hint_mode", "spy_mode"): widgets[widget].set_active(False) widgets[widget].set_sensitive(False) uistuff.keep(widgets["show_sidepanels"], "show_sidepanels") #======================================================================= # Show main window and init d'n'd #======================================================================= widgets["window1"].set_title('%s - PyChess' % _('Welcome')) widgets["window1"].connect("key-press-event", GladeHandlers.__dict__["on_window_key_press"]) uistuff.keepWindowSize("main", widgets["window1"], (575,479), POSITION_GOLDEN) widgets["window1"].show() widgets["Background"].show_all() flags = DEST_DEFAULT_MOTION | DEST_DEFAULT_HIGHLIGHT | DEST_DEFAULT_DROP # To get drag in the whole window, we add it to the menu and the # background. If it can be gotten to work, the drag_dest_set_proxy # method is very interesting. widgets["menubar1"].drag_dest_set(flags, dnd_list, gtk.gdk.ACTION_COPY) widgets["Background"].drag_dest_set(flags, dnd_list, gtk.gdk.ACTION_COPY) # The following two should really be set in the glade file widgets["menubar1"].set_events(widgets["menubar1"].get_events() | gtk.gdk.DRAG_STATUS) widgets["Background"].set_events(widgets["Background"].get_events() | gtk.gdk.DRAG_STATUS) #======================================================================= # Init 'minor' dialogs #======================================================================= #------------------------------------------------------------ Log dialog LogDialog.add_destroy_notify(lambda: widgets["log_viewer1"].set_active(0)) #---------------------------------------------------------- About dialog clb = widgets["aboutdialog1"].get_child().get_children()[1].get_children()[2] widgets["aboutdialog1"].set_name(NAME) #widgets["aboutdialog1"].set_position(gtk.WIN_POS_CENTER) #widgets["aboutdialog1"].set_website_label(_("PyChess Homepage")) link = widgets["aboutdialog1"].get_website() if os.path.isfile(prefix.addDataPrefix(".svn/entries")): f = open(prefix.addDataPrefix(".svn/entries")) line4 = [f.next() for i in xrange(4)][-1].strip() widgets["aboutdialog1"].set_version(VERSION_NAME+" r"+line4) else: widgets["aboutdialog1"].set_version(VERSION_NAME+" "+VERSION) with open(prefix.addDataPrefix("ARTISTS")) as f: widgets["aboutdialog1"].set_artists(f.read().splitlines()) with open(prefix.addDataPrefix("AUTHORS")) as f: widgets["aboutdialog1"].set_authors(f.read().splitlines()) with open(prefix.addDataPrefix("DOCUMENTERS")) as f: widgets["aboutdialog1"].set_documenters(f.read().splitlines()) with open(prefix.addDataPrefix("TRANSLATORS")) as f: widgets["aboutdialog1"].set_translator_credits(f.read()) def callback(button, *args): widgets["aboutdialog1"].hide() return True clb.connect("activate", callback) clb.connect("clicked", callback) widgets["aboutdialog1"].connect("delete-event", callback) #----------------------------------------------------- Discoverer dialog def discovering_started (discoverer, binnames): gobject.idle_add(DiscovererDialog.show, discoverer, widgets["window1"]) discoverer.connect("discovering_started", discovering_started) DiscovererDialog.init(discoverer) discoverer.start() #------------------------------------------------- Tip of the day dialog if conf.get("show_tip_at_startup", False): tipOfTheDay.TipOfTheDay.show() def website(self, clb, link): webbrowser.open(link) def widgetHandler (self, glade, functionName, widgetName, s1, s2, i1, i2): # Tasker is currently the only widget that uses glades CustomWidget tasker = TaskerManager() tasker.packTaskers (NewGameTasker(), InternetGameTasker()) return tasker def handleArgs (self, chess_file): if chess_file: def do (discoverer): newGameDialog.LoadFileExtension.run(chess_file) glock.glock_connect_after(discoverer, "all_engines_discovered", do) def run (no_debug, glock_debug, thread_debug, chess_file): PyChess(chess_file) signal.signal(signal.SIGINT, gtk.main_quit) def cleanup (): SubProcess.finishAllSubprocesses() atexit.register(cleanup) gtk.gdk.threads_init() # Start logging Log.DEBUG = False if no_debug is True else True glock.debug = glock_debug log.debug("Started\n") if thread_debug: start_thread_dump() gtk.main()
Python
#!/usr/bin/python from pychess.System import glock from pychess.System.GtkWorker import GtkWorker from pychess.System.Log import log from pychess.System.ThreadPool import pool from pychess.System.prefix import addDataPrefix, isInstalled from pychess.System.repeat import repeat_sleep from pychess.Utils.book import getOpenings from pychess.Utils.const import * from pychess.Utils.lutils import leval, lsearch from pychess.Utils.lutils.LBoard import LBoard from pychess.Utils.lutils.lmove import determineAlgebraicNotation, parseSAN, \ listToSan, toSAN, parseAny, toLAN from pychess.Utils.lutils.lsearch import alphaBeta from pychess.Utils.lutils.validator import validateMove from pychess.Utils.repr import reprResult_long, reprReason_long from pychess.ic import FICSConnection from pychess.widgets import LogDialog from time import time from urllib import urlopen, urlencode import email.Utils import gettext import gtk.glade import math import pychess import random import signal import subprocess import sys print "feature done=0" gettext.install("pychess", localedir=addDataPrefix("lang"), unicode=1) class PyChess: def __init__ (self): self.sd = 10 self.skipPruneChance = 0 self.useegtb = False self.increment = None self.mytime = None #self.optime = None self.scr = 0 # The current predicted score. Used when accepting draw offers self.playingAs = WHITE def makeReady(self): try: import psyco psyco.bind(alphaBeta) except ImportError: pass #=========================================================================== # Play related #=========================================================================== def __remainingMovesA (self): # Based on regression of a 180k games pgn x = len(self.board.history) return -1.71086e-12*x**6 \ +1.69103e-9*x**5 \ -6.00801e-7*x**4 \ +8.17741e-5*x**3 \ +2.91858e-4*x**2 \ -0.94497*x \ +78.8979 def __remainingMovesB (self): # We bet a game will be around 80 moves x = len(self.board.history) return max(80-x,4) def __getBestOpening (self): score = 0 move = None for m, w, d, l in getOpenings(self.board): s = (w+d/3.0)*random.random() if not move or s > score: move = m score = s return move def __go (self, worker): """ Finds and prints the best move from the current position """ # TODO: Length info should be put in the book. # Btw. 10 is not enough. Try 20 #if len(self.board.history) < 14: movestr = self.__getBestOpening() if movestr: mvs = [parseSAN(self.board, movestr)] #if len(self.board.history) >= 14 or not movestr: if not movestr: lsearch.skipPruneChance = self.skipPruneChance lsearch.useegtb = self.useegtb lsearch.searching = True if self.mytime == None: lsearch.endtime = sys.maxint worker.publish("Searching to depth %d without timelimit" % self.sd) mvs, self.scr = alphaBeta (self.board, self.sd) else: usetime = self.mytime / self.__remainingMovesA() if self.mytime < 6*60+self.increment*40: # If game is blitz, we assume 40 moves rather than 80 usetime *= 2 # The increment is a constant. We'll use this allways usetime += self.increment if usetime < 0.5: # We don't wan't to search for e.g. 0 secs usetime = 0.5 starttime = time() lsearch.endtime = starttime + usetime prevtime = 0 worker.publish("Time left: %3.2f seconds; Planing to thinking for %3.2f seconds" % (self.mytime, usetime)) for depth in range(1, self.sd+1): # Heuristic time saving # Don't waste time, if the estimated isn't enough to complete next depth if usetime > prevtime*4 or usetime <= 1: lsearch.timecheck_counter = lsearch.TIMECHECK_FREQ search_result = alphaBeta(self.board, depth) if lsearch.searching: mvs, self.scr = search_result if time() > lsearch.endtime: # Endtime occured after depth worker.publish("Endtime occured after depth") break worker.publish("got moves %s from depth %d" % (" ".join(listToSan(self.board, mvs)), depth)) else: # We were interrupted worker.publish("I was interrupted (%d) while searching depth %d" % (lsearch.last, depth)) if depth == 1: worker.publish("I've got to have some move, so I use what we got") mvs, self.scr = search_result break prevtime = time()-starttime - prevtime else: worker.publish("I don't have enough time to go into depth %d" % depth) # Not enough time for depth break else: worker.publish("I searched through depths [1, %d]" % (self.sd+1)) self.mytime -= time() - starttime self.mytime += self.increment if not mvs: if not lsearch.searching: # We were interupted lsearch.movesearches = 0 lsearch.nodes = 0 return # This should only happen in terminal mode #if lsearch.last == 4: # print "resign" #else: if self.scr == 0: worker.publish("result %s" % reprResult[DRAW]) elif self.scr < 0: if self.board.color == WHITE: worker.publish("result %s" % reprResult[BLACKWON]) else: worker.publish("result %s" % reprResult[WHITEWON]) else: if self.board.color == WHITE: worker.publish("result %s" % reprResult[WHITEWON]) else: worker.publish("result %s" % reprResult[BLACKWON]) worker.publish("last: %d %d" % (lsearch.last, self.scr)) return worker.publish("moves were: %s %d" % (" ".join(listToSan(self.board, mvs)), self.scr)) lsearch.movesearches = 0 lsearch.nodes = 0 lsearch.searching = False move = mvs[0] sanmove = toSAN(self.board, move) return sanmove def __analyze (self, worker): """ Searches, and prints info from, the position as stated in the cecp protocol """ start = time() lsearch.endtime = sys.maxint lsearch.searching = True for depth in xrange (1, 10): if not lsearch.searching: break t = time() mvs, scr = alphaBeta (self.board, depth) # Analyze strings are given in the following format: # depth in plies, evaluation, time used, nodes searched, p/v movstrs = " ".join(listToSan(self.board, mvs)) worker.publish("\t".join(("%d","%d","%0.2f","%d","%s")) % (depth, scr, time()-start, lsearch.nodes, movstrs)) if lsearch.movesearches: mvs_pos = lsearch.nodes/float(lsearch.movesearches) mvs_tim = lsearch.nodes/(time()-t) worker.publish("%0.1f moves/position; %0.1f n/s" % (mvs_pos, mvs_tim)) lsearch.nodes = 0 lsearch.movesearches = 0 def __analyze2 (self): import profile profile.runctx("self.__analyze2()", locals(), globals(), "/tmp/pychessprofile") from pstats import Stats s = Stats("/tmp/pychessprofile") s.sort_stats('cumulative') s.print_stats() class PyChessCECP(PyChess): def __init__ (self): PyChess.__init__(self) self.board = LBoard(NORMALCHESS) self.board.applyFen(FEN_START) self.forced = False self.analyzing = False self.worker = None self.features = { "setboard": 1, "analyze": 1, "san": 1, "usermove": 1, "reuse": 0, "draw": 1, "sigterm": 1, "colors": 1, "variants": "normal,nocastle,fischerandom", "myname": "PyChess %s" % pychess.VERSION } def makeReady(self): PyChess.makeReady(self) def run (self): while True: line = raw_input() if not line.strip(): continue lines = line.split() if lines[0] == "protover": stringPairs = ["=".join([k,repr(v)]) for k,v in self.features.iteritems()] print "feature %s done=1" % " ".join(stringPairs) elif lines[0] == "usermove": self.__stopSearching() move = parseAny (self.board, lines[1]) if not validateMove(self.board, move): print "Illegal move", lines[1] continue self.board.applyMove(move) self.playingAs = self.board.color if not self.forced and not self.analyzing: self.__go() if self.analyzing: self.__analyze() elif lines[0] == "sd": self.sd = int(lines[1]) self.skipPruneChance = max(0, (5-self.sd)*0.02) if self.sd >= 5: print "If the game has no timesettings, you probably don't want\n"+\ "to set a search depth much greater than 4" elif lines[0] == "egtb": # This is a crafty command interpreted a bit loose self.useegtb = True elif lines[0] == "level": moves = int(lines[1]) self.increment = int(lines[3]) minutes = lines[2].split(":") self.mytime = int(minutes[0])*60 if len(minutes) > 1: self.mytime += int(minutes[1]) print "Playing %d moves in %d seconds + %d increment" % \ (moves, self.mytime, self.increment) elif lines[0] == "time": self.mytime = int(lines[1])/100. #elif lines[0] == "otim": # self.optime = int(lines[1]) elif lines[0] == "quit": sys.exit() elif lines[0] == "result": # We don't really care what the result is at the moment. sys.exit() elif lines[0] == "force": if not self.forced and not self.analyzing: self.forced = True self.__stopSearching() elif lines[0] == "go": self.playingAs = self.board.color self.forced = False self.__go() elif lines[0] == "undo": self.__stopSearching() self.board.popMove() if self.analyzing: self.__analyze() elif lines[0] == "?": self.__stopSearching() elif lines[0] in ("black", "white"): newColor = lines[0] == "black" and BLACK or WHITE if self.playingAs != newColor: self.__stopSearching() self.playingAs = newColor # It is dangerous to use the same table, when we change color #lsearch.table.clear() self.board.setColor(newColor) # Concider the case: # * White moves a pawn and creates a enpassant cord # * Spy analyzer is not set back to white to analyze the # position. An attackable enpassant cord now no longer makes # sense. # * Notice though, that when the color is shifted back to black # to make the actual move - and it is an enpassant move - the # cord won't be set in the lboard. self.board.setEnpassant(None) if self.analyzing: self.__analyze() elif lines[0] == "analyze": self.playingAs = self.board.color self.analyzing = True self.__analyze() elif lines[0] == "draw": if self.scr <= 0: print "offer draw" elif lines[0] == "random": leval.random = True elif lines[0] == "variant": if lines[1] == "fischerandom": self.board.variant = FISCHERRANDOMCHESS elif lines[0] == "setboard": self.__stopSearching() self.board.applyFen(" ".join(lines[1:])) if self.analyzing: self.__analyze() elif lines[0] in ("xboard", "otim", "hard", "easy", "nopost", "post", "accepted", "rejected"): pass else: print "Warning (unknown command):", line def __stopSearching(self): lsearch.searching = False if self.worker: self.worker.cancel() glock.acquire() self.worker.get() glock.release() self.worker = None def __go (self): self.worker = GtkWorker(lambda worker: PyChess._PyChess__go(self, worker)) def process (worker, messages): print "\n".join(messages) self.worker.connect("published", process) def ondone (worker, result): if not result: return self.board.applyMove(parseSAN(self.board,result)) print "move %s" % result self.worker.connect("done", ondone) self.worker.execute() def __analyze (self): self.worker = GtkWorker(lambda worker: PyChess._PyChess__analyze(self, worker)) def process (worker, messages): print "\n".join(messages) self.worker.connect("published", process) self.worker.execute() class PyChessFICS(PyChess): def __init__ (self, password, from_address, to_address): PyChess.__init__(self) self.ports = (23, 5000) if not password: self.username = "guest" else: self.username = "PyChess" self.owner = "Lobais" self.password = password self.from_address = "The PyChess Bot <%s>" % from_address self.to_address = "Thomas Dybdahl Ahle <%s>" % to_address # Possible start times self.minutes = (1,2,3,4,5,6,7,8,9,10) self.gains = (0,5,10,15,20) # Possible colors. None == random self.colors = (WHITE, BLACK, None) # The amount of random challenges, that PyChess sends with each seek self.challenges = 10 self.useegtb = True self.sudos = set() self.ownerOnline = False self.waitingForPassword = None self.log = [] self.acceptedTimesettings = [] self.worker = None repeat_sleep(self.sendChallenges, 60*1) def __triangular(self, low, high, mode): """Triangular distribution. Continuous distribution bounded by given lower and upper limits, and having a given mode value in-between. http://en.wikipedia.org/wiki/Triangular_distribution """ u = random.random() c = (mode - low) / (high - low) if u > c: u = 1 - u c = 1 - c low, high = high, low tri = low + (high - low) * (u * c) ** 0.5 if tri < mode: return int(tri) elif tri > mode: return int(math.ceil(tri)) return int(round(tri)) def sendChallenges(self): if self.connection.bm.isPlaying(): return True statsbased = ((0.39197722779282, 3, 0), (0.59341408108783, 5, 0), (0.77320877377846, 1, 0), (0.8246379941394, 10, 0), (0.87388717406441, 2, 12), (0.91443760169489, 15, 0), (0.9286423058163, 4, 0), (0.93891977227793, 2, 0), (0.94674539138335, 20, 0), (0.95321476842423, 2, 2), (0.9594588808257, 5, 2), (0.96564528079889, 3, 2), (0.97173859621034, 7, 0), (0.97774906636184, 3, 1), (0.98357243654425, 5, 12), (0.98881309737017, 5, 5), (0.99319644938247, 6, 0), (0.99675879556023, 3, 12), (1, 5, 3)) #n = random.random() #for culminativeChance, minute, gain in statsbased: # if n < culminativeChance: # break culminativeChance, minute, gain = random.choice(statsbased) #type = random.choice((TYPE_LIGHTNING, TYPE_BLITZ, TYPE_STANDARD)) #if type == TYPE_LIGHTNING: # minute = self.__triangular(0,2+1,1) # mingain = not minute and 1 or 0 # maxgain = int((3-minute)*3/2) # gain = random.randint(mingain, maxgain) #elif type == TYPE_BLITZ: # minute = self.__triangular(0,14+1,5) # mingain = max(int((3-minute)*3/2+1), 0) # maxgain = int((15-minute)*3/2) # gain = random.randint(mingain, maxgain) #elif type == TYPE_STANDARD: # minute = self.__triangular(0,20+1,12) # mingain = max(int((15-minute)*3/2+1), 0) # maxgain = int((20-minute)*3/2) # gain = self.__triangular(mingain, maxgain, mingain) #color = random.choice(self.colors) self.extendlog(["Seeking %d %d" % (minute, gain)]) self.connection.glm.seek(minute, gain, True) opps = random.sample(self.connection.players.get_online_playernames(), self.challenges) self.extendlog("Challenging %s" % op for op in opps) for player in opps: self.connection.om.challenge(player, minute, gain, True) return True def makeReady(self): PyChess.makeReady(self) self.connection = FICSConnection("freechess.org",self.ports, self.username, self.password) self.connection.connect("connectingMsg", self.__showConnectLog) self.connection._connect() self.connection.glm.connect("addPlayer", self.__onAddPlayer) self.connection.glm.connect("removePlayer", self.__onRemovePlayer) self.connection.cm.connect("privateMessage", self.__onTell) self.connection.alm.connect("logOut", self.__onLogOut) self.connection.bm.connect("playGameCreated", self.__onGameCreated) self.connection.bm.connect("curGameEnded", self.__onGameEnded) self.connection.bm.connect("boardUpdate", self.__onBoardUpdate) self.connection.om.connect("onChallengeAdd", self.__onChallengeAdd) self.connection.om.connect("onOfferAdd", self.__onOfferAdd) self.connection.adm.connect("onAdjournmentsList", self.__onAdjournmentsList) self.connection.em.connect("onAmbiguousMove", self.__onAmbiguousMove) self.connection.em.connect("onIllegalMove", self.__onAmbiguousMove) self.connection.adm.queryAdjournments() self.connection.lvm.setVariable("autoflag", True) self.connection.fm.setFingerNote(1, "PyChess is the chess engine bundled with the PyChess %s " % pychess.VERSION + "chess client. This instance is owned by %s, but acts " % self.owner + "quite autonomously.") self.connection.fm.setFingerNote(2, "PyChess is 100% Python code and is released under the terms of " + "the GPL. The evalution function is largely equal to the one of" + "GnuChess, but it plays quite differently.") self.connection.fm.setFingerNote(3, "PyChess runs on an elderly AMD Sempron(tm) Processor 3200+, 512 " + "MB DDR2 Ram, but is built to take use of 64bit calculating when " + "accessible, through the gpm library.") self.connection.fm.setFingerNote(4, "PyChess uses a small 500 KB openingbook based solely on Kasparov " + "games. The engine doesn't have much endgame knowledge, but might " + "in some cases access an online endgamedatabase.") self.connection.fm.setFingerNote(5, "PyChess will allow any pause/resume and adjourn wishes, but will " + "deny takebacks. Draw, abort and switch offers are accepted, " + "if they are found to be an advance. Flag is auto called, but " + "PyChess never resigns. We don't want you to forget your basic " + "mating skills.") def run(self): self.connection.run() self.extendlog([str(self.acceptedTimesettings)]) self.phoneHome("Session ended\n"+"\n".join(self.log)) print "Session ended" #=========================================================================== # General #=========================================================================== def __showConnectLog (self, connection, message): print message def __onLogOut (self, autoLogoutManager): self.connection.close() #sys.exit() def __onAddPlayer (self, gameListManager, player): if player["name"] in self.sudos: self.sudos.remove(player["name"]) if player["name"] == self.owner: self.connection.cm.tellPlayer(self.owner, "Greetings") self.ownerOnline = True def __onRemovePlayer (self, gameListManager, playername): if playername == self.owner: self.ownerOnline = False def __onAdjournmentsList (self, adjournManager, adjournments): for adjournment in adjournments: if adjournment["online"]: adjournManager.challenge(adjournment["opponent"]) def __usage (self): return "|| PyChess bot help file || " +\ "# help 'Displays this help file' " +\ "# sudo <password> <command> 'Lets PyChess execute the given command' "+\ "# sendlog 'Makes PyChess send you its current log'" def __onTell (self, chatManager, name, title, isadmin, text): if self.waitingForPassword: if text.strip() == self.password or (not self.password and text == "none"): self.sudos.add(name) self.tellHome("%s gained sudo access" % name) print >> self.connection.client, self.waitingForPassword else: chatManager.tellPlayer(name, "Wrong password") self.tellHome("%s failed sudo access" % name) self.waitingForPassword = None return args = text.split() #if args == ["help"]: # chatManager.tellPlayer(name, self.__usage()) if args[0] == "sudo": command = " ".join(args[1:]) if name in self.sudos or name == self.owner: # Notice: This can be used to make nasty loops print >> self.connection.client, command else: print repr(name), self.sudos chatManager.tellPlayer(name, "Please send me the password") self.waitingForPassword = command elif args == ["sendlog"]: if self.log: # TODO: Consider email chatManager.tellPlayer(name, "\\n".join(self.log)) else: chatManager.tellPlayer(name, "The log is currently empty") else: if self.ownerOnline: self.tellHome("%s told me '%s'" % (name, text)) else: def onlineanswer (message): data = urlopen("http://www.pandorabots.com/pandora/talk?botid=8d034368fe360895", urlencode({"message":message, "botcust2":"x"})).read() ss = "<b>DMPGirl:</b>" es = "<br>" answer = data[data.find(ss)+len(ss) : data.find(es,data.find(ss))] chatManager.tellPlayer(name, answer) pool.start(onlineanswer, text) #chatManager.tellPlayer(name, "Sorry, your request was nonsense.\n"+\ # "Please read my help file for more info") #=========================================================================== # Challenges and other offers #=========================================================================== def __onChallengeAdd (self, offerManager, index, match): #match = {"tp": type, "w": fname, "rt": rating, "r": rated, "t": mins, "i": incr} offerManager.acceptIndex(index) def __onOfferAdd (self, offerManager, offer): if offer.type in (PAUSE_OFFER, RESUME_OFFER, ADJOURN_OFFER): offerManager.accept(offer) elif offer.type in (TAKEBACK_OFFER,): offerManager.decline(offer) elif offer.type in (DRAW_OFFER, ABORT_OFFER, SWITCH_OFFER): if self.scr <= 0: offerManager.accept(offer) else: offerManager.decline(offer) #=========================================================================== # Playing #=========================================================================== def __onGameCreated (self, boardManager, ficsgame): self.mytime = int(ficsgame.min)*60 self.increment = int(ficsgame.inc) self.gameno = ficsgame.gameno self.lastPly = -1 self.acceptedTimesettings.append((self.mytime, self.increment)) self.tellHome("Starting a game (%s, %s) gameno: %s" % (ficsgame.wplayer.name, ficsgame.bplayer.name, ficsgame.gameno)) if ficsgame.bplayer.name.lower() == self.connection.getUsername().lower(): self.playingAs = BLACK else: self.playingAs = WHITE self.board = LBoard(NORMALCHESS) # Now we wait until we recieve the board. def __go (self): if self.worker: self.worker.cancel() self.worker = GtkWorker(lambda worker: PyChess._PyChess__go(self, worker)) self.worker.connect("published", lambda w, msg: self.extendlog(msg)) self.worker.connect("done", self.__onMoveCalculated) self.worker.execute() def __onGameEnded (self, boardManager, ficsgame): self.tellHome(reprResult_long[ficsgame.result] + " " + reprReason_long[ficsgame.reason]) lsearch.searching = False if self.worker: self.worker.cancel() self.worker = None def __onMoveCalculated (self, worker, sanmove): if worker.isCancelled() or not sanmove: return self.board.applyMove(parseSAN(self.board,sanmove)) self.connection.bm.sendMove(sanmove) self.extendlog(["Move sent %s" % sanmove]) def __onBoardUpdate (self, boardManager, gameno, ply, curcol, lastmove, fen, wname, bname, wms, bms): self.extendlog(["","I got move %d %s for gameno %s" % (ply, lastmove, gameno)]) if self.gameno != gameno: return self.board.applyFen(fen) if self.playingAs == WHITE: self.mytime = wms/1000. else: self.mytime = bms/1000. if curcol == self.playingAs: self.__go() def __onAmbiguousMove (self, errorManager, move): # This is really a fix for fics, but sometimes it is necessary if determineAlgebraicNotation(move) == SAN: self.board.popMove() move_ = parseSAN(self.board, move) lanmove = toLAN(self.board, move_) self.board.applyMove(move_) self.connection.bm.sendMove(lanmove) else: self.connection.cm.tellOpponent( "I'm sorry, I wanted to move %s, but FICS called " % move + "it 'Ambigious'. I can't find another way to express it, " + "so you can win") self.connection.bm.resign() #=========================================================================== # Utils #=========================================================================== def extendlog(self, messages): [log.log(m+"\n") for m in messages] self.log.extend(messages) del self.log[:-10] def tellHome(self, message): print message if self.ownerOnline: self.connection.cm.tellPlayer(self.owner, message) def phoneHome(self, message): SENDMAIL = '/usr/sbin/sendmail' SUBJECT = "Besked fra botten" p = subprocess.Popen([SENDMAIL, '-f', email.Utils.parseaddr(self.from_address)[1], email.Utils.parseaddr(self.to_address)[1]], stdin=subprocess.PIPE) print >> p.stdin, "MIME-Version: 1.0" print >> p.stdin, "Content-Type: text/plain; charset=UTF-8" print >> p.stdin, "Content-Disposition: inline" print >> p.stdin, "From: %s" % self.from_address print >> p.stdin, "To: %s" % self.to_address print >> p.stdin, "Subject: %s" % SUBJECT print >> p.stdin print >> p.stdin, message print >> p.stdin, "Cheers" p.stdin.close() p.wait() ################################################################################ # main # ################################################################################ if __name__ == "__main__": if len(sys.argv) == 1 or sys.argv[1:] == ["xboard"]: pychess = PyChessCECP() elif len(sys.argv) == 5 and sys.argv[1] == "fics": pychess = PyChessFICS(*sys.argv[2:]) signal.signal(signal.SIGINT, gtk.main_quit) if isInstalled(): gettext.install("pychess", unicode=1) gtk.glade.bindtextdomain("pychess") else: gettext.install("pychess", localedir=addDataPrefix("lang"), unicode=1) gtk.glade.bindtextdomain("pychess", addDataPrefix("lang")) gtk.glade.textdomain("pychess") # Start logging log.debug("Started\n") LogDialog.show() else: print "Unknown argument(s):", repr(sys.argv) sys.exit(0) pychess.makeReady() if len(sys.argv) == 5 and sys.argv[1] == "fics": from pychess.System.ThreadPool import pool pool.start(pychess.run) gtk.gdk.threads_init() gtk.main() else: pychess.run()
Python
from gobject import GObject, SIGNAL_RUN_FIRST, TYPE_NONE class PlayerIsDead (Exception): """ Used instead of returning a move, when an engine crashes, or a nonlocal player disconnects """ pass class TurnInterrupt (Exception): """ Used instead of returning a move, when a players turn is interrupted. Currently this will only happen when undoMoves changes the current player """ pass class Player (GObject): __gsignals__ = { "offer": (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)), "withdraw": (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)), "decline": (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)), "accept": (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)), "name_changed": (SIGNAL_RUN_FIRST, TYPE_NONE, ()), } def __init__ (self): GObject.__init__(self) self.name = "" self.ichandle = None self.icrating = None def setName (self, name): """ __repr__ should return this name """ self.name = name self.emit("name_changed") def __repr__ (self): return self.name #=========================================================================== # Starting the game #=========================================================================== def prestart (self): pass # Optional def start (self): pass # Optional def setOptionInitialBoard (self, model): pass # Optional. Further defined in Engine.py #=========================================================================== # Ending the game #=========================================================================== def end (self, status, reason): """ Called when the game ends in a normal way. Use this for shutting down engines etc. """ raise NotImplementedError def kill (self, reason): """ Called when game has too die fast and ugly. Mostly used in case of errors and stuff. Use for closing connections etc. """ raise NotImplementedError #=========================================================================== # Send the player move updates #=========================================================================== def makeMove (self, board1, move, board2): """ Takes a board object, and if ply>lowply the latest move object and second latest board object as well. Otherwise these two are None. Retruns: A new move object, witch the player wants to do. """ raise NotImplementedError def putMove (self, board1, move, board2): """ Like makeMove, but doesn't block and doesn't return anything. putMove is only used when the player is spectatctor to a game """ #Optional def updateTime (self, secs, opsecs): """ Updates the player with the current remaining time as a float of seconds """ #Optional #=========================================================================== # Interacting with the player #=========================================================================== def pause (self): """ Should stop the player from thinking until resume is called """ raise NotImplementedError def resume (self): """ Should resume player to think if he's paused """ raise NotImplementedError def hurry (self): """ Forces engines to move now, and sends a hurry message to nonlocal human players """ #Optional def undoMoves (self, moves, gamemodel): """ Undo 'moves' moves and makes the latest board in gamemodel the current """ #Optional def playerUndoMoves (self, moves, gamemodel): """ Some players undo different depending on whether they are players or spectators. This is a convenient way to handle that. """ #Optional return self.undoMoves (moves, gamemodel) def spectatorUndoMoves (self, moves, gamemodel): """ Some players undo different depending on whether they are players or spectators. This is a convenient way to handle that. """ #Optional return self.undoMoves (moves, gamemodel) def putMessage (self, message): """ Sends the player a chatmessage """ #Optional #=========================================================================== # Offer handling #=========================================================================== def offer (self, offer): """ The players opponent has offered the player offer. If the player accepts, it should respond by mirroring the offer with emit("accept", offer). If it should either ignore the offer or emit "decline".""" raise NotImplementedError def offerDeclined (self, offer): """ An offer sent by the player was responded negative by the opponent """ #Optional def offerWithdrawn (self, offer): """ An offer earlier offered to the player has been withdrawn """ #Optional def offerError (self, offer, error): """ An offer, accept or action made by the player has been refused by the game model. """ #Optional
Python
from urllib import urlopen, urlencode from gobject import SIGNAL_RUN_FIRST, TYPE_NONE from pychess.System.ThreadPool import pool from pychess.System.Log import log from pychess.Utils.Offer import Offer from pychess.Utils.const import ARTIFICIAL, CHAT_ACTION from Player import Player class Engine (Player): __type__ = ARTIFICIAL ''' The first argument is the pv list of moves. The second is a score relative to the engine. If no score is known, the value can be None, but not 0, which is a draw. ''' __gsignals__ = { 'analyze': (SIGNAL_RUN_FIRST, TYPE_NONE, (object,object)) } def __init__(self): Player.__init__(self) self.currentAnalysis = [] def on_analysis(self_, analysis, score): if score != None: self.currentScore = score self.currentAnalysis = analysis self.connect('analyze', on_analysis) #=========================================================================== # Offer handling #=========================================================================== def offer (self, offer): raise NotImplementedError def offerDeclined (self, offer): pass #Ignore def offerWithdrawn (self, offer): pass #Ignore def offerError (self, offer, error): pass #Ignore #=========================================================================== # General Engine Options #=========================================================================== def setOptionAnalyzing (self, mode): self.mode = mode def setOptionInitialBoard (self, model): """ If the game starts at a board other than FEN_START, it should be sent here. We sends a gamemodel, so the engine can load the entire list of moves, if any """ pass # Optional def setOptionVariant (self, variant): """ Inform the engine of any special variant. If the engine doesn't understand the variant, this will raise an error. """ raise NotImplementedError def setOptionTime (self, secs, gain): """ Seconds is the initial clock of the game. Gain is the amount of seconds a player gets after each move. If the engine doesn't support playing with time, this will fail.""" raise NotImplementedError def setOptionStrength (self, strength): """ Strength is a number [1,8] inclusive. Higher is better. """ self.strength = strength raise NotImplementedError #=========================================================================== # Engine specific methods #=========================================================================== def canAnalyze (self): raise NotImplementedError def getAnalysis (self): """ Returns a list of moves, or None if there haven't yet been made an analysis """ return self.currentAnalysis #=========================================================================== # General chat handling #=========================================================================== def putMessage (self, message): def answer (message): try: data = urlopen("http://www.pandorabots.com/pandora/talk?botid=8d034368fe360895", urlencode({"message":message, "botcust2":"x"})).read() except IOError, e: log.warn("Couldn't answer message from online bot: '%s'\n" % e, self.defname) return ss = "<b>DMPGirl:</b>" es = "<br>" answer = data[data.find(ss)+len(ss) : data.find(es,data.find(ss))] self.emit("offer", Offer(CHAT_ACTION, answer)) pool.start(answer, message)
Python
from __future__ import with_statement import os import sys from hashlib import md5 from threading import Thread from os.path import join, dirname, abspath from copy import deepcopy import xml.etree.ElementTree as ET from xml.etree.ElementTree import fromstring try: from xml.etree.ElementTree import ParseError except ImportError: from xml.parsers.expat import ExpatError as ParseError from gobject import GObject, SIGNAL_RUN_FIRST, TYPE_NONE from pychess.System.Log import log from pychess.System.SubProcess import SubProcess, searchPath, SubProcessError from pychess.System.prefix import addUserConfigPrefix, getEngineDataPrefix from pychess.System.ThreadPool import pool, PooledThread from pychess.Players.Player import PlayerIsDead from pychess.Utils.const import * from CECPEngine import CECPEngine from UCIEngine import UCIEngine from pychess.Variants import variants attrToProtocol = { "uci": UCIEngine, "cecp": CECPEngine } def compareVersions(ver1, ver2): ''' Returns -1 if ver1 < ver2; 0 if ver1 == ver2; 1 if ver1 > ver2 ''' parts1 = map(int, ver1.split('.')) parts2 = map(int, ver2.split('.')) for part1, part2 in zip(parts1, parts2): if part1 != part2: return cmp(part1, part2) return cmp(len(parts1),len(parts2)) def mergeElements(elemA, elemB): """ Recursively merge two xml-elements into the first. If both elements contain the same child, the text will be taken form elemA. <A><B name='t'>text1</B><C>text2</C></A> + <A><B name='u'>text3</B><C>text4</C></A> = <A><B name='u'>text3</B><B name='t'>text1</B><C>text2</C></A> Merges some attributes*.""" elemA.attrib.update(elemB.attrib) childrenA = dict(((c.tag,c.get('name')),c) for c in elemA.getchildren()) for child in elemB.getchildren(): tag = (child.tag,child.get('name')) if not tag in childrenA: elemA.append(deepcopy(child)) else: mergeElements(childrenA[tag], child) #<engine protocol='cecp' protover='2' binname='PyChess.py'> # <path>/usr/bin/gnuchess</path> # <md5>bee39e0ac125b46a8ce0840507dde50e</md5> # <vm> # <path>/use/bin/python</path> # <md5>lksjdflkajdflk</md5> # </vm> #</engine> backup = """ <engines version="%s"> <engine protocol="cecp" protover="2" binname="PyChess.py"> <meta><country>dk</country></meta> <vm binname="python"><args><arg name='0' value="-u"/></args></vm></engine> <engine protocol="cecp" protover="2" binname="shatranj.py"> <vm binname="python"><args><arg name='0' value="-u"/></args></vm> <args><arg name='0' value='-xboard'/></args></engine> <engine protocol="cecp" protover="2" binname="gnuchess"> <meta><country>us</country></meta> <cecp-features><feature name="sigint" value="1"/></cecp-features> </engine> <engine protocol="cecp" protover="2" binname="gnome-gnuchess"> <meta><country>us</country></meta> <cecp-features><feature name="sigint" value="1"/></cecp-features> </engine> <engine protocol="cecp" protover="2" binname="crafty"> <meta><country>us</country></meta></engine> <engine protocol="cecp" protover="1" binname="faile"> <meta><country>ca</country></meta></engine> <engine protocol="cecp" protover="1" binname="phalanx"> <meta><country>cz</country></meta></engine> <engine protocol="cecp" protover="2" binname="sjeng"> <meta><country>be</country></meta></engine> <engine protocol="cecp" protover="2" binname="hoichess"> <meta><country>de</country></meta></engine> <engine protocol="cecp" protover="1" binname="boochess"> <meta><country>de</country></meta></engine> <engine protocol="cecp" protover="2" binname="amy"> <meta><country>de</country><author>Thorsten Greiner</author></meta></engine> <engine protocol="cecp" protover="1" binname="amundsen"> <meta><country>sw</country><author>John Bergbom</author></meta></engine> <engine protocol="uci" protover="1" binname="robbolito"> <meta><country>ru</country></meta></engine> <engine protocol="uci" protover="1" binname="glaurung"> <meta><country>no</country></meta></engine> <engine protocol="uci" protover="1" binname="stockfish"> <meta><country>no</country></meta></engine> <engine protocol="uci" protover="1" binname="ShredderClassicLinux"> <meta><country>de</country></meta></engine> <engine protocol="uci" protover="1" binname="fruit_21_static"> <meta><country>fr</country></meta></engine> <engine protocol="uci" protover="1" binname="fruit"> <meta><country>fr</country></meta></engine> <engine protocol="uci" protover="1" binname="toga2"> <meta><country>de</country></meta></engine> <engine protocol="uci" protover="1" binname="hiarcs"> <meta><country>gb</country></meta></engine> <engine protocol="uci" protover="1" binname="diablo"> <meta><country>us</country><author>Marcus Predaski</author></meta></engine> <engine protocol="uci" protover="1" binname="Houdini.exe"> <meta><country>be</country></meta> <vm binname="wine"/></engine> <engine protocol="uci" protover="1" binname="Rybka.exe"> <meta><country>ru</country></meta> <vm binname="wine"/></engine> </engines> """ % ENGINES_XML_API_VERSION class EngineDiscoverer (GObject, PooledThread): __gsignals__ = { "discovering_started": (SIGNAL_RUN_FIRST, TYPE_NONE, (object,)), "engine_discovered": (SIGNAL_RUN_FIRST, TYPE_NONE, (str, object)), "engine_failed": (SIGNAL_RUN_FIRST, TYPE_NONE, (str, object)), "all_engines_discovered": (SIGNAL_RUN_FIRST, TYPE_NONE, ()), } def __init__ (self): GObject.__init__(self) self.backup = ET.ElementTree(fromstring(backup)) self.xmlpath = addUserConfigPrefix("engines.xml") try: self.dom = ET.ElementTree(file=self.xmlpath) c = compareVersions(self.dom.getroot().get('version', default='0'), ENGINES_XML_API_VERSION) if c == -1: log.warn("engineNest: engines.xml is outdated. It will be replaced\n") self.dom = deepcopy(self.backup) elif c == 1: raise NotImplementedError, "engines.xml is of a newer date. In order" + \ "to run this version of PyChess it must first be removed" except ParseError, e: log.warn("engineNest: %s\n" % e) self.dom = deepcopy(self.backup) except IOError, e: log.log("engineNest: Couldn\'t open engines.xml. Creating a new.\n%s\n" % e) self.dom = deepcopy(self.backup) self._engines = {} ############################################################################ # Discover methods # ############################################################################ def __findRundata (self, engine): """ Searches for a readable, executable named 'binname' in the PATH. For the PyChess engine, special handling is taken, and we search PYTHONPATH as well as the directory from where the 'os' module is imported """ if engine.find('vm') is not None: altpath = engine.find('vm').find('path') is not None and \ engine.find('vm').find('path').text.strip() vmpath = searchPath(engine.find('vm').get('binname'), access=os.R_OK|os.X_OK, altpath = altpath) if engine.get('binname') == "PyChess.py": path = join(abspath(dirname(__file__)), "PyChess.py") if not os.access(path, os.R_OK): path = None else: altpath = engine.find('path') is not None and engine.find('path').text.strip() path = searchPath(engine.get('binname'), access=os.R_OK, altpath=altpath) if vmpath and path: return vmpath, path else: altpath = engine.find('path') is not None and engine.find('path').text.strip() path = searchPath(engine.get('binname'), access=os.R_OK|os.X_OK, altpath=altpath) if path: return None, path return False def __fromUCIProcess (self, subprocess): ids = subprocess.ids options = subprocess.options engine = fromstring('<engine><meta/><options/></engine>') meta = engine.find('meta') if "name" in ids: meta.append(fromstring('<name>%s</name>' % ids['name'])) if 'author' in ids: meta.append(fromstring('<author>%s</author>' % ids['author'])) optnode = engine.find('options') for name, dic in options.iteritems(): option = fromstring('<%s-option name="%s"/>' % (dic.pop('type'), name)) optnode.append(option) for key, value in dic.iteritems(): if key == 'vars': for valueoption in value: option.append(fromstring('<var name="%s" />' % valueoption)) else: option.attrib[key] = str(value) return engine def __fromCECPProcess (self, subprocess): features = subprocess.features engine = fromstring('<engine><meta/><cecp-features/><options/></engine>') meta = engine.find('meta') if "name" in features: meta.append(fromstring('<name>%s</name>' % features['myname'])) feanode = engine.find('cecp-features') for key, value in features.iteritems(): feanode.append(fromstring('<feature name="%s" value="%s"/>' % (key, value))) optnode = engine.find('options') optnode.append(fromstring('<check-option name="Ponder" default="false"/>')) optnode.append(fromstring('<check-option name="Random" default="false"/>')) optnode.append(fromstring('<spin-option name="Depth" min="1" max="-1" default="false"/>')) return engine def __discoverE (self, engine): subproc = self.initEngine (engine, BLACK) try: subproc.connect('readyForOptions', self.__discoverE2, engine) subproc.prestart() # Sends the 'start line' subproc.start() except SubProcessError, e: log.warn("Engine %s failed discovery: %s" % (engine.get('binname'),e)) self.emit("engine_failed", engine.get('binname'), engine) except PlayerIsDead, e: # Check if the player died after engine_discovered by our own hands if not self.toBeRechecked[engine]: log.warn("Engine %s failed discovery: %s" % (engine.get('binname'),e)) self.emit("engine_failed", engine.get('binname'), engine) def __discoverE2 (self, subproc, engine): if engine.get("protocol") == "uci": fresh = self.__fromUCIProcess(subproc) elif engine.get("protocol") == "cecp": fresh = self.__fromCECPProcess(subproc) mergeElements(engine, fresh) exitcode = subproc.kill(UNKNOWN_REASON) if exitcode: log.debug("Engine failed %s\n" % self.getName(engine)) self.emit("engine_failed", engine.get('binname'), engine) return engine.set('recheck', 'false') log.debug("Engine finished %s\n" % self.getName(engine)) self.emit ("engine_discovered", engine.get('binname'), engine) ############################################################################ # Main loop # ############################################################################ def __needClean(self, rundata, engine): """ Check if the filename or md5sum of the engine has changed. In that case we need to clean the engine """ vmpath, path = rundata # Check if filename is not set, or if it has changed if engine.find("path") is None or engine.find("path").text != path: return True # If the engine failed last time, we'll recheck it as well if engine.get('recheck') == "true": return True # Check if md5sum is not set, or if it has changed if engine.find("md5") is None: return True with open(path) as f: md5sum = md5(f.read()).hexdigest() if engine.find("md5").text != md5sum: return True return False def __clean(self, rundata, engine): """ Grab the engine from the backup and attach the attributes from rundata. The 'new' engine is returned and ready for discovering. If engine doesn't exist in backup, an 'unsupported engine' warning is logged, and a new engine element is created for it """ vmpath, path = rundata with open(path) as f: md5sum = md5(f.read()).hexdigest() ###### # Find the backup engine ###### try: engine2 = (c for c in self.backup.findall('engine') if c.get('binname') == engine.get('binname')).next() except StopIteration: log.warn("Engine '%s' has not been tested and verified to work with PyChess\n" % \ engine.get('binname')) engine2 = fromstring('<engine></engine>') engine2.set('binname', engine.get('binname')) engine2.set('protocol', engine.get('protocol')) if engine.get('protover'): engine2.set('protover', engine.get('protover')) engine2.set('recheck', 'true') # This doesn't work either. Dammit python # engine = any(c for c in self.backup.getchildren() # if c.get('binname') == engine.get('binname')) # Waiting for etree 1.3 to get into python, before we can use xpath # engine = self.backup.find('engine[@binname="%s"]' % engine.get('binname')) ###### # Clean it ###### engine2.append(fromstring('<path>%s</path>' % path)) engine2.append(fromstring('<md5>%s</md5>' % md5sum)) engine2.append(fromstring('<args/>')) if vmpath: vmbn = engine.find('vm').get('binname') engine2.append(fromstring('<vm binname="%s"/>' % vmbn)) engine2.find('vm').append(fromstring('<path>%s</path>' % vmpath)) engine2.find('vm').append(fromstring('<args/>')) return engine2 def run (self): # List available engines for engine in self.dom.findall('engine'): ###### # Find the known and installed engines on the system ###### # Validate slightly if not engine.get("protocol") or not engine.get("binname"): log.warn("Engine '%s' lacks protocol/binname attributes. Skipping\n" % \ engine.get('binname')) continue # Look up rundata = self.__findRundata(engine) if not rundata: # Engine is not available on the system continue if self.__needClean(rundata, engine): engine2 = self.__clean(rundata, engine) if engine2 is None: # No longer suported continue self.dom.getroot().remove(engine) self.dom.getroot().append(engine2) engine = engine2 engine.set('recheck', 'true') self._engines[engine.get("binname")] = engine ###### # Save the xml ###### def cb(self_, *args): try: with open(self.xmlpath, "w") as f: self.dom.write(f) except IOError, e: log.error("Saving enginexml raised exception: %s\n" % \ ", ".join(str(a) for a in e.args)) ###### # Runs all the engines in toBeRechecked, in order to gather information ###### self.toBeRechecked = dict((c,False) for c in self.dom.findall('engine') if c.get('recheck') == 'true') # Waiting for etree 1.3 to get into python, before we can use xpath # toBeRechecked = self.dom.findall('engine[recheck=true]') def count(self_, binname, engine, wentwell): if wentwell: self.toBeRechecked[engine] = True if all(self.toBeRechecked.values()): self.emit("all_engines_discovered") self.connect("engine_discovered", count, True) self.connect("engine_failed", count, False) if self.toBeRechecked: binnames = [engine.get('binname') for engine in self.toBeRechecked.keys()] self.emit("discovering_started", binnames) self.connect("all_engines_discovered", cb) for engine in self.toBeRechecked.keys(): self.__discoverE(engine) else: self.emit('all_engines_discovered') ############################################################################ # Interaction # ############################################################################ def getAnalyzers (self): for engine in self.getEngines().values(): protocol = engine.get("protocol") if protocol == "uci": yield engine elif protocol == "cecp": if any(True for f in engine.findall('cecp-features/feature') if f.get('name') == 'analyze' and f.get('value') == '1'): yield engine def getEngines (self): """ Returns {binname: enginexml} """ return self._engines def getEngineN (self, index): return self.getEngines()[self.getEngines().keys()[index]] def getEngineByMd5 (self, md5sum, list=[]): if not list: list = self.getEngines().values() for engine in list: md5 = engine.find('md5') if md5 is None: continue if md5.text.strip() == md5sum: return engine def getEngineVariants (self, engine): for variantClass in variants.values(): if variantClass.standard_rules: yield variantClass.board.variant else: for feature in engine.findall("cecp-features/feature"): if feature.get("name") == "variants": if variantClass.cecp_name in feature.get('value'): yield variantClass.board.variant # UCI knows Chess960 only if variantClass.cecp_name == "fischerandom": for option in engine.findall('options/check-option'): if option.get("name") == "UCI_Chess960": yield variantClass.board.variant def getName (self, engine=None): # Test if the call was to get the name of the thread if engine is None: return Thread.getName(self) nametag = engine.find("meta/name") if nametag is not None: return nametag.text.strip() return engine.get('binname') def getCountry (self, engine): country = engine.find('meta/country') if country is not None: return country.text.strip() return None def initEngine (self, xmlengine, color): protover = int(xmlengine.get("protover")) protocol = xmlengine.get("protocol") path = xmlengine.find('path').text.strip() args = [a.get('value') for a in xmlengine.findall('args/arg')] if xmlengine.find('vm') is not None: vmpath = xmlengine.find('vm/path').text.strip() vmargs = [a.get('value') for a in xmlengine.findall('vm/args/arg')] args = vmargs+[path]+args path = vmpath warnwords = ("illegal", "error", "exception") subprocess = SubProcess(path, args, warnwords, SUBPROCESS_SUBPROCESS, getEngineDataPrefix()) engine = attrToProtocol[protocol](subprocess, color, protover) if protocol == "uci": # If the user has configured special options for this engine, here is # where they should be set. def optionsCallback (engine): if engine.hasOption("OwnBook"): engine.setOption("OwnBook", True) engine.connect("readyForOptions", optionsCallback) return engine def initPlayerEngine (self, xmlengine, color, diffi, variant, secs=0, incr=0): engine = self.initEngine (xmlengine, color) def optionsCallback (engine): engine.setOptionStrength(diffi) engine.setOptionVariant(variant) if secs > 0: engine.setOptionTime(secs, incr) engine.connect("readyForOptions", optionsCallback) engine.prestart() return engine def initAnalyzerEngine (self, xmlengine, mode, variant): engine = self.initEngine (xmlengine, WHITE) def optionsCallback (engine): engine.setOptionAnalyzing(mode) engine.setOptionVariant(variant) engine.connect("readyForOptions", optionsCallback) engine.prestart() return engine discoverer = EngineDiscoverer() if __name__ == "__main__": import glib, gobject gobject.threads_init() mainloop = glib.MainLoop() # discoverer = EngineDiscoverer() def discovering_started (discoverer, binnames): print "discovering_started", binnames discoverer.connect("discovering_started", discovering_started) def engine_discovered (discoverer, binname, engine): sys.stdout.write(".") discoverer.connect("engine_discovered", engine_discovered) def all_engines_discovered (discoverer): print "all_engines_discovered" print discoverer.getEngines().keys() mainloop.quit() discoverer.connect("all_engines_discovered", all_engines_discovered) discoverer.start() mainloop.run()
Python
from threading import RLock import Queue import itertools import re import time from pychess.Savers.pgn import movre as movere from pychess.System.Log import log from pychess.System.ThreadPool import pool from pychess.Utils.Move import Move from pychess.Utils.Board import Board from pychess.Utils.Cord import Cord from pychess.Utils.Move import toSAN, toAN, parseAny, listToMoves from pychess.Utils.Offer import Offer from pychess.Utils.const import * from pychess.Utils.logic import validate, getMoveKillingKing from pychess.Utils.lutils.ldata import MATE_VALUE from pychess.Utils.lutils.lmove import ParsingError from pychess.Variants import variants from Player import PlayerIsDead, TurnInterrupt from ProtocolEngine import ProtocolEngine def isdigits (strings): for s in strings: s = s.replace(".","") if s.startswith("-"): if not s[1:].isdigit(): return False else: if not s.isdigit(): return False return True d_plus_dot_expr = re.compile(r"\d+\.") anare = re.compile(""" ^ # beginning of string \s* # \d+ [+\-\.]? # The ply analyzed. Some engines end it with a dot, minus or plus \s+ # (-?Mat\s*\d+ | [-\d\.]+) # Mat1 is used by gnuchess to specify mate in one. # otherwise we should support a signed float \s+ # [\d\.]+ # The time used in seconds \s+ # [\d\.]+ # The score found in centipawns \s+ # (.+) # The Principal-Variation. With or without move numbers \s* # $ # end of string """, re.VERBOSE) #anare = re.compile("\d+\.?\s+ (Mat\d+|[-\d\.]+) \s+ \d+\s+\d+\s+((?:%s\s*)+)" % mov) whitespaces = re.compile(r"\s+") def semisynced(f): """ All moveSynced methods will be queued up, and called in the right order after self.readyMoves is true """ def newFunction(*args, **kw): self = args[0] self.funcQueue.put((f, args, kw)) if self.readyMoves: self.boardLock.acquire() try: while True: try: func_, args_, kw_ = self.funcQueue.get_nowait() func_(*args_, **kw_) except TypeError, e: print "TypeError: %s" % repr(args) raise except Queue.Empty: break finally: self.boardLock.release() return newFunction # There is no way in the CECP protocol to determine if an engine not answering # the protover=2 handshake with done=1 is old or just very slow. Thus we # need a timeout after which we conclude the engine is 'protover=1' and will # never answer. # XBoard will only give 2 seconds, but as we are quite sure that # the engines support the protocol, we can add more. We don't add # infinite time though, just in case. # The engine can get more time by sending done=0 TIME_OUT_FIRST = 10 # The amount of seconds to add for the second timeout TIME_OUT_SECOND = 15 class CECPEngine (ProtocolEngine): def __init__ (self, subprocess, color, protover): ProtocolEngine.__init__(self, subprocess, color, protover) self.features = { "ping": 0, "setboard": 0, "playother": 0, "san": 0, "usermove": 0, "time": 1, "draw": 1, "sigint": 0, "sigterm": 0, "reuse": 0, "analyze": 0, "myname": ', '.join(self.defname), "variants": None, "colors": 1, "ics": 0, "name": 0, "pause": 0, "nps": 0, "debug": 0, "memory": 0, "smp": 0, "egt": '', } self.supported_features = [ "ping", "setboard", "san", "usermove", "time", "draw", "sigint", "analyze", "myname", "variants", "colors", "pause", "done" ] self.name = None self.board = None # if self.engineIsInNotPlaying == True, engine is in "force" mode, # i.e. not thinking or playing, but still verifying move legality self.engineIsInNotPlaying = False self.movenext = False self.waitingForMove = False self.readyForMoveNowCommand = False self.timeHandicap = 1 self.lastping = 0 self.lastpong = 0 self.timeout = None self.returnQueue = Queue.Queue() self.engine.connect("line", self.parseLines) self.engine.connect("died", lambda e: self.returnQueue.put("del")) self.funcQueue = Queue.Queue() self.optionQueue = [] self.boardLock = RLock() self.undoQueue = [] self.connect("readyForOptions", self.__onReadyForOptions_before) self.connect_after("readyForOptions", self.__onReadyForOptions) self.connect_after("readyForMoves", self.__onReadyForMoves) #=========================================================================== # Starting the game #=========================================================================== def prestart (self): print >> self.engine, "xboard" if self.protover == 1: self.emit("readyForOptions") elif self.protover == 2: print >> self.engine, "protover 2" self.timeout = time.time() + TIME_OUT_FIRST def start (self): if self.mode in (ANALYZING, INVERSE_ANALYZING): pool.start(self.__startBlocking) else: self.__startBlocking() def __startBlocking (self): if self.protover == 1: self.emit("readyForMoves") if self.protover == 2: try: r = self.returnQueue.get(True, max(self.timeout-time.time(),0)) if r == "not ready": # The engine has sent done=0, and parseLine has added more # time to self.timeout r = self.returnQueue.get(True, max(self.timeout-time.time(),0)) except Queue.Empty: log.warn("Got timeout error\n", self.defname) self.emit("readyForOptions") self.emit("readyForMoves") else: if r == 'del': raise PlayerIsDead assert r == "ready" def __onReadyForOptions_before (self, self_): self.readyOptions = True def __onReadyForOptions (self, self_): # This is no longer needed #self.timeout = time.time() # Some engines has the 'post' option enabled by default, and posts a lot # of debug information. Generelly this only help to increase the log # file size, and we don't really need it. print >> self.engine, "nopost" for command in self.optionQueue: print >> self.engine, command def __onReadyForMoves (self, self_): # If we are an analyzer, this signal was already called in a different # thread, so we can safely block it. if self.mode in (ANALYZING, INVERSE_ANALYZING): if not self.board: self.board = Board(setup=True) self.__sendAnalyze(self.mode == INVERSE_ANALYZING) self.readyMoves = True semisynced(lambda s:None)(self) #=========================================================================== # Ending the game #=========================================================================== @semisynced def end (self, status, reason): if self.connected: # We currently can't fillout the comment "field" as the repr strings # for reasons and statuses lies in Main.py # Creating Status and Reason class would solve this if status == DRAW: print >> self.engine, "result 1/2-1/2 {?}" elif status == WHITEWON: print >> self.engine, "result 1-0 {?}" elif status == BLACKWON: print >> self.engine, "result 0-1 {?}" else: print >> self.engine, "result * {?}" # Make sure the engine exits and do some cleaning self.kill(reason) def kill (self, reason): """ Kills the engine, starting with the 'quit' command, then sigterm and eventually sigkill. Returns the exitcode, or if engine have already been killed, returns None """ if self.connected: self.connected = False try: try: print >> self.engine, "quit" self.returnQueue.put("del") self.engine.gentleKill() except OSError, e: # No need to raise on a hang up error, as the engine is dead # anyways if e.errno == 32: log.warn("Hung up Error", self.defname) return e.errno else: raise finally: # Clear the analyzed data, if any self.emit("analyze", [], None) #=========================================================================== # Send the player move updates #=========================================================================== @semisynced def putMove (self, board1, move, board2): """ Sends the engine the last move made (for spectator engines). @param board1: The current board @param move: The last move made @param board2: The board before the last move was made """ self.board = board1 if not board2: self.__tellEngineToPlayCurrentColorAndMakeMove() self.movenext = False return if self.mode == INVERSE_ANALYZING: self.board = self.board.switchColor() self.__printColor() if self.engineIsInNotPlaying: print >> self.engine, "force" self.__usermove(board2, move) if self.mode == INVERSE_ANALYZING: if self.board.board.opIsChecked(): # Many engines don't like positions able to take down enemy # king. Therefore we just return the "kill king" move # automaticaly self.emit("analyze", [getMoveKillingKing(self.board)], MATE_VALUE-1) return self.__printColor() if self.engineIsInNotPlaying: print >> self.engine, "force" def makeMove (self, board1, move, board2): """ Gets a move from the engine (for player engines). @param board1: The current board @param move: The last move made @param board2: The board before the last move was made @return: The move the engine decided to make """ log.debug("makeMove: move=%s self.movenext=%s board1=%s board2=%s self.board=%s\n" % \ (move, self.movenext, board1, board2, self.board), self.defname) assert self.readyMoves self.boardLock.acquire() try: if self.board == board1 or not board2 or self.movenext: self.board = board1 self.__tellEngineToPlayCurrentColorAndMakeMove() self.movenext = False else: self.board = board1 self.__usermove(board2, move) if self.engineIsInNotPlaying: self.__tellEngineToPlayCurrentColorAndMakeMove() finally: self.boardLock.release() self.waitingForMove = True self.readyForMoveNowCommand = True # Parse outputs r = self.returnQueue.get() if r == "not ready": log.warn("Engine seems to be protover=2, but is treated as protover=1", self.defname) r = self.returnQueue.get() if r == "ready": r = self.returnQueue.get() if r == "del": raise PlayerIsDead, "Killed by foreign forces" if r == "int": raise TurnInterrupt self.waitingForMove = False self.readyForMoveNowCommand = False assert isinstance(r, Move), r return r @semisynced def updateTime (self, secs, opsecs): if self.features["time"]: print >> self.engine, "time", int(secs*100*self.timeHandicap) print >> self.engine, "otim", int(opsecs*100) #=========================================================================== # Standard options #=========================================================================== def setOptionAnalyzing (self, mode): self.mode = mode def setOptionInitialBoard (self, model): # We don't use the optionQueue here, as set board prints a whole lot of # stuff. Instead we just call it, and let semisynced handle the rest. self.setBoard(model.boards[:], model.moves[:]) @semisynced def setBoard (self, boards, moves): # Notice: If this method is to be called while playing, the engine will # need 'new' and an arrangement similar to that of 'pause' to avoid # the current thought move to appear self.boardLock.acquire() try: if self.mode == INVERSE_ANALYZING: self.board = self.board.switchColor() self.__printColor() self.__tellEngineToStopPlayingCurrentColor() if boards[0].asFen() != FEN_START: self.__setBoard(boards[0]) self.board = boards[-1] for board, move in zip(boards[:-1], moves): self.__usermove(board, move) if self.mode in (ANALYZING, INVERSE_ANALYZING): self.board = boards[-1] if self.mode == INVERSE_ANALYZING: self.board = self.board.switchColor() self.__printColor() if self.engineIsInNotPlaying: print >> self.engine, "force" # The called of setBoard will have to repost/analyze the # analyzer engines at this point. finally: self.boardLock.release() def setOptionVariant (self, variant): if self.features["variants"] is None: log.warn("setOptionVariant: engine doesn't support variants\n", self.defname) return if variant in variants.values() and not variant.standard_rules: assert variant.cecp_name in self.features["variants"], \ "%s doesn't support %s variant" % (self, variant.cecp_name) self.optionQueue.append("variant %s" % variant.cecp_name) #==================================================# # Strength system # #==================================================# # Strength Depth Ponder Time handicap # # Easy 1 1 o o # # 2 2 o o # # 3 3 o o # # Semi 4 5 o 10,00% # # 5 7 o 20,00% # # 6 9 o 40,00% # # Hard 7 o x 80,00% # # 8 o x o # #==================================================# def setOptionStrength (self, strength): self.strength = strength if 4 <= strength <= 7: self.__setTimeHandicap(0.1 * 2**(strength-4)) if strength <= 3: self.__setDepth(strength) elif strength <= 6: self.__setDepth(5+(strength-4)*2) self.__setPonder(strength >= 7) if strength == 8: self.optionQueue.append("egtb") else: self.optionQueue.append("random") def __setDepth (self, depth): self.optionQueue.append("sd %d" % depth) def __setTimeHandicap (self, timeHandicap): self.timeHandicap = timeHandicap def __setPonder (self, ponder): if ponder: self.optionQueue.append("hard") else: self.optionQueue.append("hard") self.optionQueue.append("easy") def setOptionTime (self, secs, gain): # Notice: In CECP we apply time handicap in updateTime, not in # setOptionTime. minutes = int(secs / 60) secs = int(secs % 60) s = str(minutes) if secs: s += ":" + str(secs) self.optionQueue.append("level 0 %s %d" % (s, gain)) #=========================================================================== # Interacting with the player #=========================================================================== @semisynced def pause (self): """ Pauses engine using the "pause" command if available. Otherwise put engine in force mode. By the specs the engine shouldn't ponder in force mode, but some of them do so anyways. """ self.engine.pause() return if self.mode in (ANALYZING, INVERSE_ANALYZING): return if self.features["pause"]: print >> self.engine, "pause" elif self.board: self.__tellEngineToStopPlayingCurrentColor() self._blockTillMove() @semisynced def resume (self): self.engine.resume() return if self.mode not in (ANALYZING, INVERSE_ANALYZING): if self.features["pause"]: print "features resume" print >> self.engine, "resume" elif self.board: print "go resume" self.__tellEngineToPlayCurrentColorAndMakeMove() @semisynced def hurry (self): log.debug("hurry: self.waitingForMove=%s self.readyForMoveNowCommand=%s\n" % \ (self.waitingForMove, self.readyForMoveNowCommand), self.defname) if self.waitingForMove and self.readyForMoveNowCommand: self.__tellEngineToMoveNow() self.readyForMoveNowCommand = False @semisynced def spectatorUndoMoves (self, moves, gamemodel): log.debug("spectatorUndoMoves: moves=%s gamemodel.ply=%s gamemodel.boards[-1]=%s self.board=%s\n" % \ (moves, gamemodel.ply, gamemodel.boards[-1], self.board), self.defname) if self.mode == INVERSE_ANALYZING: self.board = self.board.switchColor() self.__printColor() if self.engineIsInNotPlaying: print >> self.engine, "force" for i in xrange(moves): print >> self.engine, "undo" self.board = gamemodel.boards[-1] if self.mode == INVERSE_ANALYZING: self.board = self.board.switchColor() self.__printColor() if self.engineIsInNotPlaying: print >> self.engine, "force" @semisynced def playerUndoMoves (self, moves, gamemodel): log.debug("playerUndoMoves: moves=%s gamemodel.ply=%s gamemodel.boards[-1]=%s self.board=%s\n" % \ (moves, gamemodel.ply, gamemodel.boards[-1], self.board), self.defname) if gamemodel.curplayer != self and moves % 2 == 1: # Interrupt if we were searching, but should no longer do so self.returnQueue.put("int") self.__tellEngineToStopPlayingCurrentColor() if self.board and gamemodel.status in UNFINISHED_STATES: log.debug("playerUndoMoves: self.__tellEngineToMoveNow(), self._blockTillMove()\n") self.__tellEngineToMoveNow() self._blockTillMove() for i in xrange(moves): print >> self.engine, "undo" if gamemodel.curplayer == self: self.board = gamemodel.boards[-1] self.__tellEngineToPlayCurrentColorAndMakeMove() else: self.board = None #=========================================================================== # Offer handling #=========================================================================== def offer (self, offer): if offer.type == DRAW_OFFER: if self.features["draw"]: print >> self.engine, "draw" else: self.emit("accept", offer) def offerError (self, offer, error): if self.features["draw"]: # We don't keep track if engine draws are offers or accepts. We just # Always assume they are accepts, and if they are not, we get this # error and emit offer instead if offer.type == DRAW_OFFER and error == ACTION_ERROR_NONE_TO_ACCEPT: self.emit("offer", Offer(DRAW_OFFER)) #=========================================================================== # Internal #=========================================================================== def __usermove (self, board, move): if self.features["usermove"]: self.engine.write("usermove ") if self.features["san"]: print >> self.engine, toSAN(board, move) else: print >> self.engine, toAN(board, move, short=True) def __tellEngineToMoveNow (self): if self.features["sigint"]: self.engine.sigint() print >> self.engine, "?" def __tellEngineToStopPlayingCurrentColor (self): print >> self.engine, "force" self.engineIsInNotPlaying = True def __tellEngineToPlayCurrentColorAndMakeMove (self): self.__printColor() print >> self.engine, "go" self.engineIsInNotPlaying = False def __sendAnalyze (self, inverse=False): self.__tellEngineToStopPlayingCurrentColor() if inverse: self.board = self.board.setColor(1-self.color) self.__printColor() if self.engineIsInNotPlaying: print >> self.engine, "force" self.mode = INVERSE_ANALYZING else: self.mode = ANALYZING print >> self.engine, "post" print >> self.engine, "analyze" # workaround for crafty not sending analysis after it has found a mating line # http://code.google.com/p/pychess/issues/detail?id=515 if "crafty" in self.features["myname"].lower(): print >> self.engine, "noise 0" def __printColor (self): if self.features["colors"] or self.mode == INVERSE_ANALYZING: if self.board.color == WHITE: print >> self.engine, "white" else: print >> self.engine, "black" def __setBoard (self, board): if self.features["setboard"]: self.__tellEngineToStopPlayingCurrentColor() print >> self.engine, "setboard", board.asFen() else: # Kludge to set black to move, avoiding the troublesome and now # deprecated "black" command. - Equal to the one xboard uses self.__tellEngineToStopPlayingCurrentColor() if board.color == BLACK: print >> self.engine, "a2a3" print >> self.engine, "edit" print >> self.engine, "#" for color in WHITE, BLACK: for y, row in enumerate(board.data): for x, piece in enumerate(row): if not piece or piece.color != color: continue sign = reprSign[piece.sign] cord = repr(Cord(x,y)) print >> self.engine, sign+cord print >> self.engine, "c" print >> self.engine, "." def _blockTillMove (self): saved_state = self.boardLock._release_save() log.debug("_blockTillMove(): acquiring self.movecon lock\n", self.defname) self.movecon.acquire() log.debug("_blockTillMove(): self.movecon acquired\n", self.defname) try: log.debug("_blockTillMove(): doing self.movecon.wait\n", self.defname) self.movecon.wait() finally: log.debug("_blockTillMove(): releasing self.movecon..\n", self.defname) self.movecon.release() self.boardLock._acquire_restore(saved_state) #=========================================================================== # Parsing #=========================================================================== def parseLines (self, engine, lines): for line in lines: self.__parseLine(line) def __parseLine (self, line): # log.debug("__parseLine: line=\"%s\"\n" % line.strip(), self.defname) parts = whitespaces.split(line.strip()) if parts[0] == "pong": self.lastpong = int(parts[1]) return # Illegal Move if parts[0].lower().find("illegal") >= 0: log.warn("__parseLine: illegal move: line=\"%s\", board=%s" \ % (line.strip(), self.board), self.defname) if parts[-2] == "sd" and parts[-1].isdigit(): print >> self.engine, "depth", parts[-1] return # A Move (Perhaps) if self.board: if parts[0] == "move": movestr = parts[1] # Old Variation elif d_plus_dot_expr.match(parts[0]) and parts[1] == "...": movestr = parts[2] else: movestr = False if movestr: log.debug("__parseLine: acquiring self.boardLock\n", self.defname) self.waitingForMove = False self.readyForMoveNowCommand = False self.boardLock.acquire() try: if self.engineIsInNotPlaying: # If engine was set in pause just before the engine sent its # move, we ignore it. However the engine has to know that we # ignored it, and thus we step it one back log.log("__parseLine: Discarding engine's move: %s\n" % movestr, self.defname) print >> self.engine, "undo" return else: try: move = parseAny(self.board, movestr) except ParsingError, e: raise PlayerIsDead, e if validate(self.board, move): self.board = None self.returnQueue.put(move) return raise PlayerIsDead, "Board didn't validate after move" finally: log.debug("__parseLine(): releasing self.boardLock\n", self.defname) self.boardLock.release() self.movecon.acquire() self.movecon.notifyAll() self.movecon.release() # Analyzing if self.engineIsInNotPlaying: if parts[:4] == ["0","0","0","0"]: # Crafty doesn't analyze until it is out of book print >> self.engine, "book off" return match = anare.match(line) if match: score, moves = match.groups() if "mat" in score.lower(): # Will look either like -Mat 3 or Mat3 scoreval = MATE_VALUE - int("".join(c for c in score if c.isdigit())) if score.startswith('-'): scoreval = -scoreval else: scoreval = int(score) mvstrs = movere.findall(moves) try: moves = listToMoves (self.board, mvstrs, type=None, validate=True, ignoreErrors=False) except ParsingError, e: # ParsingErrors may happen when parsing "old" lines from # analyzing engines, which haven't yet noticed their new tasks log.debug("Ignored a line from analyzer: ParsingError%s\n" % e, self.defname) return # Don't emit if we weren't able to parse moves, or if we have a move # to kill the opponent king - as it confuses many engines if moves and not self.board.board.opIsChecked(): self.emit("analyze", moves, scoreval) return # Offers draw if parts[0:2] == ["offer", "draw"]: self.emit("accept", Offer(DRAW_OFFER)) return # Resigns if "resign" in parts: self.emit("offer", Offer(RESIGNATION)) return #if parts[0].lower() == "error": # return #Tell User Error if parts[0] == "tellusererror": log.warn("Ignoring tellusererror: %s\n" % " ".join(parts[1:])) return # Tell Somebody if parts[0][:4] == "tell" and \ parts[0][4:] in ("others", "all", "ics", "icsnoalias"): # Crafty sometimes only resign to ics :S #if parts[1] == "resign": # self.emit("offer", Offer(RESIGNATION)) # log.warn("Interpreted tellics as a wish to resign") #else: log.log("Ignoring tell %s: %s\n" % (parts[0][4:], " ".join(parts[1:]))) return if "feature" in parts: # We skip parts before 'feature', as some engines give us lines like # White (1) : feature setboard=1 analyze...e="GNU Chess 5.07" done=1 parts = parts[parts.index("feature"):] for i, pair in enumerate(parts[1:]): # As "parts" is split with no thoughs on quotes or double quotes # we need to do some extra handling. if pair.find("=") < 0: continue key, value = pair.split("=",1) if value[0] in ('"',"'") and value[-1] in ('"',"'"): value = value[1:-1] # If our pair was unfinished, like myname="GNU, we search the # rest of the pairs for a quotating mark. elif value[0] in ('"',"'"): rest = value[1:] + " " + " ".join(parts[2+i:]) i = rest.find('"') j = rest.find("'") if i + j == -2: log.warn("Missing endquotation in %s feature", self.defname) value = rest elif min(i, j) != -1: value = rest[:min(i, j)] else: l = max(i, j) value = rest[:l] else: # All nonquoted values are ints value = int(value) if key in self.supported_features: print >> self.engine, "accepted %s" % key else: print >> self.engine, "rejected %s" % key if key == "done": if value == 1: self.emit("readyForOptions") self.emit("readyForMoves") self.returnQueue.put("ready") elif value == 0: log.log("Adds %d seconds timeout\n" % TIME_OUT_SECOND, self.defname) # This'll buy you some more time self.timeout = time.time()+TIME_OUT_SECOND self.returnQueue.put("not ready") return self.features[key] = value if key == "myname" and not self.name: self.setName(value) # A hack to get better names in protover 1. # Unfortunately it wont work for now, as we don't read any lines from # protover 1 engines. When should we stop? if self.protover == 1: if self.defname[0] in ''.join(parts): basis = self.defname[0] name = ' '.join(itertools.dropwhile(lambda part: basis not in part, parts)) self.features['myname'] = name if not self.name: self.setName(name) #=========================================================================== # Info #=========================================================================== def canAnalyze (self): assert self.ready, "Still waiting for done=1" return self.features["analyze"] def isAnalyzing (self): return self.mode in (ANALYZING, INVERSE_ANALYZING) def __repr__ (self): if self.name: return self.name return self.features["myname"]
Python
from gobject import SIGNAL_RUN_FIRST from threading import Condition from pychess.System.Log import log from pychess.Players.Engine import Engine from pychess.Utils.const import * from pychess.Utils.repr import reprColor class ProtocolEngine (Engine): __gsignals__ = { "readyForOptions": (SIGNAL_RUN_FIRST, None, ()), "readyForMoves": (SIGNAL_RUN_FIRST, None, ()) } #=========================================================================== # Setting engine options #=========================================================================== def __init__ (self, subprocess, color, protover): Engine.__init__(self) self.engine = subprocess self.defname = subprocess.defname self.color = color self.protover = protover self.readyMoves = False self.readyOptions = False self.connected = True self.mode = NORMAL log.debug(reprColor[color]+"\n", self.defname) self.movecon = Condition()
Python
from __future__ import with_statement import collections from copy import copy import Queue from threading import RLock from pychess.Utils.Move import * from pychess.Utils.Board import Board from pychess.Utils.Cord import Cord from pychess.Utils.Offer import Offer from pychess.Utils.logic import validate, getMoveKillingKing, getStatus from pychess.Utils.const import * from pychess.Utils.lutils.ldata import MATE_VALUE from pychess.System.Log import log from pychess.System.SubProcess import TimeOutError, SubProcessError from pychess.System.ThreadPool import pool from pychess.Variants.fischerandom import FischerRandomChess from ProtocolEngine import ProtocolEngine from Player import Player, PlayerIsDead, TurnInterrupt TYPEDIC = {"check":lambda x:x=="true", "spin":int} OPTKEYS = ("type", "min", "max", "default", "var") class UCIEngine (ProtocolEngine): def __init__ (self, subprocess, color, protover): ProtocolEngine.__init__(self, subprocess, color, protover) self.ids = {} self.options = {} self.optionsToBeSent = {} self.wtime = 60000 self.btime = 60000 self.incr = 0 self.timeHandicap = 1 self.moveLock = RLock() # none of the following variables should be changed or used in a # condition statement without holding the above self.moveLock self.pondermove = None self.ignoreNext = False self.waitingForMove = False self.needBestmove = False self.readyForStop = False # keeps track of whether we already sent a 'stop' command self.commands = collections.deque() self.board = None self.uciok = False self.returnQueue = Queue.Queue() self.engine.connect("line", self.parseLines) self.engine.connect("died", self.__die) self.connect("readyForOptions", self.__onReadyForOptions_before) self.connect_after("readyForOptions", self.__onReadyForOptions) self.connect_after("readyForMoves", self.__onReadyForMoves) def __die (self, subprocess): self.returnQueue.put("die") #=========================================================================== # Starting the game #=========================================================================== def prestart (self): print >> self.engine, "uci" def start (self): if self.mode in (ANALYZING, INVERSE_ANALYZING): pool.start(self.__startBlocking) else: self.__startBlocking() def __startBlocking (self): r = self.returnQueue.get() if r == 'die': raise PlayerIsDead assert r == "ready" or r == 'del' #self.emit("readyForOptions") #self.emit("readyForMoves") def __onReadyForOptions_before (self, self_): self.readyOptions = True def __onReadyForOptions (self, self_): if self.mode in (ANALYZING, INVERSE_ANALYZING): if self.hasOption("Ponder"): self.setOption('Ponder', False) for option, value in self.optionsToBeSent.iteritems(): if self.options[option]["default"] != value: self.options[option]["default"] = value if type(value) == bool: value = str(value).lower() print >> self.engine, "setoption name", option, "value", str(value) print >> self.engine, "isready" def __onReadyForMoves (self, self_): self.returnQueue.put("ready") self.readyMoves = True self._newGame() # If we are an analyzer, this signal was already called in a different # thread, so we can safely block it. if self.mode in (ANALYZING, INVERSE_ANALYZING): if not self.board: self.board = Board(setup=True) self.putMove(self.board, None, None) #=========================================================================== # Ending the game #=========================================================================== def end (self, status, reason): # UCI doens't care about reason, so we just kill self.kill(reason) def kill (self, reason): """ Kills the engine, starting with the 'stop' and 'quit' commands, then trying sigterm and eventually sigkill. Returns the exitcode, or if engine have already been killed, the method returns None """ if self.connected: self.connected = False try: try: print >> self.engine, "stop" print >> self.engine, "quit" self.returnQueue.put("del") return self.engine.gentleKill() except OSError, e: # No need to raise on a hang up error, as the engine is dead # anyways if e.errno == 32: log.warn("Hung up Error", self.defname) return e.errno else: raise finally: # Clear the analyzed data, if any self.emit("analyze", [], None) #=========================================================================== # Send the player move updates #=========================================================================== def putMove (self, board1, move, board2): log.debug("putMove: board1=%s move=%s board2=%s self.board=%s\n" % \ (board1, move, board2, self.board), self.defname) if not self.readyMoves: return self.board = board1 if self.mode == INVERSE_ANALYZING: self.board = self.board.switchColor() self._searchNow() def makeMove (self, board1, move, board2): log.debug("makeMove: move=%s self.pondermove=%s board1=%s board2=%s self.board=%s\n" % \ (move, self.pondermove, board1, board2, self.board), self.defname) assert self.readyMoves with self.moveLock: self.board = board1 self.waitingForMove = True ponderhit = False if board2 and self.pondermove and move == self.pondermove: ponderhit = True elif board2 and self.pondermove: self.ignoreNext = True print >> self.engine, "stop" self._searchNow(ponderhit=ponderhit) # Parse outputs try: r = self.returnQueue.get() if r == "del": raise PlayerIsDead if r == "int": with self.moveLock: self.pondermove = None self.ignoreNext = True self.needBestmove = True self.hurry() raise TurnInterrupt return r finally: with self.moveLock: self.waitingForMove = False # empty the queue of any moves received post-undo/TurnInterrupt self.returnQueue.queue.clear() def updateTime (self, secs, opsecs): if self.color == WHITE: self.wtime = int(secs*1000*self.timeHandicap) self.btime = int(opsecs*1000) else: self.btime = int(secs*1000*self.timeHandicap) self.wtime = int(opsecs*1000) #=========================================================================== # Standard options #=========================================================================== def setOptionAnalyzing (self, mode): self.mode = mode def setOptionInitialBoard (self, model): log.debug("setOptionInitialBoard: self=%s, model=%s\n" % \ (self, model), self.defname) # UCI always sets the position when searching for a new game, but for # getting analyzers ready to analyze at first ply, it is good to have. self.board = model.getBoardAtPly(model.ply) pass def setOptionVariant (self, variant): if variant == FischerRandomChess: assert self.hasOption("UCI_Chess960") self.setOption("UCI_Chess960", True) def setOptionTime (self, secs, gain): self.wtime = int(max(secs*1000*self.timeHandicap, 1)) self.btime = int(max(secs*1000*self.timeHandicap, 1)) self.incr = int(gain*1000*self.timeHandicap) def setOptionStrength (self, strength): self.strength = strength if self.hasOption('UCI_LimitStrength') and strength <= 6: self.setOption('UCI_LimitStrength', True) if self.hasOption('UCI_Elo'): self.setOption('UCI_Elo', 300 * strength + 200) if not self.hasOption('UCI_Elo') or strength == 7: self.timeHandicap = th = 0.01 * 10**(strength/4.) self.wtime = int(max(self.wtime*th, 1)) self.btime = int(max(self.btime*th, 1)) self.incr = int(self.incr*th) if self.hasOption('Ponder'): self.setOption('Ponder', strength >= 7) #=========================================================================== # Interacting with the player #=========================================================================== def pause (self): log.debug("pause: self=%s\n" % self, self.defname) self.engine.pause() return if self.board and self.board.color == self.color or \ self.mode != NORMAL or self.pondermove: self.ignoreNext = True print >> self.engine, "stop" def resume (self): log.debug("resume: self=%s\n" % self, self.defname) self.engine.resume() return if self.mode == NORMAL: if self.board and self.board.color == self.color: self._searchNow() elif self.getOption('Ponder') and self.pondermove: self._startPonder() else: self._searchNow() def hurry (self): log.debug("hurry: self.waitingForMove=%s self.readyForStop=%s\n" % \ (self.waitingForMove, self.readyForStop), self.defname) # sending this more than once per move will crash most engines # so we need to send only the first one, and then ignore every "hurry" request # after that until there is another outstanding "position..go" with self.moveLock: if self.waitingForMove and self.readyForStop: print >> self.engine, "stop" self.readyForStop = False def playerUndoMoves (self, moves, gamemodel): log.debug("playerUndoMoves: moves=%s gamemodel.ply=%s gamemodel.boards[-1]=%s self.board=%s\n" % \ (moves, gamemodel.ply, gamemodel.boards[-1], self.board), self.defname) if (gamemodel.curplayer != self and moves % 2 == 1) or \ (gamemodel.curplayer == self and moves % 2 == 0): # Interrupt if we were searching but should no longer do so, or # if it is was our move before undo and it is still our move after undo # since we need to send the engine the new FEN in makeMove() log.debug("playerUndoMoves: putting 'int' into self.returnQueue=%s\n" % \ self.returnQueue.queue, self.defname) self.returnQueue.put("int") def spectatorUndoMoves (self, moves, gamemodel): log.debug("spectatorUndoMoves: moves=%s gamemodel.ply=%s gamemodel.boards[-1]=%s self.board=%s\n" % \ (moves, gamemodel.ply, gamemodel.boards[-1], self.board), self.defname) self.putMove(gamemodel.getBoardAtPly(gamemodel.ply), None, None) #=========================================================================== # Offer handling #=========================================================================== def offer (self, offer): if offer.type == DRAW_OFFER: self.emit("decline", offer) else: self.emit("accept", offer) #=========================================================================== # Option handling #=========================================================================== def setOption (self, key, value): """ Set an option, which will be sent to the engine, after the 'readyForOptions' signal has passed. If you want to know the possible options, you should go to engineDiscoverer or use the getOption, getOptions and hasOption methods, while you are in your 'readyForOptions' signal handler """ if self.readyMoves: log.warn("Options set after 'readyok' are not sent to the engine", self.defname) self.optionsToBeSent[key] = value def getOption (self, option): assert self.readyOptions if option in self.options: return self.options[option]["default"] return None def getOptions (self): assert self.readyOptions return copy(self.options) def hasOption (self, key): assert self.readyOptions return key in self.options #=========================================================================== # Internal #=========================================================================== def _newGame (self): print >> self.engine, "ucinewgame" def _searchNow (self, ponderhit=False): log.debug("_searchNow: self.needBestmove=%s ponderhit=%s self.board=%s\n" % \ (self.needBestmove, ponderhit, self.board), self.defname) with self.moveLock: commands = [] if ponderhit: commands.append("ponderhit") elif self.mode == NORMAL: commands.append("position fen %s" % self.board.asFen()) if self.strength <= 3: commands.append("go depth %d" % self.strength) else: commands.append("go wtime %d btime %d winc %d binc %d" % \ (self.wtime, self.btime, self.incr, self.incr)) else: if self.mode == INVERSE_ANALYZING: if self.board.board.opIsChecked(): # Many engines don't like positions able to take down enemy # king. Therefore we just return the "kill king" move # automaticaly self.emit("analyze", [getMoveKillingKing(self.board)], MATE_VALUE-1) return print >> self.engine, "stop" if self.board.asFen() == FEN_START: commands.append("position startpos") else: commands.append("position fen %s" % self.board.asXFen()) commands.append("go infinite") if self.needBestmove: self.commands.append(commands) log.debug("_searchNow: self.needBestmove==True, appended to self.commands=%s\n" % \ self.commands, self.defname) else: for command in commands: print >> self.engine, command if self.board.asFen() != FEN_START and getStatus(self.board)[1] != WON_MATE: self.needBestmove = True self.readyForStop = True def _startPonder (self): print >> self.engine, "position fen", self.board.asXFen(), \ "moves", toAN(self.board, self.pondermove, short=True) print >> self.engine, "go ponder wtime", self.wtime, \ "btime", self.btime, "winc", self.incr, "binc", self.incr #=========================================================================== # Parsing from engine #=========================================================================== def parseLines (self, engine, lines): for line in lines: self.__parseLine(line) def __parseLine (self, line): if not self.connected: return parts = line.split() if not parts: return #---------------------------------------------------------- Initializing if parts[0] == "id": self.ids[parts[1]] = " ".join(parts[2:]) if parts[1] == "name": self.setName(self.ids["name"]) return if parts[0] == "uciok": self.emit("readyForOptions") return if parts[0] == "readyok": self.emit("readyForMoves") return #------------------------------------------------------- Options parsing if parts[0] == "option": dic = {} last = 1 varlist = [] for i in xrange (2, len(parts)+1): if i == len(parts) or parts[i] in OPTKEYS: key = parts[last] value = " ".join(parts[last+1:i]) if "type" in dic and dic["type"] in TYPEDIC: value = TYPEDIC[dic["type"]](value) if key == "var": varlist.append(value) else: dic[key] = value last = i if varlist: dic["vars"] = varlist name = dic["name"] del dic["name"] self.options[name] = dic return #---------------------------------------------------------------- A Move if self.mode == NORMAL and parts[0] == "bestmove": with self.moveLock: self.needBestmove = False self.__sendQueuedGo() if self.ignoreNext: log.debug("__parseLine: line='%s' self.ignoreNext==True, returning\n" % \ line.strip(), self.defname) self.ignoreNext = False self.readyForStop = True return if not self.waitingForMove: log.warn("__parseLine: self.waitingForMove==False, ignoring move=%s\n" % \ parts[1], self.defname) self.pondermove = None return self.waitingForMove = False move = parseAN(self.board, parts[1]) if not validate(self.board, move): # This is critical. To avoid game stalls, we need to resign on # behalf of the engine. log.error("__parseLine: move=%s didn't validate, putting 'del' in returnQueue. self.board=%s\n" % \ (repr(move), self.board), self.defname) self.returnQueue.put('del') return self.board = self.board.move(move) log.debug("__parseLine: applied move=%s to self.board=%s\n" % \ (move, self.board), self.defname) if self.getOption('Ponder'): self.pondermove = None # An engine may send an empty ponder line, simply to clear. if len(parts) == 4 and self.board: # Engines don't always check for everything in their # ponders. Hence we need to validate. # But in some cases, what they send may not even be # correct AN - specially in the case of promotion. try: pondermove = parseAN(self.board, parts[3]) except ParsingError: pass else: if validate(self.board, pondermove): self.pondermove = pondermove self._startPonder() self.returnQueue.put(move) log.debug("__parseLine: put move=%s into self.returnQueue=%s\n" % \ (move, self.returnQueue.queue), self.defname) return #----------------------------------------------------------- An Analysis if self.mode != NORMAL and parts[0] == "info" and "pv" in parts: scoretype = parts[parts.index("score")+1] if scoretype in ('lowerbound', 'upperbound'): score = None else: score = int(parts[parts.index("score")+2]) if scoretype == 'mate': # print >> self.engine, "stop" sign = score/abs(score) score = sign * (MATE_VALUE-abs(score)) movstrs = parts[parts.index("pv")+1:] try: moves = listToMoves (self.board, movstrs, AN, validate=True, ignoreErrors=False) except ParsingError, e: # ParsingErrors may happen when parsing "old" lines from # analyzing engines, which haven't yet noticed their new tasks log.debug("__parseLine: Ignored (%s) from analyzer: ParsingError%s\n" % \ (' '.join(movstrs),e), self.defname) return self.emit("analyze", moves, score) return #----------------------------------------------- An Analyzer bestmove if self.mode != NORMAL and parts[0] == "bestmove": with self.moveLock: log.debug("__parseLine: processing analyzer bestmove='%s'\n" % \ line.strip(), self.defname) self.needBestmove = False self.__sendQueuedGo(sendlast=True) return # Stockfish complaining it received a 'stop' without a corresponding 'position..go' if line.strip() == "Unknown command: stop": with self.moveLock: log.debug("__parseLine: processing '%s'\n" % line.strip(), self.defname) self.ignoreNext = False self.needBestmove = False self.readyForStop = False self.__sendQueuedGo() return #* score #* cp <x> # the score from the engine's point of view in centipawns. #* mate <y> # mate in y moves, not plies. # If the engine is getting mated use negative values for y. #* lowerbound # the score is just a lower bound. #* upperbound # the score is just an upper bound. def __sendQueuedGo (self, sendlast=False): """ Sends the next position...go or ponderhit command set which was queued (if any). sendlast -- If True, send the last position-go queued rather than the first, and discard the others (intended for analyzers) """ with self.moveLock: if len(self.commands) > 0: if sendlast: commands = self.commands.pop() self.commands.clear() else: commands = self.commands.popleft() for command in commands: print >> self.engine, command self.needBestmove = True self.readyForStop = True log.debug("__sendQueuedGo: sent queued go=%s\n" % commands, self.defname) #=========================================================================== # Info #=========================================================================== def canAnalyze (self): # All UCIEngines can analyze return True def __repr__ (self): if self.name: return self.name if "name" in self.ids: return self.ids["name"] return ', '.join(self.defname)
Python
from collections import defaultdict from Queue import Queue from Player import Player, PlayerIsDead, TurnInterrupt from pychess.Utils.Move import parseSAN, toAN, ParsingError from pychess.Utils.Offer import Offer from pychess.Utils.const import * from pychess.System.Log import log class ICPlayer (Player): __type__ = REMOTE def __init__ (self, gamemodel, ichandle, gameno, color, name, icrating=None): Player.__init__(self) self.queue = Queue() self.okqueue = Queue() self.setName(name) self.ichandle = ichandle self.icrating = icrating self.color = color self.gameno = gameno self.gamemodel = gamemodel self.connection = connection = self.gamemodel.connection self.connections = connections = defaultdict(list) connections[connection.bm].append(connection.bm.connect_after("boardUpdate", self.__boardUpdate)) connections[connection.om].append(connection.om.connect("onOfferAdd", self.__onOfferAdd)) connections[connection.om].append(connection.om.connect("onOfferRemove", self.__onOfferRemove)) connections[connection.om].append(connection.om.connect("onOfferDeclined", self.__onOfferDeclined)) connections[connection.cm].append(connection.cm.connect("privateMessage", self.__onPrivateMessage)) self.offers = {} def getICHandle (self): return self.name #=========================================================================== # Handle signals from the connection #=========================================================================== def __onOfferAdd (self, om, offer): if self.gamemodel.status in UNFINISHED_STATES and not self.gamemodel.isObservationGame(): log.debug("ICPlayer.__onOfferAdd: emitting offer: self.gameno=%s self.name=%s %s\n" % \ (self.gameno, self.name, offer)) self.offers[offer.index] = offer self.emit ("offer", offer) def __onOfferDeclined (self, om, offer): for offer_ in self.gamemodel.offers.keys(): if offer.type == offer_.type: offer.param = offer_.param log.debug("ICPlayer.__onOfferDeclined: emitting decline for %s\n" % offer) self.emit("decline", offer) def __onOfferRemove (self, om, offer): if offer.index in self.offers: log.debug("ICPlayer.__onOfferRemove: emitting withdraw: self.gameno=%s self.name=%s %s\n" % \ (self.gameno, self.name, offer)) self.emit ("withdraw", self.offers[offer.index]) del self.offers[offer.index] def __onPrivateMessage (self, cm, name, title, isadmin, text): if name == self.name: self.emit("offer", Offer(CHAT_ACTION, param=text)) def __boardUpdate (self, bm, gameno, ply, curcol, lastmove, fen, wname, bname, wms, bms): log.debug("ICPlayer.__boardUpdate: id(self)=%d self=%s %s %s %s %d %d %s %s %d %d\n" % \ (id(self), self, gameno, wname, bname, ply, curcol, lastmove, fen, wms, bms)) if gameno == self.gameno and len(self.gamemodel.players) >= 2 \ and wname == self.gamemodel.players[0].ichandle \ and bname == self.gamemodel.players[1].ichandle: log.debug("ICPlayer.__boardUpdate: id=%d self=%s gameno=%s: this is my move\n" % \ (id(self), self, gameno)) # In some cases (like lost on time) the last move is resent if ply <= self.gamemodel.ply: return if 1-curcol == self.color: log.debug("ICPlayer.__boardUpdate: id=%d self=%s ply=%d: putting move=%s in queue\n" % \ (id(self), self, ply, lastmove)) self.queue.put((ply, lastmove)) # Ensure the fics thread doesn't continue parsing, before the # game/player thread has recieved the move. # Specifically this ensures that we aren't killed due to end of # game before our last move is recieved self.okqueue.get(block=True) #=========================================================================== # Ending the game #=========================================================================== def __disconnect (self): if self.connections is None: return for obj in self.connections: for handler_id in self.connections[obj]: if obj.handler_is_connected(handler_id): obj.disconnect(handler_id) self.connections = None def end (self, status, reason): self.__disconnect() self.queue.put("del") def kill (self, reason): self.__disconnect() self.queue.put("del") #=========================================================================== # Send the player move updates #=========================================================================== def makeMove (self, board1, move, board2): log.debug("ICPlayer.makemove: id(self)=%d self=%s move=%s board1=%s board2=%s\n" % \ (id(self), self, move, board1, board2)) if board2 and not self.gamemodel.isObservationGame(): self.connection.bm.sendMove (toAN (board2, move)) item = self.queue.get(block=True) try: if item == "del": raise PlayerIsDead if item == "int": raise TurnInterrupt ply, sanmove = item if ply < board1.ply: # This should only happen in an observed game board1 = self.gamemodel.getBoardAtPly(max(ply-1, 0)) log.debug("ICPlayer.makemove: id(self)=%d self=%s from queue got: ply=%d sanmove=%s\n" % \ (id(self), self, ply, sanmove)) try: move = parseSAN (board1, sanmove) log.debug("ICPlayer.makemove: id(self)=%d self=%s parsed move=%s\n" % \ (id(self), self, move)) except ParsingError, e: raise return move finally: log.debug("ICPlayer.makemove: id(self)=%d self=%s returning move=%s\n" % \ (id(self), self, move)) self.okqueue.put("ok") #=========================================================================== # Interacting with the player #=========================================================================== def pause (self): pass def resume (self): pass def setBoard (self, fen): # setBoard will currently only be called for ServerPlayer when starting # to observe some game. In this case FICS already knows how the board # should look, and we don't need to set anything pass def playerUndoMoves (self, movecount, gamemodel): log.debug("ICPlayer.playerUndoMoves: id(self)=%d self=%s, undoing movecount=%d\n" % \ (id(self), self, movecount)) # If current player has changed so that it is no longer us to move, # We raise TurnInterruprt in order to let GameModel continue the game if movecount % 2 == 1 and gamemodel.curplayer != self: self.queue.put("int") def putMessage (self, text): self.connection.cm.tellPlayer (self.name, text) #=========================================================================== # Offer handling #=========================================================================== def offerRematch (self): if self.gamemodel.timemodel: min = int(self.gamemodel.timemodel.intervals[0][0])/60 inc = self.gamemodel.timemodel.gain else: min = 0 inc = 0 self.connection.om.challenge(self.ichandle, self.gamemodel.ficsgame.game_type, min, inc, self.gamemodel.ficsgame.rated) def offer (self, offer): log.debug("ICPlayer.offer: self=%s %s\n" % (repr(self), offer)) if offer.type == TAKEBACK_OFFER: # only 1 outstanding takeback offer allowed on FICS, so remove any of ours indexes = self.offers.keys() for index in indexes: if self.offers[index].type == TAKEBACK_OFFER: log.debug("ICPlayer.offer: del self.offers[%s] %s\n" % (index, offer)) del self.offers[index] self.connection.om.offer(offer, self.gamemodel.ply) def offerDeclined (self, offer): log.debug("ICPlayer.offerDeclined: sending decline for %s\n" % offer) self.connection.om.decline(offer) def offerWithdrawn (self, offer): pass def offerError (self, offer, error): pass
Python
from Queue import Queue import gtk, gobject from pychess.Utils.const import * from pychess.Utils.Offer import Offer from pychess.System.Log import log from pychess.System import glock, conf from Player import Player, PlayerIsDead, TurnInterrupt OFFER_MESSAGES = { DRAW_OFFER: (_("Your opponent has offered you a draw. Accept?"), _("Your opponent has offered you a draw. If you accept this offer, the game will end with a score of 1/2 - 1/2."), False), ABORT_OFFER: (_("Your opponent wants to abort the game. Accept?"), _("Your opponent has asked that the game be aborted. If you accept this offer, the game will end with no rating change."), False), ADJOURN_OFFER: (_("Your opponent wants to adjourn the game. Accept?"), _("Your opponent has asked that the game be adjourned. If you accept this offer, the game will be adjourned and you can resume it later (when your opponent is online and both players agree to resume)."), False), TAKEBACK_OFFER: (_("Your opponent wants to undo %s move(s). Accept?"), _("Your opponent has asked that the last %s move(s) be undone. If you accept this offer, the game will continue from the earlier position."), True), PAUSE_OFFER: (_("Your opponent wants to pause the game. Accept?"), _("Your opponent has asked that the game be paused. If you accept this offer, the game clock will be paused until both players agree to resume the game."), False), RESUME_OFFER: (_("Your opponent wants to resume the game. Accept?"), _("Your opponent has asked that the game be resumed. If you accept this offer, the game clock will continue from where it was paused."), False) } ACTION_NAMES = { RESIGNATION: _("The resignation"), FLAG_CALL: _("The flag call"), DRAW_OFFER: _("The draw offer"), ABORT_OFFER: _("The abort offer"), ADJOURN_OFFER: _("The adjourn offer"), PAUSE_OFFER: _("The pause offer"), RESUME_OFFER: _("The resume offer"), SWITCH_OFFER: _("The offer to switch sides"), TAKEBACK_OFFER: _("The takeback offer"), } ACTION_ACTIONS = { RESIGNATION: _("resign"), FLAG_CALL: _("call your opponents flag"), DRAW_OFFER: _("offer a draw"), ABORT_OFFER: _("offer an abort"), ADJOURN_OFFER: _("offer to adjourn"), PAUSE_OFFER: _("offer a pause"), RESUME_OFFER: _("offer to resume"), SWITCH_OFFER: _("offer to switch sides"), TAKEBACK_OFFER: _("offer a takeback"), HURRY_ACTION: _("ask your opponent to move") } ERROR_MESSAGES = { ACTION_ERROR_NOT_OUT_OF_TIME: _("Your opponent is not out of time."), ACTION_ERROR_CLOCK_NOT_STARTED: _("The clock hasn't been started yet."), ACTION_ERROR_SWITCH_UNDERWAY: _("You can't switch colors during the game."), ACTION_ERROR_TOO_LARGE_UNDO: _("You have tried to undo too many moves."), } class Human (Player): __type__ = LOCAL __gsignals__ = { "messageRecieved": (gobject.SIGNAL_RUN_FIRST, None, (str,)), } def __init__ (self, gmwidg, color, name, ichandle=None, icrating=None): Player.__init__(self) self.defname = "Human" self.board = gmwidg.board self.gmwidg = gmwidg self.gamemodel = self.board.view.model self.queue = Queue() self.color = color self.conid = [ self.board.connect("piece_moved", self.piece_moved), self.board.connect("action", lambda b,action,param: self.emit_action(action, param)) ] self.setName(name) self.ichandle = ichandle self.icrating = icrating if self.gamemodel.timemodel: self.gamemodel.timemodel.connect('zero_reached', self.zero_reached) #=========================================================================== # Handle signals from the board #=========================================================================== def zero_reached (self, timemodel, color): if conf.get('autoCallFlag', False) and \ self.gamemodel.status == RUNNING and \ timemodel.getPlayerTime(1-self.color) <= 0: log.log('Automatically sending flag call on behalf of player %s.' % self.name) self.emit("offer", Offer(FLAG_CALL)) def piece_moved (self, board, move, color): if color != self.color: return self.queue.put(move) def emit_action (self, action, param): # If there are two or more tabs open, we have to ensure us that it is # us who are in the active tab, and not the others if not self.gmwidg.isInFront(): return log.debug("Human.emit_action: self.name=%s, action=%s\n" % (self.name, action)) # If there are two human players, we have to ensure us that it was us # who did the action, and not the others if self.gamemodel.players[1-self.color].__type__ == LOCAL: if action == HURRY_ACTION: if self.gamemodel.boards[-1].color == self.color: return else: if self.gamemodel.boards[-1].color != self.color: return self.emit("offer", Offer(action, param=param)) #=========================================================================== # Send the player move updates #=========================================================================== def makeMove (self, board1, move, board2): log.debug("Human.makeMove: move=%s, board1=%s board2=%s\n" % \ (move, board1, board2)) self.gmwidg.setLocked(False) item = self.queue.get(block=True) self.gmwidg.setLocked(True) if item == "del": raise PlayerIsDead, "Killed by foreign forces" if item == "int": log.debug("Human.makeMove: %s: raise TurnInterrupt" % self) raise TurnInterrupt return item #=========================================================================== # Ending the game #=========================================================================== def end (self, status, reason): self.queue.put("del") def kill (self, reason): print "I am killed", self for id in self.conid: if self.board.handler_is_connected(id): self.board.disconnect(id) self.queue.put("del") #=========================================================================== # Interacting with the player #=========================================================================== def hurry (self): title = _("Your opponent asks you to hurry!") description = _("Generally this means nothing, as the game is timebased, but if you want to please your opponent, perhaps you should get going.") self._message(title, description, gtk.MESSAGE_INFO, gtk.BUTTONS_OK) @glock.glocked def pause (self): self.gmwidg.setLocked(True) @glock.glocked def resume (self): log.debug("Human.resume: %s\n" % (self)) if self.board.view.model.curplayer == self: self.gmwidg.setLocked(False) def playerUndoMoves (self, movecount, gamemodel): log.debug("Human.playerUndoMoves: movecount=%s self=%s\n" % (movecount, self)) #If the movecount is odd, the player has changed, and we have to interupt if movecount % 2 == 1: # If it is no longer us to move, we raise TurnInterruprt in order to # let GameModel continue the game. if gamemodel.curplayer != self: log.debug("Human.playerUndoMoves: putting TurnInterrupt into self.queue\n") self.queue.put("int") # If the movecount is even, we have to ensure the board is unlocked. # This is because it might have been locked by the game ending, but # perhaps we have now undone some moves, and it is no longer ended. elif movecount % 2 == 0 and gamemodel.curplayer == self: log.debug("Human.playerUndoMoves: self=%s: calling gmwidg.setLocked\n" % (self)) self.gmwidg.setLocked(False) def putMessage (self, text): self.emit("messageRecieved", text) def sendMessage (self, text): self.emit("offer", Offer(CHAT_ACTION, param=text)) #=========================================================================== # Offer handling #=========================================================================== def offer (self, offer): log.debug("Human.offer: self=%s %s\n" % (self, offer)) title, description, takesParam = OFFER_MESSAGES[offer.type] if takesParam: param = offer.param if offer.type == TAKEBACK_OFFER and \ self.gamemodel.players[1-self.color].__type__ is not REMOTE: param = self.gamemodel.ply - offer.param title = title % param description = description % param def responsecb (dialog, response): if response == gtk.RESPONSE_YES: self.emit("accept", offer) else: self.emit("decline", offer) self._message(title, description, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO, responsecb) def offerDeclined (self, offer): log.debug("Human.offerDeclined: self=%s %s\n" % (self, offer)) if offer.type not in ACTION_NAMES: return title = _("%s was declined by your opponent") % ACTION_NAMES[offer.type] description = _("You can try to send the offer to your opponent later in the game again.") self._message(title, description, gtk.MESSAGE_INFO, gtk.BUTTONS_OK) def offerWithdrawn (self, offer): log.debug("Human.offerWithdrawn: self=%s %s\n" % (self, offer)) if offer.type not in ACTION_NAMES: return title = _("%s was withdrawn by your opponent") % ACTION_NAMES[offer.type] description = _("Your opponent seems to have changed his or her mind.") self._message(title, description, gtk.MESSAGE_INFO, gtk.BUTTONS_OK) def offerError (self, offer, error): log.debug("Human.offerError: self=%s error=%s %s\n" % (self, error, offer)) if offer.type not in ACTION_NAMES: return actionName = ACTION_NAMES[offer.type] if error == ACTION_ERROR_NONE_TO_ACCEPT: title = _("Unable to accept %s") % actionName.lower() description = _("PyChess was unable to get the %s offer accepted. Probably because it has been withdrawn.") elif error == ACTION_ERROR_NONE_TO_DECLINE or \ error == ACTION_ERROR_NONE_TO_WITHDRAW: # If the offer was not there, it has probably already been either # declined or withdrawn. return else: title = _("%s returns an error") % actionName description = ERROR_MESSAGES[error] self._message(title, description, gtk.MESSAGE_INFO, gtk.BUTTONS_OK) @glock.glocked def _message (self, title, description, type, buttons, responsecb=(lambda d,r:None)): d = gtk.MessageDialog (type=type, buttons=buttons) d.set_markup ("<big><b>%s</b></big>" % title) d.format_secondary_text (description) def response (dialog, response, responsecb): responsecb(dialog, response) dialog.hide() d.connect("response", response, responsecb) d.show()
Python
# # main.py # flickrmirror # # Created by Nathan Van Gheem on 5/18/09. # Copyright __MyCompanyName__ 2009. All rights reserved. # #import modules required by application import objc import Foundation import AppKit from PyObjCTools import AppHelper # import modules containing classes required to start application and load MainMenu.nib import flickrmirrorAppDelegate import controller # pass control to AppKit AppHelper.runEventLoop()
Python
# # flickrmirrorAppDelegate.py # flickrmirror # # Created by Nathan Van Gheem on 5/18/09. # Copyright __MyCompanyName__ 2009. All rights reserved. # from Foundation import * from AppKit import * class flickrmirrorAppDelegate(NSObject): def applicationDidFinishLaunching_(self, sender): NSLog("Application did finish launching.")
Python
# # controller.py # flickrmirror # # Created by Nathan Van Gheem on 5/19/09. # Copyright (c) 2009 __MyCompanyName__. All rights reserved. # #import local libs to be able to use import sys, time, os, threading, datetime #now add the path so we have the right libraries to use... path = '/'.join(os.path.abspath( __file__ ).split('/')[:-1]) sys.path.append(os.path.join(path, 'libs')) from objc import YES, NO, IBAction, IBOutlet from Foundation import * from AppKit import * from PyObjCTools import AppHelper from flickrmirror.controller import MirrorController from flickrmirror.settings import pickled_foldername from flickrmirror.tools import logger class controller(NSWindowController): setsTableView = IBOutlet() mirrorLocation = IBOutlet() loadingSign = IBOutlet() loadingText = IBOutlet() flickrInfo = IBOutlet() progressBar = IBOutlet() photoProgressBar = IBOutlet() _mirror_controller = None tabView = IBOutlet() authenticateButton = IBOutlet() loadSettingsButton = IBOutlet() stopButton = IBOutlet() syncButton = IBOutlet() mirrorButton = IBOutlet() currentPhotoDownloadDetailsText = IBOutlet() overallDownloadDetailsText = IBOutlet() authenticatedText = IBOutlet() current_sender = None cancel_operation = False name = u"flickrmirror" def applicationDidFinishLaunching_(self, sender): logger.info("flickrmirror has finished loading") def applicationWillTerminate_(self, sender): logger.info("flickrmirror terminating") self.cancel_operation = True if self.has_mirror_loaded(): logger.info("flickrmirror saving before terminating") self.status("saving flickrmirror settings before exiting.") self.mirror_controller.save() def input(self, prompt): alert = NSAlert.alloc().init() alert.addButtonWithTitle_(u"Go!") alert.setMessageText_("Wait one moment...") alert.setInformativeText_(prompt) alert.setAlertStyle_(NSWarningAlertStyle) input = NSTextField.alloc().initWithFrame_(NSMakeRect(0, 0, 200, 24)) input.setStringValue_("") alert.setAccessoryView_(input) button = alert.runModal() input.validateEditing() return input.stringValue() def prompt(self, msg, result=True): if result: return self.input(msg) else: alert = NSAlert.alloc().init() alert.addButtonWithTitle_(u"OK") alert.setMessageText_("Wait one moment...") alert.setInformativeText_(msg) alert.setAlertStyle_(NSWarningAlertStyle) alert.runModal() def status(self, msg, nl=False): logger.info(msg) self.loadingText.setStringValue_(msg) def start_loading(self, sender): self.current_sender = sender self.loadingSign.startAnimation_(sender) self.authenticateButton.setEnabled_(NO) self.loadSettingsButton.setEnabled_(NO) self.mirrorButton.setEnabled_(NO) self.setsTableView.setEnabled_(NO) self.syncButton.setEnabled_(NO) self.stopButton.setEnabled_(YES) def stop_loading(self, sender): self.loadingSign.stopAnimation_(sender) self.authenticateButton.setEnabled_(YES) self.loadSettingsButton.setEnabled_(YES) self.mirrorButton.setEnabled_(YES) self.setsTableView.setEnabled_(YES) self.syncButton.setEnabled_(YES) self.stopButton.setEnabled_(NO) self.stopButton.setTitle_(u"Stop!") self.cancel_operation = False def get_mc(self): if self._mirror_controller is None: self._mirror_controller = MirrorController(self) return self._mirror_controller mirror_controller = property(get_mc) def get_mirror_directory_from_user(self, sender): panel = NSOpenPanel.openPanel() panel.setCanChooseDirectories_(YES) panel.setAllowsMultipleSelection_(NO) panel.setCanChooseFiles_(NO) panel.setTitle_(u"Choose the directory where you want to store your flickrmirror") returnCode = panel.runModal() if returnCode: folder = panel.filenames()[0] self.mirrorLocation.setStringValue_(folder) self.mirror_controller.backup_directory = folder if os.path.exists(os.path.join(folder, pickled_foldername)): self.status(u"Existing flickr settings present in this mirror location.") else: self.status(u"No existing flickr settings file present. You will need to load from scratch.") else: raise Exception("Must select directory.") def has_mirror_location(self): if not self.mirrorLocation.stringValue(): return False else: return True def authenticated(self): return self.mirror_controller.authenticator.authenticated() def has_mirror_loaded(self): return self.mirror_controller.mirror_model is not None def update_last_update(self): if self.mirror_model.last_updated > 0: dt = datetime.datetime.fromtimestamp(self.mirror_model.last_updated) self.view.status("last updated on %s" % dt.strftime("%Y-%m-%d %H:%M:%S")) else: #never updated pass def run_action(self, precondition, condition_message, start_msg, end_msg, error_msg, run_method, sender): if precondition: self.prompt(condition_message, False) return controller = self class T(threading.Thread): def run(self): try: run_method() controller.status(end_msg) except Exception, inst: logger.error(inst.message) controller.status(error_msg) finally: controller.stop_loading(sender) self.start_loading(sender) self.status(start_msg) t = T() t.start() @IBAction def stopButtonClicked_(self, sender): self.cancel_operation = True self.stopButton.setTitle_(u"Stopping...") @IBAction def authenticateButtonClicked_(self, sender): def run_method(): self.mirror_controller.authenticate() if self.authenticated(): self.authenticatedText.setStringValue_(u"YES") else: self.authenticatedText.setStringValue_(u"NO") self.run_action( False, u"Not going to happen", u"Authenticating...", u"Authenticated.", u"An error occurred while attempting to authenticate with flickr.com", run_method, sender ) @IBAction def loadButtonClicked_(self, sender): def run_method(): self.get_mirror_directory_from_user(sender) self.mirror_controller.load() self.setsTableView.reloadData() self.run_action( not self.authenticated(), u"Must authenticate before you can set your flickrmirror location.", u"Selecting and loading flickrmirror...", u"Finished Loading.", u"An error occurred while attempting to load flickr mirror settings.", run_method, sender ) @IBAction def syncButtonClicked_(self, sender): def run_method(): if self.mirror_controller.mirror_model is None: self.mirror_controller.load() self.setsTableView.reloadData() self.mirror_controller.synchronize_server() self.setsTableView.reloadData() self.stop_loading(sender) self.run_action( not self.has_mirror_location() or not self.authenticated(), u"Must set flickrmirror location and authenticate before you can synchronize with flickr.com", u"Syncing...", u"Finished Sync.", u"An error occurred while attempting to sync.", run_method, sender ) @IBAction def mirrorClicked_(self, sender): def report_hook(x, y, z): if self.cancel_operation: raise Exception("Exiting download...") res = int((float(x*y)/z)*100) if res > 100: res = 100 self.photoProgressBar.setIntValue_(res) self.currentPhotoDownloadDetailsText.setStringValue_("%i%% - %.1f/%.1fmb" % (res, float(x*y)/1024.0/1024.0, float(z)/1024.0/1024.0)) def run_method(): if self.mirror_controller.mirror_model is None: self.mirror_controller.load() self.setsTableView.reloadData() dirty_photos = self.mirror_controller.get_dirty_photos() self.update_flickr_info(len(dirty_photos), 0) for i in range(0, len(dirty_photos)): if self.cancel_operation: self.mirror_controller.save() self.stop_loading(sender) return photo, set = dirty_photos[i] self.status("%i/%i - Downloading photo %s from set %s." % (i+1, len(dirty_photos), photo.title, set.title) ) self.mirror_controller.retrieve_photo(photo, set, report_hook) self.update_flickr_info(len(dirty_photos), i+1) self.mirror_controller.save() self.run_action( not self.has_mirror_location() or not self.authenticated(), u"Must select location and authenticate before you can load your flickr data.", u"Mirroring...", u"Finished Mirror.", u"Mirroring has stopped.", run_method, sender ) def update_flickr_info(self, num_dirty_photos, current_photo_number): """ sets : # of sets total photos : # of photos photos to be updated : """ pc = self.mirror_controller.get_photo_count() self.flickrInfo.setStringValue_( """Number of sets : %i Total number of photos : %i Total photos needing update : %i""" % ( len(self.mirror_controller.mirror_model.filtered_sets()), pc, num_dirty_photos ) ) percent_downloaded = int( (float(current_photo_number)/float(num_dirty_photos))*100) self.progressBar.setIntValue_(percent_downloaded) self.overallDownloadDetailsText.setStringValue_("%i%%" % (percent_downloaded)) self.photoProgressBar.setIntValue_(0) self.currentPhotoDownloadDetailsText.setStringValue_(u"...") def numberOfRowsInTableView_(self, tableView): """ Delegate method for data source Retrieves number of sets in the mirror """ if self.mirror_controller.mirror_model is None: return 0 else: return len(self.mirror_controller.mirror_model.sets) def tableView_objectValueForTableColumn_row_(self, sender, tableColumn, row): """ Delegate method for data source Retrieves a cell value """ headerText = tableColumn.headerCell().title() set = self.mirror_controller.mirror_model.sets[row] if headerText == "Enabled": return set.id not in self.mirror_controller.mirror_model.filtered elif headerText == "id": return set.id elif headerText == "# photos": return set.number_of_photos_and_videos else: return set.title def tableView_setObjectValue_forTableColumn_row_(self, sender, enabled, tableColumn, row): """ Delegate the sets a cell value """ headerText = tableColumn.headerCell().title() if headerText == "Enabled": set = self.mirror_controller.mirror_model.sets[row] if enabled: if set.id in self.mirror_controller.mirror_model.filtered: self.mirror_controller.unfilter_set(set.id) else: if set.id not in self.mirror_controller.mirror_model.filtered: self.mirror_controller.filter_set(set.id)
Python
'''Persistent token cache management for the Flickr API''' import os.path import logging logging.basicConfig() LOG = logging.getLogger(__name__) LOG.setLevel(logging.INFO) __all__ = ('TokenCache', 'SimpleTokenCache') class SimpleTokenCache(object): '''In-memory token cache.''' def __init__(self): self.token = None def forget(self): '''Removes the cached token''' self.token = None class TokenCache(object): '''On-disk persistent token cache for a single application. The application is identified by the API key used. Per application multiple users are supported, with a single token per user. ''' def __init__(self, api_key, username=None): '''Creates a new token cache instance''' self.api_key = api_key self.username = username self.memory = {} def __get_cached_token_path(self): """Return the directory holding the app data.""" return os.path.expanduser(os.path.join("~", ".flickr", self.api_key)) def __get_cached_token_filename(self): """Return the full pathname of the cached token file.""" if self.username: filename = 'auth-%s.token' % self.username else: filename = 'auth.token' return os.path.join(self.__get_cached_token_path(), filename) def __get_cached_token(self): """Read and return a cached token, or None if not found. The token is read from the cached token file. """ # Only read the token once if self.username in self.memory: return self.memory[self.username] try: f = file(self.__get_cached_token_filename(), "r") token = f.read() f.close() return token.strip() except IOError: return None def __set_cached_token(self, token): """Cache a token for later use.""" # Remember for later use self.memory[self.username] = token path = self.__get_cached_token_path() if not os.path.exists(path): os.makedirs(path) f = file(self.__get_cached_token_filename(), "w") print >>f, token f.close() def forget(self): '''Removes the cached token''' if self.username in self.memory: del self.memory[self.username] filename = self.__get_cached_token_filename() if os.path.exists(filename): os.unlink(filename) token = property(__get_cached_token, __set_cached_token, forget, "The cached token")
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- '''A FlickrAPI interface. See `the FlickrAPI homepage`_ for more info. .. _`the FlickrAPI homepage`: http://flickrapi.sf.net/ ''' __version__ = '1.2' __all__ = ('FlickrAPI', 'IllegalArgumentException', 'FlickrError', 'CancelUpload', 'XMLNode', 'set_log_level', '__version__') __author__ = u'Sybren St\u00fcvel'.encode('utf-8') # Copyright (c) 2007 by the respective coders, see # http://flickrapi.sf.net/ # # This code is subject to the Python licence, as can be read on # http://www.python.org/download/releases/2.5.2/license/ # # For those without an internet connection, here is a summary. When this # summary clashes with the Python licence, the latter will be applied. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import sys import md5 import urllib import urllib2 import mimetools import os.path import logging import copy import webbrowser from flickrapi.tokencache import TokenCache, SimpleTokenCache from flickrapi.xmlnode import XMLNode from flickrapi.multipart import Part, Multipart, FilePart from flickrapi.exceptions import * from flickrapi.cache import SimpleCache from flickrapi import reportinghttp logging.basicConfig() LOG = logging.getLogger(__name__) LOG.setLevel(logging.INFO) def make_utf8(dictionary): '''Encodes all Unicode strings in the dictionary to UTF-8. Converts all other objects to regular strings. Returns a copy of the dictionary, doesn't touch the original. ''' result = {} for (key, value) in dictionary.iteritems(): if isinstance(value, unicode): value = value.encode('utf-8') else: value = str(value) result[key] = value return result def debug(method): '''Method decorator for debugging method calls. Using this automatically sets the log level to DEBUG. ''' LOG.setLevel(logging.DEBUG) def debugged(*args, **kwargs): LOG.debug("Call: %s(%s, %s)" % (method.__name__, args, kwargs)) result = method(*args, **kwargs) LOG.debug("\tResult: %s" % result) return result return debugged # REST parsers, {format: parser_method, ...}. Fill by using the # @rest_parser(format) function decorator rest_parsers = {} def rest_parser(format): '''Function decorator, use this to mark a function as the parser for REST as returned by Flickr. ''' def decorate_parser(method): rest_parsers[format] = method return method return decorate_parser class FlickrAPI: """Encapsulates Flickr functionality. Example usage:: flickr = flickrapi.FlickrAPI(api_key) photos = flickr.photos_search(user_id='73509078@N00', per_page='10') sets = flickr.photosets_getList(user_id='73509078@N00') """ flickr_host = "api.flickr.com" flickr_rest_form = "/services/rest/" flickr_auth_form = "/services/auth/" flickr_upload_form = "/services/upload/" flickr_replace_form = "/services/replace/" def __init__(self, api_key, secret=None, fail_on_error=None, username=None, token=None, format='etree', store_token=True, cache=False): """Construct a new FlickrAPI instance for a given API key and secret. api_key The API key as obtained from Flickr. secret The secret belonging to the API key. fail_on_error If False, errors won't be checked by the FlickrAPI module. Deprecated, don't use this parameter, just handle the FlickrError exceptions. username Used to identify the appropriate authentication token for a certain user. token If you already have an authentication token, you can give it here. It won't be stored on disk by the FlickrAPI instance. format The response format. Use either "xmlnode" or "etree" to get a parsed response, or use any response format supported by Flickr to get an unparsed response from method calls. It's also possible to pass the ``format`` parameter on individual calls. store_token Disables the on-disk token cache if set to False (default is True). Use this to ensure that tokens aren't read nor written to disk, for example in web applications that store tokens in cookies. cache Enables in-memory caching of FlickrAPI calls - set to ``True`` to use. If you don't want to use the default settings, you can instantiate a cache yourself too: >>> f = FlickrAPI(api_key='123') >>> f.cache = SimpleCache(timeout=5, max_entries=100) """ if fail_on_error is not None: LOG.warn("fail_on_error has been deprecated. Remove this " "parameter and just handle the FlickrError exceptions.") else: fail_on_error = True self.api_key = api_key self.secret = secret self.fail_on_error = fail_on_error self.default_format = format self.__handler_cache = {} if token: # Use a memory-only token cache self.token_cache = SimpleTokenCache() self.token_cache.token = token elif not store_token: # Use an empty memory-only token cache self.token_cache = SimpleTokenCache() else: # Use a real token cache self.token_cache = TokenCache(api_key, username) if cache: self.cache = SimpleCache() else: self.cache = None def __repr__(self): '''Returns a string representation of this object.''' return '[FlickrAPI for key "%s"]' % self.api_key __str__ = __repr__ def trait_names(self): '''Returns a list of method names as supported by the Flickr API. Used for tab completion in IPython. ''' try: rsp = self.reflection_getMethods(format='etree') except FlickrError: return None def tr(name): '''Translates Flickr names to something that can be called here. >>> tr(u'flickr.photos.getInfo') u'photos_getInfo' ''' return name[7:].replace('.', '_') return [tr(m.text) for m in rsp.getiterator('method')] @rest_parser('xmlnode') def parse_xmlnode(self, rest_xml): '''Parses a REST XML response from Flickr into an XMLNode object.''' rsp = XMLNode.parse(rest_xml, store_xml=True) if rsp['stat'] == 'ok' or not self.fail_on_error: return rsp err = rsp.err[0] raise FlickrError(u'Error: %(code)s: %(msg)s' % err) @rest_parser('etree') def parse_etree(self, rest_xml): '''Parses a REST XML response from Flickr into an ElementTree object.''' try: import xml.etree.ElementTree as ElementTree except ImportError: # For Python 2.4 compatibility: try: import elementtree.ElementTree as ElementTree except ImportError: raise ImportError("You need to install " "ElementTree for using the etree format") rsp = ElementTree.fromstring(rest_xml) if rsp.attrib['stat'] == 'ok' or not self.fail_on_error: return rsp err = rsp.find('err') raise FlickrError(u'Error: %s: %s' % ( err.attrib['code'], err.attrib['msg'])) def sign(self, dictionary): """Calculate the flickr signature for a set of params. data a hash of all the params and values to be hashed, e.g. ``{"api_key":"AAAA", "auth_token":"TTTT", "key": u"value".encode('utf-8')}`` """ data = [self.secret] for key in sorted(dictionary.keys()): data.append(key) datum = dictionary[key] if isinstance(datum, unicode): raise IllegalArgumentException("No Unicode allowed, " "argument %s (%r) should have been UTF-8 by now" % (key, datum)) data.append(datum) md5_hash = md5.new() md5_hash.update(''.join(data)) return md5_hash.hexdigest() def encode_and_sign(self, dictionary): '''URL encodes the data in the dictionary, and signs it using the given secret, if a secret was given. ''' dictionary = make_utf8(dictionary) if self.secret: dictionary['api_sig'] = self.sign(dictionary) return urllib.urlencode(dictionary) def __getattr__(self, attrib): """Handle all the regular Flickr API calls. Example:: flickr.auth_getFrob(api_key="AAAAAA") etree = flickr.photos_getInfo(photo_id='1234') etree = flickr.photos_getInfo(photo_id='1234', format='etree') xmlnode = flickr.photos_getInfo(photo_id='1234', format='xmlnode') json = flickr.photos_getInfo(photo_id='1234', format='json') """ # Refuse to act as a proxy for unimplemented special methods if attrib.startswith('_'): raise AttributeError("No such attribute '%s'" % attrib) # Construct the method name and see if it's cached method = "flickr." + attrib.replace("_", ".") if method in self.__handler_cache: return self.__handler_cache[method] def handler(**args): '''Dynamically created handler for a Flickr API call''' if self.token_cache.token and not self.secret: raise ValueError("Auth tokens cannot be used without " "API secret") # Set some defaults defaults = {'method': method, 'auth_token': self.token_cache.token, 'api_key': self.api_key, 'format': self.default_format} args = self.__supply_defaults(args, defaults) return self.__wrap_in_parser(self.__flickr_call, parse_format=args['format'], **args) handler.method = method self.__handler_cache[method] = handler return handler def __supply_defaults(self, args, defaults): '''Returns a new dictionary containing ``args``, augmented with defaults from ``defaults``. Defaults can be overridden, or completely removed by setting the appropriate value in ``args`` to ``None``. >>> f = FlickrAPI('123') >>> f._FlickrAPI__supply_defaults( ... {'foo': 'bar', 'baz': None, 'token': None}, ... {'baz': 'foobar', 'room': 'door'}) {'foo': 'bar', 'room': 'door'} ''' result = args.copy() for key, default_value in defaults.iteritems(): # Set the default if the parameter wasn't passed if key not in args: result[key] = default_value for key, value in result.copy().iteritems(): # You are able to remove a default by assigning None, and we can't # pass None to Flickr anyway. if result[key] is None: del result[key] return result def __flickr_call(self, **kwargs): '''Performs a Flickr API call with the given arguments. The method name itself should be passed as the 'method' parameter. Returns the unparsed data from Flickr:: data = self.__flickr_call(method='flickr.photos.getInfo', photo_id='123', format='rest') ''' LOG.debug("Calling %s" % kwargs) post_data = self.encode_and_sign(kwargs) # Return value from cache if available if self.cache and self.cache.get(post_data): return self.cache.get(post_data) url = "http://" + FlickrAPI.flickr_host + FlickrAPI.flickr_rest_form flicksocket = urllib.urlopen(url, post_data) reply = flicksocket.read() flicksocket.close() # Store in cache, if we have one if self.cache is not None: self.cache.set(post_data, reply) return reply def __wrap_in_parser(self, wrapped_method, parse_format, *args, **kwargs): '''Wraps a method call in a parser. The parser will be looked up by the ``parse_format`` specifier. If there is a parser and ``kwargs['format']`` is set, it's set to ``rest``, and the response of the method is parsed before it's returned. ''' # Find the parser, and set the format to rest if we're supposed to # parse it. if parse_format in rest_parsers and 'format' in kwargs: kwargs['format'] = 'rest' LOG.debug('Wrapping call %s(self, %s, %s)' % (wrapped_method, args, kwargs)) data = wrapped_method(*args, **kwargs) # Just return if we have no parser if parse_format not in rest_parsers: return data # Return the parsed data parser = rest_parsers[parse_format] return parser(self, data) def auth_url(self, perms, frob): """Return the authorization URL to get a token. This is the URL the app will launch a browser toward if it needs a new token. perms "read", "write", or "delete" frob picked up from an earlier call to FlickrAPI.auth_getFrob() """ encoded = self.encode_and_sign({ "api_key": self.api_key, "frob": frob, "perms": perms}) return "http://%s%s?%s" % (FlickrAPI.flickr_host, \ FlickrAPI.flickr_auth_form, encoded) def web_login_url(self, perms): '''Returns the web login URL to forward web users to. perms "read", "write", or "delete" ''' encoded = self.encode_and_sign({ "api_key": self.api_key, "perms": perms}) return "http://%s%s?%s" % (FlickrAPI.flickr_host, \ FlickrAPI.flickr_auth_form, encoded) def __extract_upload_response_format(self, kwargs): '''Returns the response format given in kwargs['format'], or the default format if there is no such key. If kwargs contains 'format', it is removed from kwargs. If the format isn't compatible with Flickr's upload response type, a FlickrError exception is raised. ''' # Figure out the response format format = kwargs.get('format', self.default_format) if format not in rest_parsers and format != 'rest': raise FlickrError('Format %s not supported for uploading ' 'photos' % format) # The format shouldn't be used in the request to Flickr. if 'format' in kwargs: del kwargs['format'] return format def upload(self, filename, callback=None, **kwargs): """Upload a file to flickr. Be extra careful you spell the parameters correctly, or you will get a rather cryptic "Invalid Signature" error on the upload! Supported parameters: filename name of a file to upload callback method that gets progress reports title title of the photo description description a.k.a. caption of the photo tags space-delimited list of tags, ``'''tag1 tag2 "long tag"'''`` is_public "1" or "0" for a public resp. private photo is_friend "1" or "0" whether friends can see the photo while it's marked as private is_family "1" or "0" whether family can see the photo while it's marked as private content_type Set to "1" for Photo, "2" for Screenshot, or "3" for Other. hidden Set to "1" to keep the photo in global search results, "2" to hide from public searches. format The response format. You can only choose between the parsed responses or 'rest' for plain REST. The callback method should take two parameters: ``def callback(progress, done)`` Progress is a number between 0 and 100, and done is a boolean that's true only when the upload is done. """ return self.__upload_to_form(FlickrAPI.flickr_upload_form, filename, callback, **kwargs) def replace(self, filename, photo_id, callback=None, **kwargs): """Replace an existing photo. Supported parameters: filename name of a file to upload photo_id the ID of the photo to replace callback method that gets progress reports format The response format. You can only choose between the parsed responses or 'rest' for plain REST. Defaults to the format passed to the constructor. The callback parameter has the same semantics as described in the ``upload`` function. """ if not photo_id: raise IllegalArgumentException("photo_id must be specified") kwargs['photo_id'] = photo_id return self.__upload_to_form( FlickrAPI.flickr_replace_form, filename, callback, **kwargs) def __upload_to_form(self, form_url, filename, callback, **kwargs): '''Uploads a photo - can be used to either upload a new photo or replace an existing one. form_url must be either ``FlickrAPI.flickr_replace_form`` or ``FlickrAPI.flickr_upload_form``. ''' if not filename: raise IllegalArgumentException("filename must be specified") if not self.token_cache.token: raise IllegalArgumentException("Authentication is required") # Figure out the response format format = self.__extract_upload_response_format(kwargs) # Update the arguments with the ones the user won't have to supply arguments = {'auth_token': self.token_cache.token, 'api_key': self.api_key} arguments.update(kwargs) # Convert to UTF-8 if an argument is an Unicode string kwargs = make_utf8(arguments) if self.secret: kwargs["api_sig"] = self.sign(kwargs) url = "http://%s%s" % (FlickrAPI.flickr_host, form_url) # construct POST data body = Multipart() for arg, value in kwargs.iteritems(): part = Part({'name': arg}, value) body.attach(part) filepart = FilePart({'name': 'photo'}, filename, 'image/jpeg') body.attach(filepart) return self.__wrap_in_parser(self.__send_multipart, format, url, body, callback) def __send_multipart(self, url, body, progress_callback=None): '''Sends a Multipart object to an URL. Returns the resulting unparsed XML from Flickr. ''' LOG.debug("Uploading to %s" % url) request = urllib2.Request(url) request.add_data(str(body)) (header, value) = body.header() request.add_header(header, value) if not progress_callback: # Just use urllib2 if there is no progress callback # function response = urllib2.urlopen(request) return response.read() def __upload_callback(percentage, done, seen_header=[False]): '''Filters out the progress report on the HTTP header''' # Call the user's progress callback when we've filtered # out the HTTP header if seen_header[0]: return progress_callback(percentage, done) # Remember the first time we hit 'done'. if done: seen_header[0] = True response = reportinghttp.urlopen(request, __upload_callback) return response.read() def validate_frob(self, frob, perms): '''Lets the user validate the frob by launching a browser to the Flickr website. ''' auth_url = self.auth_url(perms, frob) webbrowser.open(auth_url, True, True) def get_token_part_one(self, perms="read"): """Get a token either from the cache, or make a new one from the frob. This first attempts to find a token in the user's token cache on disk. If that token is present and valid, it is returned by the method. If that fails (or if the token is no longer valid based on flickr.auth.checkToken) a new frob is acquired. The frob is validated by having the user log into flickr (with a browser). To get a proper token, follow these steps: - Store the result value of this method call - Give the user a way to signal the program that he/she has authorized it, for example show a button that can be pressed. - Wait for the user to signal the program that the authorization was performed, but only if there was no cached token. - Call flickrapi.get_token_part_two(...) and pass it the result value you stored. The newly minted token is then cached locally for the next run. perms "read", "write", or "delete" An example:: (token, frob) = flickr.get_token_part_one(perms='write') if not token: raw_input("Press ENTER after you authorized this program") flickr.get_token_part_two((token, frob)) Also take a look at ``authenticate_console(perms)``. """ # see if we have a saved token token = self.token_cache.token frob = None # see if it's valid if token: LOG.debug("Trying cached token '%s'" % token) try: rsp = self.auth_checkToken(auth_token=token, format='xmlnode') # see if we have enough permissions tokenPerms = rsp.auth[0].perms[0].text if tokenPerms == "read" and perms != "read": token = None elif tokenPerms == "write" and perms == "delete": token = None except FlickrError: LOG.debug("Cached token invalid") self.token_cache.forget() token = None # get a new token if we need one if not token: # get the frob LOG.debug("Getting frob for new token") rsp = self.auth_getFrob(auth_token=None, format='xmlnode') frob = rsp.frob[0].text # validate online self.validate_frob(frob, perms) return (token, frob) def get_token_part_two(self, (token, frob)): """Part two of getting a token, see ``get_token_part_one(...)`` for details.""" # If a valid token was obtained in the past, we're done if token: LOG.debug("get_token_part_two: no need, token already there") self.token_cache.token = token return token LOG.debug("get_token_part_two: getting a new token for frob '%s'" % frob) return self.get_token(frob) def get_token(self, frob): '''Gets the token given a certain frob. Used by ``get_token_part_two`` and by the web authentication method. ''' # get a token rsp = self.auth_getToken(frob=frob, auth_token=None, format='xmlnode') token = rsp.auth[0].token[0].text LOG.debug("get_token: new token '%s'" % token) # store the auth info for next time self.token_cache.token = token return token def authenticate_console(self, perms='read'): '''Performs the authentication, assuming a console program. Gets the token, if needed starts the browser and waits for the user to press ENTER before continuing. ''' (token, frob) = self.get_token_part_one(perms) if not token: raw_input("Press ENTER after you authorized this program") self.get_token_part_two((token, frob)) def set_log_level(level): '''Sets the log level of the logger used by the FlickrAPI module. >>> import flickrapi >>> import logging >>> flickrapi.set_log_level(logging.INFO) ''' import flickrapi.tokencache LOG.setLevel(level) flickrapi.tokencache.LOG.setLevel(level) if __name__ == "__main__": print "Running doctests" import doctest doctest.testmod() print "Tests OK"
Python
'''Exceptions used by the FlickrAPI module.''' class IllegalArgumentException(ValueError): '''Raised when a method is passed an illegal argument. More specific details will be included in the exception message when thrown. ''' class FlickrError(Exception): '''Raised when a Flickr method fails. More specific details will be included in the exception message when thrown. ''' class CancelUpload(Exception): '''Raise this exception in an upload/replace callback function to abort the upload. '''
Python
# -*- encoding: utf-8 -*- '''Module for encoding data as form-data/multipart''' import os import base64 class Part(object): '''A single part of the multipart data. >>> Part({'name': 'headline'}, 'Nice Photo') ... # doctest: +ELLIPSIS <flickrapi.multipart.Part object at 0x...> >>> image = file('tests/photo.jpg') >>> Part({'name': 'photo', 'filename': image}, image.read(), 'image/jpeg') ... # doctest: +ELLIPSIS <flickrapi.multipart.Part object at 0x...> ''' def __init__(self, parameters, payload, content_type=None): self.content_type = content_type self.parameters = parameters self.payload = payload def render(self): '''Renders this part -> List of Strings''' parameters = ['%s="%s"' % (k, v) for k, v in self.parameters.iteritems()] lines = ['Content-Disposition: form-data; %s' % '; '.join(parameters)] if self.content_type: lines.append("Content-Type: %s" % self.content_type) lines.append('') if isinstance(self.payload, unicode): lines.append(self.payload.encode('utf-8')) else: lines.append(self.payload) return lines class FilePart(Part): '''A single part with a file as the payload This example has the same semantics as the second Part example: >>> FilePart({'name': 'photo'}, 'tests/photo.jpg', 'image/jpeg') ... #doctest: +ELLIPSIS <flickrapi.multipart.FilePart object at 0x...> ''' def __init__(self, parameters, filename, content_type): parameters['filename'] = filename imagefile = open(filename, 'rb') payload = imagefile.read() imagefile.close() Part.__init__(self, parameters, payload, content_type) def boundary(): """Generate a random boundary, a bit like Python 2.5's uuid module.""" bytes = os.urandom(16) return base64.b64encode(bytes, 'ab').strip('=') class Multipart(object): '''Container for multipart data''' def __init__(self): '''Creates a new Multipart.''' self.parts = [] self.content_type = 'form-data/multipart' self.boundary = boundary() def attach(self, part): '''Attaches a part''' self.parts.append(part) def __str__(self): '''Renders the Multipart''' lines = [] for part in self.parts: lines += ['--' + self.boundary] lines += part.render() lines += ['--' + self.boundary + "--"] return '\r\n'.join(lines) def header(self): '''Returns the top-level HTTP header of this multipart''' return ("Content-Type", "multipart/form-data; boundary=%s" % self.boundary)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- '''A FlickrAPI interface. See `the FlickrAPI homepage`_ for more info. .. _`the FlickrAPI homepage`: http://flickrapi.sf.net/ ''' __version__ = '1.2' __all__ = ('FlickrAPI', 'IllegalArgumentException', 'FlickrError', 'CancelUpload', 'XMLNode', 'set_log_level', '__version__') __author__ = u'Sybren St\u00fcvel'.encode('utf-8') # Copyright (c) 2007 by the respective coders, see # http://flickrapi.sf.net/ # # This code is subject to the Python licence, as can be read on # http://www.python.org/download/releases/2.5.2/license/ # # For those without an internet connection, here is a summary. When this # summary clashes with the Python licence, the latter will be applied. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import sys import md5 import urllib import urllib2 import mimetools import os.path import logging import copy import webbrowser from flickrapi.tokencache import TokenCache, SimpleTokenCache from flickrapi.xmlnode import XMLNode from flickrapi.multipart import Part, Multipart, FilePart from flickrapi.exceptions import * from flickrapi.cache import SimpleCache from flickrapi import reportinghttp logging.basicConfig() LOG = logging.getLogger(__name__) LOG.setLevel(logging.INFO) def make_utf8(dictionary): '''Encodes all Unicode strings in the dictionary to UTF-8. Converts all other objects to regular strings. Returns a copy of the dictionary, doesn't touch the original. ''' result = {} for (key, value) in dictionary.iteritems(): if isinstance(value, unicode): value = value.encode('utf-8') else: value = str(value) result[key] = value return result def debug(method): '''Method decorator for debugging method calls. Using this automatically sets the log level to DEBUG. ''' LOG.setLevel(logging.DEBUG) def debugged(*args, **kwargs): LOG.debug("Call: %s(%s, %s)" % (method.__name__, args, kwargs)) result = method(*args, **kwargs) LOG.debug("\tResult: %s" % result) return result return debugged # REST parsers, {format: parser_method, ...}. Fill by using the # @rest_parser(format) function decorator rest_parsers = {} def rest_parser(format): '''Function decorator, use this to mark a function as the parser for REST as returned by Flickr. ''' def decorate_parser(method): rest_parsers[format] = method return method return decorate_parser class FlickrAPI: """Encapsulates Flickr functionality. Example usage:: flickr = flickrapi.FlickrAPI(api_key) photos = flickr.photos_search(user_id='73509078@N00', per_page='10') sets = flickr.photosets_getList(user_id='73509078@N00') """ flickr_host = "api.flickr.com" flickr_rest_form = "/services/rest/" flickr_auth_form = "/services/auth/" flickr_upload_form = "/services/upload/" flickr_replace_form = "/services/replace/" def __init__(self, api_key, secret=None, fail_on_error=None, username=None, token=None, format='etree', store_token=True, cache=False): """Construct a new FlickrAPI instance for a given API key and secret. api_key The API key as obtained from Flickr. secret The secret belonging to the API key. fail_on_error If False, errors won't be checked by the FlickrAPI module. Deprecated, don't use this parameter, just handle the FlickrError exceptions. username Used to identify the appropriate authentication token for a certain user. token If you already have an authentication token, you can give it here. It won't be stored on disk by the FlickrAPI instance. format The response format. Use either "xmlnode" or "etree" to get a parsed response, or use any response format supported by Flickr to get an unparsed response from method calls. It's also possible to pass the ``format`` parameter on individual calls. store_token Disables the on-disk token cache if set to False (default is True). Use this to ensure that tokens aren't read nor written to disk, for example in web applications that store tokens in cookies. cache Enables in-memory caching of FlickrAPI calls - set to ``True`` to use. If you don't want to use the default settings, you can instantiate a cache yourself too: >>> f = FlickrAPI(api_key='123') >>> f.cache = SimpleCache(timeout=5, max_entries=100) """ if fail_on_error is not None: LOG.warn("fail_on_error has been deprecated. Remove this " "parameter and just handle the FlickrError exceptions.") else: fail_on_error = True self.api_key = api_key self.secret = secret self.fail_on_error = fail_on_error self.default_format = format self.__handler_cache = {} if token: # Use a memory-only token cache self.token_cache = SimpleTokenCache() self.token_cache.token = token elif not store_token: # Use an empty memory-only token cache self.token_cache = SimpleTokenCache() else: # Use a real token cache self.token_cache = TokenCache(api_key, username) if cache: self.cache = SimpleCache() else: self.cache = None def __repr__(self): '''Returns a string representation of this object.''' return '[FlickrAPI for key "%s"]' % self.api_key __str__ = __repr__ def trait_names(self): '''Returns a list of method names as supported by the Flickr API. Used for tab completion in IPython. ''' try: rsp = self.reflection_getMethods(format='etree') except FlickrError: return None def tr(name): '''Translates Flickr names to something that can be called here. >>> tr(u'flickr.photos.getInfo') u'photos_getInfo' ''' return name[7:].replace('.', '_') return [tr(m.text) for m in rsp.getiterator('method')] @rest_parser('xmlnode') def parse_xmlnode(self, rest_xml): '''Parses a REST XML response from Flickr into an XMLNode object.''' rsp = XMLNode.parse(rest_xml, store_xml=True) if rsp['stat'] == 'ok' or not self.fail_on_error: return rsp err = rsp.err[0] raise FlickrError(u'Error: %(code)s: %(msg)s' % err) @rest_parser('etree') def parse_etree(self, rest_xml): '''Parses a REST XML response from Flickr into an ElementTree object.''' try: import xml.etree.ElementTree as ElementTree except ImportError: # For Python 2.4 compatibility: try: import elementtree.ElementTree as ElementTree except ImportError: raise ImportError("You need to install " "ElementTree for using the etree format") rsp = ElementTree.fromstring(rest_xml) if rsp.attrib['stat'] == 'ok' or not self.fail_on_error: return rsp err = rsp.find('err') raise FlickrError(u'Error: %s: %s' % ( err.attrib['code'], err.attrib['msg'])) def sign(self, dictionary): """Calculate the flickr signature for a set of params. data a hash of all the params and values to be hashed, e.g. ``{"api_key":"AAAA", "auth_token":"TTTT", "key": u"value".encode('utf-8')}`` """ data = [self.secret] for key in sorted(dictionary.keys()): data.append(key) datum = dictionary[key] if isinstance(datum, unicode): raise IllegalArgumentException("No Unicode allowed, " "argument %s (%r) should have been UTF-8 by now" % (key, datum)) data.append(datum) md5_hash = md5.new() md5_hash.update(''.join(data)) return md5_hash.hexdigest() def encode_and_sign(self, dictionary): '''URL encodes the data in the dictionary, and signs it using the given secret, if a secret was given. ''' dictionary = make_utf8(dictionary) if self.secret: dictionary['api_sig'] = self.sign(dictionary) return urllib.urlencode(dictionary) def __getattr__(self, attrib): """Handle all the regular Flickr API calls. Example:: flickr.auth_getFrob(api_key="AAAAAA") etree = flickr.photos_getInfo(photo_id='1234') etree = flickr.photos_getInfo(photo_id='1234', format='etree') xmlnode = flickr.photos_getInfo(photo_id='1234', format='xmlnode') json = flickr.photos_getInfo(photo_id='1234', format='json') """ # Refuse to act as a proxy for unimplemented special methods if attrib.startswith('_'): raise AttributeError("No such attribute '%s'" % attrib) # Construct the method name and see if it's cached method = "flickr." + attrib.replace("_", ".") if method in self.__handler_cache: return self.__handler_cache[method] def handler(**args): '''Dynamically created handler for a Flickr API call''' if self.token_cache.token and not self.secret: raise ValueError("Auth tokens cannot be used without " "API secret") # Set some defaults defaults = {'method': method, 'auth_token': self.token_cache.token, 'api_key': self.api_key, 'format': self.default_format} args = self.__supply_defaults(args, defaults) return self.__wrap_in_parser(self.__flickr_call, parse_format=args['format'], **args) handler.method = method self.__handler_cache[method] = handler return handler def __supply_defaults(self, args, defaults): '''Returns a new dictionary containing ``args``, augmented with defaults from ``defaults``. Defaults can be overridden, or completely removed by setting the appropriate value in ``args`` to ``None``. >>> f = FlickrAPI('123') >>> f._FlickrAPI__supply_defaults( ... {'foo': 'bar', 'baz': None, 'token': None}, ... {'baz': 'foobar', 'room': 'door'}) {'foo': 'bar', 'room': 'door'} ''' result = args.copy() for key, default_value in defaults.iteritems(): # Set the default if the parameter wasn't passed if key not in args: result[key] = default_value for key, value in result.copy().iteritems(): # You are able to remove a default by assigning None, and we can't # pass None to Flickr anyway. if result[key] is None: del result[key] return result def __flickr_call(self, **kwargs): '''Performs a Flickr API call with the given arguments. The method name itself should be passed as the 'method' parameter. Returns the unparsed data from Flickr:: data = self.__flickr_call(method='flickr.photos.getInfo', photo_id='123', format='rest') ''' LOG.debug("Calling %s" % kwargs) post_data = self.encode_and_sign(kwargs) # Return value from cache if available if self.cache and self.cache.get(post_data): return self.cache.get(post_data) url = "http://" + FlickrAPI.flickr_host + FlickrAPI.flickr_rest_form flicksocket = urllib.urlopen(url, post_data) reply = flicksocket.read() flicksocket.close() # Store in cache, if we have one if self.cache is not None: self.cache.set(post_data, reply) return reply def __wrap_in_parser(self, wrapped_method, parse_format, *args, **kwargs): '''Wraps a method call in a parser. The parser will be looked up by the ``parse_format`` specifier. If there is a parser and ``kwargs['format']`` is set, it's set to ``rest``, and the response of the method is parsed before it's returned. ''' # Find the parser, and set the format to rest if we're supposed to # parse it. if parse_format in rest_parsers and 'format' in kwargs: kwargs['format'] = 'rest' LOG.debug('Wrapping call %s(self, %s, %s)' % (wrapped_method, args, kwargs)) data = wrapped_method(*args, **kwargs) # Just return if we have no parser if parse_format not in rest_parsers: return data # Return the parsed data parser = rest_parsers[parse_format] return parser(self, data) def auth_url(self, perms, frob): """Return the authorization URL to get a token. This is the URL the app will launch a browser toward if it needs a new token. perms "read", "write", or "delete" frob picked up from an earlier call to FlickrAPI.auth_getFrob() """ encoded = self.encode_and_sign({ "api_key": self.api_key, "frob": frob, "perms": perms}) return "http://%s%s?%s" % (FlickrAPI.flickr_host, \ FlickrAPI.flickr_auth_form, encoded) def web_login_url(self, perms): '''Returns the web login URL to forward web users to. perms "read", "write", or "delete" ''' encoded = self.encode_and_sign({ "api_key": self.api_key, "perms": perms}) return "http://%s%s?%s" % (FlickrAPI.flickr_host, \ FlickrAPI.flickr_auth_form, encoded) def __extract_upload_response_format(self, kwargs): '''Returns the response format given in kwargs['format'], or the default format if there is no such key. If kwargs contains 'format', it is removed from kwargs. If the format isn't compatible with Flickr's upload response type, a FlickrError exception is raised. ''' # Figure out the response format format = kwargs.get('format', self.default_format) if format not in rest_parsers and format != 'rest': raise FlickrError('Format %s not supported for uploading ' 'photos' % format) # The format shouldn't be used in the request to Flickr. if 'format' in kwargs: del kwargs['format'] return format def upload(self, filename, callback=None, **kwargs): """Upload a file to flickr. Be extra careful you spell the parameters correctly, or you will get a rather cryptic "Invalid Signature" error on the upload! Supported parameters: filename name of a file to upload callback method that gets progress reports title title of the photo description description a.k.a. caption of the photo tags space-delimited list of tags, ``'''tag1 tag2 "long tag"'''`` is_public "1" or "0" for a public resp. private photo is_friend "1" or "0" whether friends can see the photo while it's marked as private is_family "1" or "0" whether family can see the photo while it's marked as private content_type Set to "1" for Photo, "2" for Screenshot, or "3" for Other. hidden Set to "1" to keep the photo in global search results, "2" to hide from public searches. format The response format. You can only choose between the parsed responses or 'rest' for plain REST. The callback method should take two parameters: ``def callback(progress, done)`` Progress is a number between 0 and 100, and done is a boolean that's true only when the upload is done. """ return self.__upload_to_form(FlickrAPI.flickr_upload_form, filename, callback, **kwargs) def replace(self, filename, photo_id, callback=None, **kwargs): """Replace an existing photo. Supported parameters: filename name of a file to upload photo_id the ID of the photo to replace callback method that gets progress reports format The response format. You can only choose between the parsed responses or 'rest' for plain REST. Defaults to the format passed to the constructor. The callback parameter has the same semantics as described in the ``upload`` function. """ if not photo_id: raise IllegalArgumentException("photo_id must be specified") kwargs['photo_id'] = photo_id return self.__upload_to_form( FlickrAPI.flickr_replace_form, filename, callback, **kwargs) def __upload_to_form(self, form_url, filename, callback, **kwargs): '''Uploads a photo - can be used to either upload a new photo or replace an existing one. form_url must be either ``FlickrAPI.flickr_replace_form`` or ``FlickrAPI.flickr_upload_form``. ''' if not filename: raise IllegalArgumentException("filename must be specified") if not self.token_cache.token: raise IllegalArgumentException("Authentication is required") # Figure out the response format format = self.__extract_upload_response_format(kwargs) # Update the arguments with the ones the user won't have to supply arguments = {'auth_token': self.token_cache.token, 'api_key': self.api_key} arguments.update(kwargs) # Convert to UTF-8 if an argument is an Unicode string kwargs = make_utf8(arguments) if self.secret: kwargs["api_sig"] = self.sign(kwargs) url = "http://%s%s" % (FlickrAPI.flickr_host, form_url) # construct POST data body = Multipart() for arg, value in kwargs.iteritems(): part = Part({'name': arg}, value) body.attach(part) filepart = FilePart({'name': 'photo'}, filename, 'image/jpeg') body.attach(filepart) return self.__wrap_in_parser(self.__send_multipart, format, url, body, callback) def __send_multipart(self, url, body, progress_callback=None): '''Sends a Multipart object to an URL. Returns the resulting unparsed XML from Flickr. ''' LOG.debug("Uploading to %s" % url) request = urllib2.Request(url) request.add_data(str(body)) (header, value) = body.header() request.add_header(header, value) if not progress_callback: # Just use urllib2 if there is no progress callback # function response = urllib2.urlopen(request) return response.read() def __upload_callback(percentage, done, seen_header=[False]): '''Filters out the progress report on the HTTP header''' # Call the user's progress callback when we've filtered # out the HTTP header if seen_header[0]: return progress_callback(percentage, done) # Remember the first time we hit 'done'. if done: seen_header[0] = True response = reportinghttp.urlopen(request, __upload_callback) return response.read() def validate_frob(self, frob, perms): '''Lets the user validate the frob by launching a browser to the Flickr website. ''' auth_url = self.auth_url(perms, frob) webbrowser.open(auth_url, True, True) def get_token_part_one(self, perms="read"): """Get a token either from the cache, or make a new one from the frob. This first attempts to find a token in the user's token cache on disk. If that token is present and valid, it is returned by the method. If that fails (or if the token is no longer valid based on flickr.auth.checkToken) a new frob is acquired. The frob is validated by having the user log into flickr (with a browser). To get a proper token, follow these steps: - Store the result value of this method call - Give the user a way to signal the program that he/she has authorized it, for example show a button that can be pressed. - Wait for the user to signal the program that the authorization was performed, but only if there was no cached token. - Call flickrapi.get_token_part_two(...) and pass it the result value you stored. The newly minted token is then cached locally for the next run. perms "read", "write", or "delete" An example:: (token, frob) = flickr.get_token_part_one(perms='write') if not token: raw_input("Press ENTER after you authorized this program") flickr.get_token_part_two((token, frob)) Also take a look at ``authenticate_console(perms)``. """ # see if we have a saved token token = self.token_cache.token frob = None # see if it's valid if token: LOG.debug("Trying cached token '%s'" % token) try: rsp = self.auth_checkToken(auth_token=token, format='xmlnode') # see if we have enough permissions tokenPerms = rsp.auth[0].perms[0].text if tokenPerms == "read" and perms != "read": token = None elif tokenPerms == "write" and perms == "delete": token = None except FlickrError: LOG.debug("Cached token invalid") self.token_cache.forget() token = None # get a new token if we need one if not token: # get the frob LOG.debug("Getting frob for new token") rsp = self.auth_getFrob(auth_token=None, format='xmlnode') frob = rsp.frob[0].text # validate online self.validate_frob(frob, perms) return (token, frob) def get_token_part_two(self, (token, frob)): """Part two of getting a token, see ``get_token_part_one(...)`` for details.""" # If a valid token was obtained in the past, we're done if token: LOG.debug("get_token_part_two: no need, token already there") self.token_cache.token = token return token LOG.debug("get_token_part_two: getting a new token for frob '%s'" % frob) return self.get_token(frob) def get_token(self, frob): '''Gets the token given a certain frob. Used by ``get_token_part_two`` and by the web authentication method. ''' # get a token rsp = self.auth_getToken(frob=frob, auth_token=None, format='xmlnode') token = rsp.auth[0].token[0].text LOG.debug("get_token: new token '%s'" % token) # store the auth info for next time self.token_cache.token = token return token def authenticate_console(self, perms='read'): '''Performs the authentication, assuming a console program. Gets the token, if needed starts the browser and waits for the user to press ENTER before continuing. ''' (token, frob) = self.get_token_part_one(perms) if not token: raw_input("Press ENTER after you authorized this program") self.get_token_part_two((token, frob)) def set_log_level(level): '''Sets the log level of the logger used by the FlickrAPI module. >>> import flickrapi >>> import logging >>> flickrapi.set_log_level(logging.INFO) ''' import flickrapi.tokencache LOG.setLevel(level) flickrapi.tokencache.LOG.setLevel(level) if __name__ == "__main__": print "Running doctests" import doctest doctest.testmod() print "Tests OK"
Python
# -*- encoding: utf-8 -*- '''HTTPHandler that supports a callback method for progress reports. ''' import urllib2 import httplib import logging __all__ = ['urlopen'] logging.basicConfig() LOG = logging.getLogger(__name__) progress_callback = None class ReportingSocket(object): '''Wrapper around a socket. Gives progress report through a callback function. ''' min_chunksize = 10240 def __init__(self, socket): self.socket = socket def sendall(self, bits): '''Sends all data, calling the callback function for every sent chunk. ''' LOG.debug("SENDING: %s..." % bits[0:30]) total = len(bits) sent = 0 chunksize = max(self.min_chunksize, total / 100) while len(bits) > 0: send = bits[0:chunksize] self.socket.sendall(send) sent += len(send) if progress_callback: progress = float(sent) / total * 100 progress_callback(progress, sent == total) bits = bits[chunksize:] def makefile(self, mode, bufsize): '''Returns a file-like object for the socket.''' return self.socket.makefile(mode, bufsize) def close(self): '''Closes the socket.''' return self.socket.close() class ProgressHTTPConnection(httplib.HTTPConnection): '''HTTPConnection that gives regular progress reports during sending of data. ''' def connect(self): '''Connects to a HTTP server.''' httplib.HTTPConnection.connect(self) self.sock = ReportingSocket(self.sock) class ProgressHTTPHandler(urllib2.HTTPHandler): '''HTTPHandler that gives regular progress reports during sending of data. ''' def http_open(self, req): return self.do_open(ProgressHTTPConnection, req) def set_callback(method): '''Sets the callback function to use for progress reports.''' global progress_callback # IGNORE:W0603 if not callable(method): raise ValueError('Callback method must be callable') progress_callback = method def urlopen(url_or_request, callback, body=None): '''Opens an URL using the ProgressHTTPHandler.''' set_callback(callback) opener = urllib2.build_opener(ProgressHTTPHandler) return opener.open(url_or_request, body) if __name__ == '__main__': def upload(progress, finished): '''Upload progress demo''' LOG.info("%3.0f - %s" % (progress, finished)) conn = urlopen("http://www.flickr.com/", 'x' * 10245, upload) data = conn.read() LOG.info("Read data") print data[:100].split('\n')[0]
Python
'''FlickrAPI uses its own in-memory XML representation, to be able to easily use the info returned from Flickr. There is no need to use this module directly, you'll get XMLNode instances from the FlickrAPI method calls. ''' import xml.dom.minidom __all__ = ('XMLNode', ) class XMLNode: """XMLNode -- generic class for holding an XML node >>> xml_str = '''<xml foo="32"> ... <taggy bar="10">Name0</taggy> ... <taggy bar="11" baz="12">Name1</taggy> ... </xml>''' >>> f = XMLNode.parse(xml_str) >>> f.name u'xml' >>> f['foo'] u'32' >>> f.taggy[0].name u'taggy' >>> f.taggy[0]["bar"] u'10' >>> f.taggy[0].text u'Name0' >>> f.taggy[1].name u'taggy' >>> f.taggy[1]["bar"] u'11' >>> f.taggy[1]["baz"] u'12' """ def __init__(self): """Construct an empty XML node.""" self.name = "" self.text = "" self.attrib = {} self.xml = None def __setitem__(self, key, item): """Store a node's attribute in the attrib hash.""" self.attrib[key] = item def __getitem__(self, key): """Retrieve a node's attribute from the attrib hash.""" return self.attrib[key] @classmethod def __parse_element(cls, element, this_node): """Recursive call to process this XMLNode.""" this_node.name = element.nodeName # add element attributes as attributes to this node for i in range(element.attributes.length): an = element.attributes.item(i) this_node[an.name] = an.nodeValue for a in element.childNodes: if a.nodeType == xml.dom.Node.ELEMENT_NODE: child = XMLNode() # Ugly fix for an ugly bug. If an XML element <name /> # exists, it now overwrites the 'name' attribute # storing the XML element name. if not hasattr(this_node, a.nodeName) or a.nodeName == 'name': setattr(this_node, a.nodeName, []) # add the child node as an attrib to this node children = getattr(this_node, a.nodeName) children.append(child) cls.__parse_element(a, child) elif a.nodeType == xml.dom.Node.TEXT_NODE: this_node.text += a.nodeValue return this_node @classmethod def parse(cls, xml_str, store_xml=False): """Convert an XML string into a nice instance tree of XMLNodes. xml_str -- the XML to parse store_xml -- if True, stores the XML string in the root XMLNode.xml """ dom = xml.dom.minidom.parseString(xml_str) # get the root root_node = XMLNode() if store_xml: root_node.xml = xml_str return cls.__parse_element(dom.firstChild, root_node)
Python
# -*- encoding: utf-8 -*- '''Call result cache. Designed to have the same interface as the `Django low-level cache API`_. Heavily inspired (read: mostly copied-and-pasted) from the Django framework - thanks to those guys for designing a simple and effective cache! .. _`Django low-level cache API`: http://www.djangoproject.com/documentation/cache/#the-low-level-cache-api ''' import threading import time class SimpleCache(object): '''Simple response cache for FlickrAPI calls. This stores max 50 entries, timing them out after 120 seconds: >>> cache = SimpleCache(timeout=120, max_entries=50) ''' def __init__(self, timeout=300, max_entries=200): self.storage = {} self.expire_info = {} self.lock = threading.RLock() self.default_timeout = timeout self.max_entries = max_entries self.cull_frequency = 3 def locking(method): '''Method decorator, ensures the method call is locked''' def locked(self, *args, **kwargs): self.lock.acquire() try: return method(self, *args, **kwargs) finally: self.lock.release() return locked @locking def get(self, key, default=None): '''Fetch a given key from the cache. If the key does not exist, return default, which itself defaults to None. ''' now = time.time() exp = self.expire_info.get(key) if exp is None: return default elif exp < now: self.delete(key) return default return self.storage[key] @locking def set(self, key, value, timeout=None): '''Set a value in the cache. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. ''' if len(self.storage) >= self.max_entries: self.cull() if timeout is None: timeout = self.default_timeout self.storage[key] = value self.expire_info[key] = time.time() + timeout @locking def delete(self, key): '''Deletes a key from the cache, failing silently if it doesn't exist.''' if key in self.storage: del self.storage[key] if key in self.expire_info: del self.expire_info[key] @locking def has_key(self, key): '''Returns True if the key is in the cache and has not expired.''' return self.get(key) is not None @locking def __contains__(self, key): '''Returns True if the key is in the cache and has not expired.''' return self.has_key(key) @locking def cull(self): '''Reduces the number of cached items''' doomed = [k for (i, k) in enumerate(self.storage) if i % self.cull_frequency == 0] for k in doomed: self.delete(k) @locking def __len__(self): '''Returns the number of cached items -- they might be expired though. ''' return len(self.storage)
Python
import os, os.path, time, pickle, commands, copy from model import * from settings import pickled_foldername, pickled_filename, \ flickr, log_file_name, mirror_model_pickle_name from utils import * import logging import logging.handlers # Set up a specific logger with our desired output level logger = logging.getLogger('flickrmirror') logger.setLevel(logging.DEBUG) # Add the log message handler to the logger handler = logging.handlers.RotatingFileHandler( log_file_name, maxBytes=20000, backupCount=1) logger.addHandler(handler) class Authenticator: token = None #authentication token perms = 'read' #desired permissions def __init__(self): pass def get_authenticated_perms(self): return flickr.auth_checkToken( auth_token=self.token.find('token').text ).getchildren()[0].find('perms').text def authenticated(self): if self.token is None: return False #elif self.get_authenticated_perms() != self.perms: # return False else: return True def start_authentication(self): logger.info("authentication requested") frob = flickr.auth_getFrob().getchildren()[0].text commands.getoutput("""open "%s" """ % flickr.auth_url(self.perms, frob)) return frob def end_authentication(self, frob): self.token = flickr.auth_getToken(frob=frob).getchildren()[0] flickr.token_cache.token = self.token.find("token").text logger.info("authentication successful") def get_userid(self): return self.token.getchildren()[0].find("user").get('nsid') def get_directory(view, auto_create=False): while True: try: res = view.prompt("Type the full path of the backup directory: ") return Directory(res, auto_create) except: pass class Directory: def __init__(self, path, auto_create = True): self.path = path if auto_create and not os.path.exists(path): os.makedirs(path) elif not os.path.exists(path): raise Exception("Folder not found") def __str__(self): return self.path class Retriever(object): def __init__(self, status_method=lambda x: None): self.status_method = status_method def fill_set_with_photos(self, aset): """ This method fills a set with it's photos """ page = 1 while aset.number_of_photos_and_videos < (aset.num_photos + aset.num_videos): aset.add_photos(flickr.photosets_getPhotos( photoset_id=aset.id, per_page=500, extras="original_format,last_update,media", page=page, media='all' ).find('photoset') ) page += 1 return aset def sets(self, filled=False): self.status_method("Getting photo sets.") sets = [Set(node) for node in flickr.photosets_getList().find('photosets').getchildren()] logger.info("retrieved all photo sets") if filled: set_count = 1 for a_set in sets: self.status_method("%s/%s - Getting photo information for %s" % (set_count, len(sets), a_set.title) ) self.fill_set_with_photos(a_set) set_count += 1 return sets def url(self, photo): if photo.media == 'video': return "http://www.flickr.com/photos/%s/%s/play/orig/%s" % ( photo.owner, photo.id, photo.originalsecret ) else: return "http://farm%s.static.flickr.com/%s/%s_%s%s.%s" % ( photo.farm, photo.server, photo.id, photo.originalsecret, '_o', photo.originalformat ) def pickled_mirror(self, directory): pickle_path = os.path.join(directory, pickled_foldername) mirror_file_name = os.path.join(pickle_path, mirror_model_pickle_name) if has_pickle_settings(directory): self.status_method("Flickr settings found. Loading....") logger.info("loading mirror model from %s" % mirror_file_name) mirror = MirrorModel().load(eval(open(mirror_file_name, 'rb').read())) for fi in [f for f in os.listdir(pickle_path) if f != mirror_model_pickle_name and f.endswith('.dict')]: file_path = os.path.join(pickle_path, fi) if os.path.isfile(file_path): logger.info("loading set from %s" % file_path) fileobject = open(file_path, 'rb') logger.info("loaded file") value = eval(fileobject.read()) logger.info("converted to value") s = Set().load(value) logger.info("created Set") self.status_method("Loaded set %s information from file." % (s.title)) mirror.sets.append(s) return mirror else: mirror = MirrorModel(self.sets(filled=True)) mirror.last_updated = int(time.time()) #save it right away since it is the first time loading it... Storer().pickle_mirror(mirror, directory, self.status_method) return mirror def has_pickle_settings(directory): pickle_path = os.path.join(directory, pickled_foldername) mirror_file_name = os.path.join(pickle_path, mirror_model_pickle_name) return os.path.exists(pickle_path) and os.path.exists(mirror_file_name) class Storer(object): def pickle_mirror(self, mirror, directory, status_method): logger.info("starting pickling of mirror objects") pickle_path = os.path.join(directory, pickled_foldername) mirror_file_name = os.path.join(pickle_path, mirror_model_pickle_name) if not os.path.exists(pickle_path): os.mkdir(pickle_path) # save main mirror object logger.info("storing main mirror object") open(mirror_file_name, 'wb').write(str(mirror.dump())) logger.info("going through sets and seeing if they need to be saved.") for set in mirror.sets: if set.dirty: set.dirty = False set_filename = os.path.join(pickle_path, normalize(set.title) + '.dict') status_method("Saving set %s information..." % set.title) set.file_saved_location = set_filename open(set_filename, 'wb').write(str(set.dump())) return pickle_path
Python
from controller import MirrorController from view.gui import GUIView import wx def startapp(): app = wx.App() view = GUIView() app.MainLoop()
Python
import wx class HasEvents(object): def __getattr__(self, name): """ register_click_event_for_authenticate_button ['register', 'button', 'event', 'for', 'authenticate', 'button'] """ items = name.split("_") if items[0] == "register": attr = getattr(self, '_'.join(items[4:])) event = getattr(wx, 'EVT_' + items[1]) return lambda handler: self.Bind(event, lambda self, event: handler(), id=attr.GetId()) class MirrorButton(wx.Button): start_text = "Start/Resume/Update" pause_text = "Pause" def __init__(self, parent): wx.Button.__init__(self, parent, -1, self.start_text, (100, 80), (200, 30)) def paused(self): self.SetLabel(self.start_text) def started(self): self.SetLabel(self.pause_text) def active(self): return self.GetLabel() == self.pause_text class MainFrame(wx.Frame): def __init__(self, view, parent=None, id=-1, title="flickrmirror", size=(500, 150)): wx.Frame.__init__(self, parent, id, title, size=size) self.view = view #self.setup_menu_bar() self.CreateStatusBar() self.authenticate_button = \ wx.Button(self, -1, "Authenticate", (20, 20), (120, 30)) self.authenticate_text = \ wx.StaticText(self, -1, '', (150, 23)) self.Bind( wx.EVT_BUTTON, self.view.authenticate_button_clicked, id=self.authenticate_button.GetId() ) self.backup_directory_button = \ wx.Button(self, -1, "Mirror Location", (20, 50), (120, 30)) self.backup_directory_text = \ wx.StaticText(self, -1, '', (150, 53)) self.Bind( wx.EVT_BUTTON, self.view.backup_directory_button_clicked, id=self.backup_directory_button.GetId() ) self.mirror_button = MirrorButton(self) self.Bind( wx.EVT_BUTTON, self.view.mirror_button_clicked, id=self.mirror_button.GetId() ) self.Centre() self.Show(True) def setup_menu_bar(self): menubar = wx.MenuBar() file = wx.Menu() file.Append(1, '&Quit', 'Exit flickrmirror') menubar.Append(file, '&File') self.SetMenuBar(menubar) #self.Bind(wx.EVT_MENU, self.OnClose, id=1)
Python
from flickrmirror.view.base import IView from flickrmirror.controller import MirrorController from flickrmirror.tools import * from frames import * import wx import threading class GUIView: def __init__(self): self.controller = MirrorController(self) self.main_frame = MainFrame(self) self.update_information() def authenticate_button_clicked(self, event): self.controller.authenticate() self.update_information() def update_information(self): bd = self.controller.backup_directory if bd is None: self.main_frame.backup_directory_text.SetLabel("No folder selected.") else: self.main_frame.backup_directory_text.SetLabel(str(bd)) authenticated = self.controller.authenticator.authenticated() if authenticated: self.main_frame.authenticate_text.SetLabel("You are authenticated with flickr.") else: self.main_frame.authenticate_text.SetLabel("You are NOT authenticated with flickr.") def run_mirror(self): class RunMirrorThread(threading.Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, view=None): self.view = view threading.Thread.__init__(self, group, target, name, args, kwargs) def run(self): self.view.started_mirroring() self.view.controller.mirror() self.view.ended_mirroring() thread = RunMirrorThread(view=self) thread.start() def started_mirroring(self): self.main_frame.mirror_button.started() self.main_frame.authenticate_button.Disable() self.main_frame.backup_directory_button.Disable() def ended_mirroring(self): self.main_frame.mirror_button.paused() self.main_frame.authenticate_button.Enable() self.main_frame.backup_directory_button.Enable() def mirror_button_clicked(self, event): if self.main_frame.mirror_button.active(): self.ended_mirroring() else: if self.controller.authenticator.authenticated() and self.controller.backup_directory is not None: self.run_mirror() else: wx.MessageBox("You must be authenticated with flickr and select a backup location") def backup_directory_button_clicked(self, event): d = wx.DirDialog(self.main_frame, "Please enter the backup location") d.ShowModal() self.controller.backup_directory = d.GetPath() self.update_information() def prompt(self, msg, result=True): if result: wx.TextEntryDialog(self.main_frame, msg).GetValue().strip() else: wx.MessageBox(msg) def status(self, msg): self.main_frame.SetStatusText(msg)
Python
from view import GUIView
Python
from flickrmirror.exceptions import NotImplementedException from flickrmirror.tools import logger class IView: """ base view for all the views here... interface type deal... """ name = property(NotImplementedException) def __init__(): raise NotImplementedException("""Constructor is not initialized...""") def prompt(msg, result=True): raise NotImplementedException("""prompt method not implemented""") def status(msg): raise NotImplementedException("""status method not implemented""") def log(msg): logger.info(msg)
Python
from base import IView from flickrmirror.controller import MirrorController from flickrmirror.tools import * class CLIView(IView): name = 'cli' def __init__(self): self.controller = MirrorController(self) self.menu() def menu(self): res = '0' while res not in ['1', '2', '3', '4', '5', '6', '7', '8', '9']: print """ flickrmirror ----------- backup location : %s authenticated : %s total photos : %s Options ----------- 1 : set backup location(required) 2 : authenticate with flickr(required) 3 : load set information 4 : list managed sets 5 : filter set(s) -- seperate by comma, '*' filters everything out 6 : remove filtered sets(s) -- seperate by comma, '*' un-filters everything 7 : save settings 8 : *Run Mirror(this will retrieve any photos not currently on the file system) 9 : exit """ % ( str(self.controller.backup_directory), self.controller.authenticator.authenticated(), self.controller.get_photo_count() ) res = raw_input("Make your selection: ").strip() if res == '1': self.controller.backup_directory = get_directory(self) self.menu() elif res == '2': self.controller.authenticate() self.menu() elif res == '3': self.controller.load() self.controller.synchronize_server() self.menu() elif res == '4': if self.controller.mirror_model is None: print "sets not loaded yet..." self.menu() print "-----------\nManaged Sets" for s in self.controller.mirror_model.filtered_sets(): print "Title: '%s', id: '%s', %i photos" % (s.title, s.id, s.number_of_photos_and_videos) self.menu() elif res == '5': set = self.prompt("Enter set name or id seperated by a comma: ") self.controller.filter_set(set) self.menu() elif res == '6': set = self.prompt("Enter set name or id seperated by a comma: ") self.controller.unfilter_set(set) self.menu() elif res == '7': self.controller.save() self.menu() elif res == '8': self.controller.mirror() self.menu() elif res == '9': return else: self.menu() def ready(self): return len(str(self.controller.backup_directory)) > 0 and \ self.controller.authenticator.authenticated() def prompt(self, msg, result=True): return raw_input(msg).strip() def log(msg): pass def status(self, msg, nl=True): if nl: print msg else: print msg,
Python
import os from exceptions import NotImplementedException from utils import * class DictSerializableModel(object): def dump(self): raise NotImplementedException() def load(self): raise NotImplementedException() class MirrorModel(DictSerializableModel): def __init__(self, sets=None): if sets is not None: #should only be none when serializing self.sets = sets self.last_updated = 0 self.filtered = [] def dump(self): return { 'sets' : [], 'last_updated' : self.last_updated, 'filtered' : self.filtered } def load(self, value): self.sets = value['sets'] self.last_updated = value['last_updated'] self.filtered = value['filtered'] return self def filtered_sets(self): sets = [] for s in self.sets: if s.id not in self.filtered: sets.append(s) return sets def has_set(self, id): for set in self.sets: if set.id == id or id == set.title: return True return False def get_set(self, id): for set in self.sets: if set.id == id or id == set.title: return set return False class Node(object): def __init__(self, node): self.node = node def get_node(self): return None def set_node(self, node): self.set_id(node) self.set_title(node) node = property(get_node, set_node) def set_id(self, node): self.id = node.get('id') def set_title(self, node): raise NotImplementedException("Must implement set_title on object") class Set(Node, DictSerializableModel): def __init__(self, node=None): if node is not None: #should only be none when serializing self.node = node self.photos = [] self.dirty = True self.file_saved_location = '' def dump(self): return { 'photos' : [photo.dump() for photo in self.photos], 'dirty' : self.dirty, 'id' : self.id, 'title' : self.title, 'num_photos' : self.num_photos, 'num_videos' : self.num_videos, 'file_saved_location' : self.file_saved_location } def load(self, value): self.photos = [Photo().load(p, self) for p in value['photos']] self.dirty = value['dirty'] self.id = value['id'] self.title = value['title'] self.num_photos = value['num_photos'] self.num_videos = value['num_videos'] self.file_saved_location = value['file_saved_location'] return self def delete(self): logger.info("Deleting set %s" % self.id) for photo in self.photos: photo.delete() if os.path.exists(self.file_saved_location): logger.info("removing set settings at %s" % (self.title, self.file_saved_location)) os.remove(self.file_saved_location) del self def update(self, otherset): if self.title != otherset.title: self.title = otherset.title self.dirty = True if self.num_photos != otherset.num_photos: self.num_photos = otherset.num_photos self.dirty = True if self.num_videos != otherset.num_videos: self.num_videos = otherset.num_videos self.dirty = True def append_photo(self, photo): self.photos.append(photo) self.dirty = True def remove_photo(self, photo): self.photos.remove(photo) self.dirty = True def get_photo(self, id): for photo in self.photos: if photo.id == id: return photo return False def has_photo(self, id): for photo in self.photos: if photo.id == id: return True return False def add_photos(self, set_node): for photo in set_node.getchildren(): self.append_photo(Photo(set_node, photo, self)) self.dirty = True def get_node(self): return None def set_node(self, node): self.dirty = True Node.set_node(self, node) self.set_number_of_photos(node) self.set_number_of_videos(node) node = property(get_node, set_node) def set_title(self, node): self.title = node.find('title').text def set_number_of_photos(self, node): self.num_photos = int(node.get('photos')) def set_number_of_videos(self, node): self.num_videos = int(node.get('videos')) def get_number_of_photos_and_videos(self): return len(self.photos) number_of_photos_and_videos = property(get_number_of_photos_and_videos) def __str__(self): return "<flickr Set>%s, id: %s, photos: %i</flickr Set>" % ( hasattr(self, 'title') and self.title or '', hasattr(self, 'id') and self.id or '', hasattr(self, 'number_of_photos_and_videos') and self.number_of_photos_and_videos or 0 ) class Photo(Node, DictSerializableModel): def __init__(self, set_node=None, photo_node=None, parent=None): if set_node is not None and photo_node is not None and parent is not None: # should only be none when serializing self.set = parent self.set_info(set_node, photo_node) self.location = '' self.dirty = True def dump(self): return { 'owner' : self.owner, 'title' : self.title, 'id' : self.id, 'secret' : self.secret, 'media' : self.media, 'dirty' : self.dirty, 'originalsecret' : self.originalsecret, 'farm' : self.farm, 'server' : self.server, 'originalformat' : self.originalformat, 'lastupdate' : self.lastupdate, 'location' : self.location } def load(self, value, parent): self.set = parent for k, v in value.items(): setattr(self, k, v) return self def delete(self): self.set.dirty = True if os.path.exists(self.location): os.remove(self.location) del self def get_dirty(self): if not os.path.exists(self.location): return True else: return self._dirty def set_dirty(self, value): self._dirty = value self.set.dirty = True dirty = property(get_dirty, set_dirty) def set_info(self, set_node, photo_node): self.set.dirty = True Node.set_node(self, photo_node) self.set_secret(photo_node) self.set_originalsecret(photo_node) self.set_farm(photo_node) self.set_originalformat(photo_node) self.set_server(photo_node) self.set_lastupdate(photo_node) self.set_media(photo_node) self.set_owner(set_node) def set_owner(self, node): self.owner = node.get('owner') def set_title(self, node): self.title = node.get('title') def set_secret(self, node): self.secret = node.get('secret') def set_media(self, node): self.media = node.get('media') def set_originalsecret(self, node): self.originalsecret = node.get('originalsecret') def set_farm(self, node): self.farm = node.get('farm') def set_server(self, node): self.server = node.get('server') def set_originalformat(self, node): self.originalformat = node.get('originalformat') def set_lastupdate(self, node): self.lastupdate = int(node.get('lastupdate')) def get_filename(self): if self.media == 'video': return "%s-%s.avi" % (self.id, normalize(self.title)) else: return "%s-%s.%s" % (self.id, normalize(self.title), self.originalformat) filename = property(get_filename) def __str__(self): return "<flickr Photo>%s, in set %s</flickr Photo>" % ( hasattr(self, 'title') and self.title or '', hasattr(self, 'set') and self.set or '' )
Python
# this will control a user's fake photo collection # and prevent it from actually calling flickr for # the results. # # As long as all the results are structured correctly, # everything should work the same.... # # The fake user's photo collection will look like this, # Sets: # -Hawaii # -20 photos # -id 1 # -secrete 12345 # -Family Photos # -500 photos # -id 2 # -secret 54321 # import xml.etree.ElementTree as ElementTree number_of_photosets = 3 def photosets_getList(*args, **kwargs): return ElementTree.fromstring(""" <photosets cancreate="1"> <photoset id="1" primary="2483" secret="abcdef" server="8" photos="4" farm="1"> <title>Test</title> <description>foo</description> </photoset> <photoset id="4" primary="1234" secret="832659" server="3" photos="12" farm="1"> <title>My Set</title> <description>bar</description> </photoset> </photosets>""") def photos_recentlyUpdated(*args, **kwargs): return ElementTree.fromstring(""" <photos page="1" pages="1" perpage="100" total="2"> <photo id="169885459" owner="35034348999@N01" secret="c85114c195" server="46" title="Doubting Michael" ispublic="1" isfriend="0" isfamily="0" lastupdate="1150755888" /> <photo id="85022332" owner="35034348999@N01" secret="23de6de0c0" server="41" title="&quot;Do you think we're allowed to tape stuff to the walls?&quot;" ispublic="1" isfriend="0" isfamily="0" lastupdate="1150564974" /> </photos>""") def auth_checkToken(*args, **kwargs): return ElementTree.fromstring(""" <auth> <token>976598454353455</token> <perms>read</perms> <user nsid="12037949754@N01" username="Bees" fullname="Cal H" /> </auth>""") def auth_getFrob(*args, **kwargs): return ElementTree.fromstring("""<frob>746563215463214621</frob>""") def auth_getToken(*args, **kwargs): return ElementTree.fromstring(""" <auth> <token>976598454353455</token> <perms>write</perms> <user nsid="12037949754@N01" username="Bees" fullname="Cal H" /> </auth>""") def photosets_getPhotos(*args, **kwargs): return ElementTree.fromstring(""" <photoset id="4" primary="2483" page="1" perpage="500" pages="1" total="2"> <photo id="2484" secret="123456" server="1" title="my photo" isprimary="0" /> <photo id="2483" secret="123456" server="1" title="flickr rocks" isprimary="1" /> </photoset>""")
Python
import flickrapi import os.path key = "57ed171ead518050f3802d2ef8620621" secret = "15863af84276ca85" pickled_filename = '.flickrmirror' pickled_foldername = '__flickrmirrorsettings__' mirror_model_pickle_name = '__mirror_model.dict' flickr = flickrapi.FlickrAPI(key, secret) log_file_name = os.path.join("/tmp", "flickrmirror.log")
Python
def normalize(name): bad_letters_skip = """'"/\\,<>?[]{}+=()*&^%$#@!~`""" bad_letters_replace = """ :;""" for b in bad_letters_skip: name = name.replace(b, '') for b in bad_letters_replace: name = name.replace(b, '-') return name.strip().replace('--', '-')
Python
class NotImplementedException(Exception): """ Method not implemented """
Python
# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: from pkgutil import extend_path __path__ = extend_path(__path__, __name__)
Python
from flickrmirror.view.cli import CLIView view = CLIView()
Python
import commands, urllib, os.path, os, pickle, time, model, datetime, shutil from tools import * from settings import flickr from utils import * class MirrorController: """ """ def __init__(self, view): self.view = view self.authenticator = Authenticator() self.retrieve = Retriever(self.view.status) self._backup_directory = None self.mirror_model = None def save(self): if self.mirror_model is not None: loc = Storer().pickle_mirror(self.mirror_model, str(self.backup_directory), self.view.status) else: self.view.prompt("You haven't even loaded your settings yet!", False) def load(self): if self.backup_directory is None: self.view.prompt("You must select a backup directory before you load your data!", False) return if self.mirror_model is None: self.mirror_model = self.retrieve.pickled_mirror(str(self.backup_directory)) self.view.status("Loaded flickrmirror settings.") def get_photo_count(self): if self.mirror_model: num = 0 for s in self.mirror_model.filtered_sets(): num += s.number_of_photos_and_videos return num else: return 0 def authenticate(self): if not self.authenticator.authenticated(): r = self.authenticator.start_authentication() self.view.prompt("Press enter once you're authenticated.", False) self.authenticator.end_authentication(r) def filter_set(self, sets): if sets == "*": self.mirror_model.filtered = [] for set in self.mirror_model.sets: self.mirror_model.filtered.append(set.id) self.view.status("Filtered all sets.") else: sets = sets.split(',') for set_id_or_title in sets: set_id_or_title = set_id_or_title.strip() set = self.mirror_model.get_set(set_id_or_title) if set and set.id not in self.mirror_model.filtered: self.mirror_model.filtered.append(set.id) self.view.status("Filtered set %s" % set.title) self.save() def unfilter_set(self, sets): if sets == "*": self.mirror_model.filtered = [] else: sets = sets.split(',') for set_id_or_title in sets: set_id_or_title = set_id_or_title.strip() set = self.mirror_model.get_set(set_id_or_title) if set.id in self.mirror_model.filtered: self.mirror_model.filtered.remove(set.id) self.view.status("Un-filtered set %s" % set.title) self.save() def mirror(self): self.load() self.view.status("Getting updated flickr information.") self.synchronize_server() self.view.status("Synchronizing with local hard drive.") self.synchronize_local() self.save() def synchronize_server(self): """ big, nasty method... needs a lot of work... Don't worry about last updated... There is no way of knowing if sets get updated or anything so just get a new list of sets and compare """ updated_mirror = MirrorModel(self.retrieve.sets(filled=True)) sets_to_add = [] for s in updated_mirror.sets: if self.mirror_model.has_set(s.id): current_set = self.mirror_model.get_set(s.id) current_set.update(s) for p in s.photos: cp = current_set.get_photo(p.id) if not cp: current_set.append_photo(p) elif cp.lastupdate < p.lastupdate: current_set.remove_photo(cp) cp.delete() #so it'll be updated... maybe a better way? current_set.append_photo(p) else: sets_to_add.append(s) self.mirror_model.sets.extend(sets_to_add) sets_to_remove = [] for current_set in self.mirror_model.sets: new_set = updated_mirror.get_set(current_set.id) if not new_set: sets_to_remove.append(current_set) else: for photo in current_set.photos: new_photo = new_set.get_photo(photo.id) if not new_photo: current_set.remove_photo(photo) photo.delete() for set in sets_to_remove: self.mirror_model.sets.remove(set) set.delete() self.mirror_model.last_updated = int(time.time()) self.save() # don't save until the end in case something goes wrong... def get_dirty_photos(self): dirty_photos = [] for set in self.mirror_model.filtered_sets(): for photo in set.photos: if photo.dirty: dirty_photos.append( (photo, set) ) return dirty_photos def retrieve_photo(self, photo, set, report=lambda x,y,z: x): set_storage = Directory(os.path.join(str(self.backup_directory), normalize(set.title))) self.download(photo, set_storage, report) self.save() def synchronize_local(self): dirty_photos = self.get_dirty_photos() for i in range(0, len(dirty_photos)): photo, set = dirty_photos[i] self.view.status("%i/%i - Downloading photo %s from set %s." % ( i+1, len(dirty_photos), photo.title, set.title ) ) self.retrieve_photo(photo, set) def download(self, photo, storage, report=lambda x,y,z: x): url = self.retrieve.url(photo) file_location = os.path.join(storage.path, photo.filename) if os.path.exists(file_location): self.view.status("%s already exists. Skipping download." % photo.title) else: logger.info("downloading %s from %s" % (str(photo), url)) #save to temp file first and then move to location so incomplete downloads are not saved tmp_file = urllib.urlretrieve(url, file_location, report)[0] shutil.move(tmp_file, file_location) self.view.status("Saved photo %s to %s." % (photo.title, file_location)) logger.info("saved photo %s to %s" % (photo.title, file_location)) photo.location = file_location photo.dirty = False def mirror_set(self, a_set): if type(a_set) == str: a_set = self.retrieve.set(a_set) self.retrieve.fill_set_with_photos(a_set) for photo in a_set.photos: self.view.status('retrieving photo info %s' % photo.title) self.retrieve.fill_photo_info(photo) storage = Directory(os.path.join(str(self.backup_directory), normalize(a_set.title))) for index in range(0, len(a_set.photos)): photo = a_set.photos[index] self.view.status("backing up photo %s(%s/%s)" % ( photo.title, index + 1, len(a_set.photos) ), False) self.download(photo, storage) self.view.status("done...") def get_backup_directory(self): return self._backup_directory def set_backup_directory(self, value): while not os.path.exists(value): value = raw_input("Enter your backup directory: ").strip() self._backup_directory = Directory(value, False) backup_directory = property(get_backup_directory, set_backup_directory)
Python
import flickrapi from settings import key, secret
Python
import sys, os.path from setuptools import setup, find_packages version = "0.1b2" setup( name="flickrmirror", version=version, description="A library that allows you to easily mirror your flickr set colletion to your hard drive.", long_description=open("README.txt").read() + "\n" + open(os.path.join("docs", "HISTORY.txt")).read(), author="Nathan Van Gheem", author_email="vangheem@gmail.com", maintainer="Nathan Van Gheem", maintainer_email="vangheem@gmail.com", packages=find_packages(exclude=['tests']), url="http://code.google.com/p/flickrmirror/", include_package_data=True, namespace_packages=['flickrmirror'], zip_safe=False, include_package_data=True, install_requires=[ "flickrapi" ] )
Python
import os, os.path, time, pickle, commands, copy from model import * from settings import pickled_foldername, pickled_filename, \ flickr, log_file_name, mirror_model_pickle_name from utils import * import logging import logging.handlers # Set up a specific logger with our desired output level logger = logging.getLogger('flickrmirror') logger.setLevel(logging.DEBUG) # Add the log message handler to the logger handler = logging.handlers.RotatingFileHandler( log_file_name, maxBytes=20000, backupCount=1) logger.addHandler(handler) class Authenticator: token = None #authentication token perms = 'read' #desired permissions def __init__(self): pass def get_authenticated_perms(self): return flickr.auth_checkToken( auth_token=self.token.find('token').text ).getchildren()[0].find('perms').text def authenticated(self): if self.token is None: return False #elif self.get_authenticated_perms() != self.perms: # return False else: return True def start_authentication(self): logger.info("authentication requested") frob = flickr.auth_getFrob().getchildren()[0].text commands.getoutput("""open "%s" """ % flickr.auth_url(self.perms, frob)) return frob def end_authentication(self, frob): self.token = flickr.auth_getToken(frob=frob).getchildren()[0] flickr.token_cache.token = self.token.find("token").text logger.info("authentication successful") def get_userid(self): return self.token.getchildren()[0].find("user").get('nsid') def get_directory(view, auto_create=False): while True: try: res = view.prompt("Type the full path of the backup directory: ") return Directory(res, auto_create) except: pass class Directory: def __init__(self, path, auto_create = True): self.path = path if auto_create and not os.path.exists(path): os.makedirs(path) elif not os.path.exists(path): raise Exception("Folder not found") def __str__(self): return self.path class Retriever(object): def __init__(self, status_method=lambda x: None): self.status_method = status_method def fill_set_with_photos(self, aset): """ This method fills a set with it's photos """ page = 1 while len(aset.photos) < aset.number_of_photos_and_videos: aset.add_photos(flickr.photosets_getPhotos( photoset_id=aset.id, per_page=500, extras="original_format,last_update,media", page=page, media='all' ).find('photoset') ) page += 1 return aset def get_all_sets(self, filled=False): self.status_method("Getting photo sets.") sets = [Set(node) for node in flickr.photosets_getList().find('photosets').getchildren()] logger.info("retrieved all photo sets") if filled: set_count = 1 for a_set in sets: self.status_method("%s/%s - Getting photo information for %s" % (set_count, len(sets), a_set.title) ) self.fill_set_with_photos(a_set) set_count += 1 return sets def url(self, photo): if photo.media == 'video': return "http://www.flickr.com/photos/%s/%s/play/orig/%s" % ( photo.owner, photo.id, photo.originalsecret ) else: return "http://farm%s.static.flickr.com/%s/%s_%s%s.%s" % ( photo.farm, photo.server, photo.id, photo.originalsecret, '_o', photo.originalformat ) def get_pickled_mirror(self, directory): pickler = Pickler(directory, self.status_method) if pickler.has_pickle_settings(): self.status_method("Flickr settings found. Loading....") return pickler.load_pickle() else: return pickler.start_new() class Pickler(object): def __init__(self, directory, status_method): self.status_method = status_method self.directory = directory self.pickle_path = os.path.join(directory, pickled_foldername) self.mirror_file_name = os.path.join(self.pickle_path, mirror_model_pickle_name) def has_pickle_settings(self): return os.path.exists(self.pickle_path) and os.path.exists(self.mirror_file_name) def load_pickle(self): logger.info("loading mirror model from %s" % self.mirror_file_name) mirror = MirrorModel().load(eval(open(self.mirror_file_name, 'rb').read())) files = [f for f in os.listdir(self.pickle_path) if f != mirror_model_pickle_name and f.endswith('.dict')] for fi in files: file_path = os.path.join(self.pickle_path, fi) if os.path.isfile(file_path): logger.info("loading set from %s" % file_path) fileobject = open(file_path, 'rb') logger.info("loaded file") value = eval(fileobject.read()) logger.info("converted to value") s = Set().load(value) logger.info("created Set") self.status_method("Loaded set %s information from file." % (s.title)) mirror.sets.append(s) return mirror def start_new(self): mirror = MirrorModel(Retriever(self.status_method).get_all_sets(filled=True)) mirror.last_updated = int(time.time()) #save it right away since it is the first time loading it... self.save_pickle(mirror) return mirror def save_pickle(self, mirror): logger.info("starting pickling of mirror objects") if not os.path.exists(self.pickle_path): os.mkdir(self.pickle_path) # save main mirror object logger.info("storing main mirror object") open(self.mirror_file_name, 'wb').write(str(mirror.dump())) logger.info("going through sets and seeing if they need to be saved.") for set in mirror.sets: if set.dirty: set.dirty = False set_filename = os.path.join(self.pickle_path, normalize(set.title) + '.dict') self.status_method("Saving set %s information..." % set.title) set.file_saved_location = set_filename open(set_filename, 'wb').write(str(set.dump())) return self.pickle_path class Storer(object): def pickle_mirror(self, mirror, directory, status_method): return Pickler(directory, status_method).save_pickle(mirror)
Python
from flickrmirror.exceptions import NotImplementedException from flickrmirror.tools import logger class IView: """ base view for all the views here... interface type deal... """ name = property(NotImplementedException) def __init__(): raise NotImplementedException("""Constructor is not initialized...""") def prompt(msg, result=True): raise NotImplementedException("""prompt method not implemented""") def status(msg): raise NotImplementedException("""status method not implemented""") def log(msg): logger.info(msg)
Python
from base import IView from flickrmirror.controller import MirrorController from flickrmirror.tools import * class CLIView(IView): name = 'cli' def __init__(self): self.controller = MirrorController(self) self.menu() def menu(self): res = '0' while res not in ['1', '2', '3', '4', '5', '6', '7', '8', '9']: print """ flickrmirror ----------- backup location : %s authenticated : %s total photos : %s Options ----------- 1 : set backup location(required) 2 : authenticate with flickr(required) 3 : load set information 4 : list managed sets 5 : filter set(s) -- seperate by comma, '*' filters everything out 6 : remove filtered sets(s) -- seperate by comma, '*' un-filters everything 7 : save settings 8 : *Run Mirror(this will retrieve any photos not currently on the file system) 9 : exit """ % ( str(self.controller.backup_directory), self.controller.authenticator.authenticated(), self.controller.get_photo_count() ) res = raw_input("Make your selection: ").strip() if res == '1': self.controller.backup_directory = get_directory(self) self.menu() elif res == '2': self.controller.authenticate() self.menu() elif res == '3': self.controller.load() self.menu() elif res == '4': if self.controller.mirror_model is None: print "sets not loaded yet..." self.menu() print "-----------\nManaged Sets" for s in self.controller.mirror_model.filtered_sets(): print "Title: '%s', id: '%s', %i photos" % (s.title, s.id, len(s.photos)) self.menu() elif res == '5': set = self.prompt("Enter set name or id seperated by a comma: ") self.controller.filter_set(set) self.menu() elif res == '6': set = self.prompt("Enter set name or id seperated by a comma: ") self.controller.unfilter_set(set) self.menu() elif res == '7': self.controller.save() self.menu() elif res == '8': self.controller.synchronize_local() self.menu() elif res == '9': return else: self.menu() def ready(self): return len(str(self.controller.backup_directory)) > 0 and \ self.controller.authenticator.authenticated() def prompt(self, msg, result=True): return raw_input(msg).strip() def log(msg): pass def status(self, msg, nl=True): if nl: print msg else: print msg,
Python
import os from exceptions import NotImplementedException from utils import * class DictSerializableModel(object): def dump(self): raise NotImplementedException() def load(self): raise NotImplementedException() class MirrorModel(DictSerializableModel): def __init__(self, sets=None): if sets is not None: #should only be none when serializing self.sets = sets self.last_updated = 0 self.filtered = [] def dump(self): return { 'sets' : [], 'last_updated' : self.last_updated, 'filtered' : self.filtered } def load(self, value): self.sets = value['sets'] self.last_updated = value['last_updated'] self.filtered = value['filtered'] return self def filtered_sets(self): sets = [] for s in self.sets: if s.id not in self.filtered: sets.append(s) return sets def has_set(self, id): for set in self.sets: if set.id == id or id == set.title: return True return False def get_set(self, id): for set in self.sets: if set.id == id or id == set.title: return set return False class Node(object): def __init__(self, node): self.node = node def get_node(self): return None def set_node(self, node): self.set_id(node) self.set_title(node) node = property(get_node, set_node) def set_id(self, node): self.id = node.get('id') def set_title(self, node): raise NotImplementedException("Must implement set_title on object") class Set(Node, DictSerializableModel): def __init__(self, node=None): if node is not None: #should only be none when serializing self.node = node self.photos = [] self.dirty = True self.file_saved_location = '' def dump(self): return { 'photos' : [photo.dump() for photo in self.photos], 'dirty' : self.dirty, 'id' : self.id, 'title' : self.title, 'num_photos' : self.num_photos, 'num_videos' : self.num_videos, 'file_saved_location' : self.file_saved_location } def load(self, value): self.photos = [Photo().load(p, self) for p in value['photos']] self.dirty = value['dirty'] self.id = value['id'] self.title = value['title'] self.num_photos = value['num_photos'] self.num_videos = value['num_videos'] self.file_saved_location = value['file_saved_location'] return self def delete(self): logger.info("Deleting set %s" % self.id) for photo in self.photos: photo.delete() if os.path.exists(self.file_saved_location): logger.info("removing set settings at %s" % (self.title, self.file_saved_location)) os.remove(self.file_saved_location) del self def update(self, otherset): if self.title != otherset.title: self.title = otherset.title self.dirty = True if self.num_photos != otherset.num_photos: self.num_photos = otherset.num_photos self.dirty = True if self.num_videos != otherset.num_videos: self.num_videos = otherset.num_videos self.dirty = True def append_photo(self, photo): self.photos.append(photo) self.dirty = True def remove_photo(self, photo): self.photos.remove(photo) self.dirty = True def get_photo(self, id): for photo in self.photos: if photo.id == id: return photo return False def has_photo(self, id): for photo in self.photos: if photo.id == id: return True return False def add_photos(self, set_node): for photo in set_node.getchildren(): self.append_photo(Photo(set_node, photo, self)) self.dirty = True def get_node(self): return None def set_node(self, node): self.dirty = True Node.set_node(self, node) self.set_number_of_photos(node) self.set_number_of_videos(node) node = property(get_node, set_node) def set_title(self, node): self.title = node.find('title').text def set_number_of_photos(self, node): self.num_photos = int(node.get('photos')) def set_number_of_videos(self, node): self.num_videos = int(node.get('videos')) def get_number_of_photos_and_videos(self): return self.num_photos + self.num_videos number_of_photos_and_videos = property(get_number_of_photos_and_videos) def __str__(self): return "<flickr Set>%s, id: %s, photos: %i</flickr Set>" % ( hasattr(self, 'title') and self.title or '', hasattr(self, 'id') and self.id or '', hasattr(self, 'number_of_photos_and_videos') and self.number_of_photos_and_videos or 0 ) class Photo(Node, DictSerializableModel): def __init__(self, set_node=None, photo_node=None, parent=None): if set_node is not None and photo_node is not None and parent is not None: # should only be none when serializing self.set = parent self.set_info(set_node, photo_node) self.location = '' self.dirty = True def dump(self): return { 'owner' : self.owner, 'title' : self.title, 'id' : self.id, 'secret' : self.secret, 'media' : self.media, 'dirty' : self.dirty, 'originalsecret' : self.originalsecret, 'farm' : self.farm, 'server' : self.server, 'originalformat' : self.originalformat, 'lastupdate' : self.lastupdate, 'location' : self.location } def load(self, value, parent): self.set = parent for k, v in value.items(): setattr(self, k, v) return self def delete(self): self.set.dirty = True if os.path.exists(self.location): os.remove(self.location) del self def get_dirty(self): if not os.path.exists(self.location): return True else: return self._dirty def set_dirty(self, value): self._dirty = value self.set.dirty = True dirty = property(get_dirty, set_dirty) def set_info(self, set_node, photo_node): self.set.dirty = True Node.set_node(self, photo_node) self.set_secret(photo_node) self.set_originalsecret(photo_node) self.set_farm(photo_node) self.set_originalformat(photo_node) self.set_server(photo_node) self.set_lastupdate(photo_node) self.set_media(photo_node) self.set_owner(set_node) def set_owner(self, node): self.owner = node.get('owner') def set_title(self, node): self.title = node.get('title') def set_secret(self, node): self.secret = node.get('secret') def set_media(self, node): self.media = node.get('media') def set_originalsecret(self, node): self.originalsecret = node.get('originalsecret') def set_farm(self, node): self.farm = node.get('farm') def set_server(self, node): self.server = node.get('server') def set_originalformat(self, node): self.originalformat = node.get('originalformat') def set_lastupdate(self, node): self.lastupdate = int(node.get('lastupdate')) def get_filename(self): if self.media == 'video': return "%s-%s.avi" % (self.id, normalize(self.title)) else: return "%s-%s.%s" % (self.id, normalize(self.title), self.originalformat) filename = property(get_filename) def __str__(self): return "<flickr Photo>%s, in set %s</flickr Photo>" % ( hasattr(self, 'title') and self.title or '', hasattr(self, 'set') and self.set or '' )
Python
# do all flickrapi overrides here... import flickrapi, math import xml.etree.ElementTree as ElementTree sets_information = [ { 'id' : 1, 'photos' : 1, 'videos' : 0 }, { 'id' : 2, 'photos' : 0, 'videos' : 0 }, { 'id' : 3, 'photos' : 10000, 'videos' : 300 }, { 'id' : 4, 'photos' : 499, 'videos' : 0 }, { 'id' : 5, 'photos' : 500, 'videos' : 0 }, { 'id' : 6, 'photos' : 501, 'videos' : 0 } ] def get_set_info(id): for s in sets_information: if s['id'] == int(id): return s return None photoset_result = """ <photoset id="%(id)i" primary="primary%(id)i" secret="secret%(id)i" server="server%(id)i" photos="%(photos)i" videos="%(videos)i" farm="farm%(id)i"> <title>Test %(id)i</title> <description>Test %(id)i description</description> </photoset> """ photo_result = """<photo id="%(id)s" secret="secret%(id)s" server="server%(id)s" farm="farm%(id)s" title="Title %(id)s" isprimary="1" originalsecret="originalsecret%(id)s" originalformat="jpg" lastupdate="1232549345" media="%(type)s" media_status="ready"/> """ class FakeFlickrAPI(object): def __init__(self, key, secret): self.key = key self.secret = secret self.retrieved_photos = {} def photosets_getList(self): return ElementTree.fromstring("""<rsp stat="ok"><photosets cancreate="1">""" + ''.join([photoset_result % set_info for set_info in sets_information]) + """</photosets></rsp>""") def auth_checkToken(self, *args, **kwargs): return ElementTree.fromstring(""" <auth> <token>976598454353455</token> <perms>read</perms> <user nsid="12037949754@N01" username="Bees" fullname="Cal H" /> </auth>""") def auth_getFrob(self, *args, **kwargs): return ElementTree.fromstring("""<frob>746563215463214621</frob>""") def auth_getToken(self, *args, **kwargs): return ElementTree.fromstring(""" <auth> <token>976598454353455</token> <perms>write</perms> <user nsid="12037949754@N01" username="Bees" fullname="Cal H" /> </auth>""") def photosets_getPhotos(self, photoset_id='',per_page=500,extras='',page=1,media='all'): if not self.retrieved_photos.has_key(photoset_id): self.retrieved_photos[photoset_id] = {'photos' : 0, 'videos' : 0} set_info = get_set_info(photoset_id) total = (set_info['photos'] + set_info['videos']) count_info = self.retrieved_photos[photoset_id] head = """<rsp stat="ok"> <photoset id="%(id)s" primary="2483" page="%(page)i" perpage="%(per_page)i" pages="%(pages)i" total="%(total)i">""" % { 'id' : photoset_id, 'page' : page, 'per_page' : per_page, 'pages' : int(math.ceil(float(total)/float(500))), 'total' : total } photos_rsp = '' current_count = 0 while current_count < per_page and (count_info['photos'] + count_info['videos']) < total: current_count += 1 if count_info['photos'] < set_info['photos']: photos_rsp += photo_result % {'id' : str(page) + str(current_count), 'type' : 'photo'} count_info['photos'] += 1 else: photos_rsp += photo_result % {'id' : str(page) + str(current_count), 'type' : 'video'} count_info['videos'] += 1 return ElementTree.fromstring(head + photos_rsp + """</photoset></rsp>""") flickrapi.FlickrAPI = FakeFlickrAPI from flickrmirror.view.base import IView from flickrmirror.controller import MirrorController class TestView(IView): name = "test view" def __init__(self): self.controller = MirrorController(self) self.last_prompt = None self.last_status = None self.next_prompt_result = None self.last_log = None def prompt(self, msg, result=True): self.last_prompt = msg if result: return self.next_prompt_result def status(self, msg): self.last_status = msg def log(self, msg): self.last_log = msg
Python
import test_tools
Python
import flickrapi import os.path key = "57ed171ead518050f3802d2ef8620621" secret = "15863af84276ca85" pickled_filename = '.flickrmirror' pickled_foldername = '__flickrmirrorsettings__' mirror_model_pickle_name = '__mirror_model.dict' flickr = flickrapi.FlickrAPI(key, secret) log_file_name = os.path.join("/tmp", "flickrmirror.log")
Python
def normalize(name): bad_letters_skip = """'"/\\,<>?[]{}+=()*&^%$#@!~`""" bad_letters_replace = """ :;""" for b in bad_letters_skip: name = name.replace(b, '') for b in bad_letters_replace: name = name.replace(b, '-') return name.strip().replace('--', '-')
Python
class NotImplementedException(Exception): """ Method not implemented """
Python
# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: from pkgutil import extend_path __path__ = extend_path(__path__, __name__)
Python
from flickrmirror.view.cli import CLIView view = CLIView()
Python
import commands, urllib, os.path, os, pickle, time, model, datetime, shutil from tools import * from settings import flickr from utils import * class MirrorController: """ """ def __init__(self, view): self.view = view self.authenticator = Authenticator() self.retrieve = Retriever(self.view.status) self._backup_directory = None self.mirror_model = None def save(self): if self.mirror_model is not None: loc = Storer().pickle_mirror(self.mirror_model, str(self.backup_directory), self.view.status) else: self.view.prompt("You haven't even loaded your settings yet!", False) def load(self): if self.backup_directory is None: self.view.prompt("You must select a backup directory before you load your data!", False) return if self.mirror_model is None: self.mirror_model = self.retrieve.get_pickled_mirror(str(self.backup_directory)) self.view.status("Loaded flickrmirror settings.") def get_photo_count(self): if self.mirror_model: num = 0 for s in self.mirror_model.filtered_sets(): num += len(s.photos) return num else: return 0 def authenticate(self): if not self.authenticator.authenticated(): r = self.authenticator.start_authentication() self.view.prompt("Press enter once you're authenticated.", False) self.authenticator.end_authentication(r) def filter_set(self, sets): if sets == "*": self.mirror_model.filtered = [] for set in self.mirror_model.sets: self.mirror_model.filtered.append(set.id) self.view.status("Filtered all sets.") else: sets = sets.split(',') for set_id_or_title in sets: set_id_or_title = set_id_or_title.strip() set = self.mirror_model.get_set(set_id_or_title) if set and set.id not in self.mirror_model.filtered: self.mirror_model.filtered.append(set.id) self.view.status("Filtered set %s" % set.title) self.save() def unfilter_set(self, sets): if sets == "*": self.mirror_model.filtered = [] else: sets = sets.split(',') for set_id_or_title in sets: set_id_or_title = set_id_or_title.strip() set = self.mirror_model.get_set(set_id_or_title) if set.id in self.mirror_model.filtered: self.mirror_model.filtered.remove(set.id) self.view.status("Un-filtered set %s" % set.title) self.save() def mirror(self): self.load() self.view.status("Getting updated flickr information.") self.synchronize_server() self.view.status("Synchronizing with local hard drive.") self.synchronize_local() self.save() def synchronize_server(self): """ big, nasty method... needs a lot of work... Don't worry about last updated... There is no way of knowing if sets get updated or anything so just get a new list of sets and compare """ updated_mirror = MirrorModel(self.retrieve.get_all_sets(filled=True)) sets_to_add = [] for s in updated_mirror.sets: if self.mirror_model.has_set(s.id): current_set = self.mirror_model.get_set(s.id) current_set.update(s) for p in s.photos: cp = current_set.get_photo(p.id) if not cp: current_set.append_photo(p) elif cp.lastupdate < p.lastupdate: current_set.remove_photo(cp) cp.delete() #so it'll be updated... maybe a better way? current_set.append_photo(p) else: sets_to_add.append(s) self.mirror_model.sets.extend(sets_to_add) sets_to_remove = [] for current_set in self.mirror_model.sets: new_set = updated_mirror.get_set(current_set.id) if not new_set: sets_to_remove.append(current_set) else: for photo in current_set.photos: new_photo = new_set.get_photo(photo.id) if not new_photo: current_set.remove_photo(photo) photo.delete() for set in sets_to_remove: self.mirror_model.sets.remove(set) set.delete() self.mirror_model.last_updated = int(time.time()) self.save() # don't save until the end in case something goes wrong... def get_dirty_photos(self): dirty_photos = [] for set in self.mirror_model.filtered_sets(): for photo in set.photos: if photo.dirty: dirty_photos.append( (photo, set) ) return dirty_photos def retrieve_photo(self, photo, set, report=lambda x,y,z: x): set_storage = Directory(os.path.join(str(self.backup_directory), normalize(set.title))) self.download(photo, set_storage, report) self.save() def synchronize_local(self): dirty_photos = self.get_dirty_photos() for i in range(0, len(dirty_photos)): photo, set = dirty_photos[i] self.view.status("%i/%i - Downloading photo %s from set %s." % ( i+1, len(dirty_photos), photo.title, set.title ) ) self.retrieve_photo(photo, set) def download(self, photo, storage, report=lambda x,y,z: x): url = self.retrieve.url(photo) file_location = os.path.join(storage.path, photo.filename) if os.path.exists(file_location): self.view.status("%s already exists. Skipping download." % photo.title) else: logger.info("downloading %s from %s" % (str(photo), url)) #save to temp file first and then move to location so incomplete downloads are not saved tmp_file = urllib.urlretrieve(url, file_location, report)[0] shutil.move(tmp_file, file_location) self.view.status("Saved photo %s to %s." % (photo.title, file_location)) logger.info("saved photo %s to %s" % (photo.title, file_location)) photo.location = file_location photo.dirty = False def mirror_set(self, a_set): if type(a_set) == str: a_set = self.retrieve.set(a_set) self.retrieve.fill_set_with_photos(a_set) for photo in a_set.photos: self.view.status('retrieving photo info %s' % photo.title) self.retrieve.fill_photo_info(photo) storage = Directory(os.path.join(str(self.backup_directory), normalize(a_set.title))) for index in range(0, len(a_set.photos)): photo = a_set.photos[index] self.view.status("backing up photo %s(%s/%s)" % ( photo.title, index + 1, len(a_set.photos) ), False) self.download(photo, storage) self.view.status("done...") def get_backup_directory(self): return self._backup_directory def set_backup_directory(self, value): while not os.path.exists(value): value = raw_input("Enter your backup directory: ").strip() self._backup_directory = Directory(value, False) backup_directory = property(get_backup_directory, set_backup_directory)
Python
from pyamf.remoting.gateway.google import WebAppGateway from src.model.Contact import Contact from src.services import ContactService import jinja2 import os import pyamf import webapp2 jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.abspath("html")), autoescape=True) class MainHandler(webapp2.RequestHandler): def get(self): htmlPage = jinja_env.get_template("flex.html").render() self.response.out.write(htmlPage) pyamf.register_class(Contact, 'src.model.Contact') services = { 'ContactService' : ContactService } gateway = WebAppGateway(services, debug=True) mappings = [ ('/', MainHandler), ('/gateway', gateway) ] app = webapp2.WSGIApplication(mappings, debug=True)
Python
from src.model.Contact import Contact def echo(message): return "echo " + message def addContact(contact): try: contact.put() return True except: return False def getContacts(): contacts = Contact.all() return list(contacts)
Python
from google.appengine.ext import db class Contact(db.Model): name = db.StringProperty(required=True) surname = db.StringProperty(required=True)
Python
# Copyright (c) The PyAMF Project. # See LICENSE.txt for details. """ Local Shared Object implementation. Local Shared Object (LSO), sometimes known as Adobe Flash cookies, is a cookie-like data entity used by the Adobe Flash Player and Gnash. The players allow web content to read and write LSO data to the computer's local drive on a per-domain basis. @see: U{Local Shared Object on WikiPedia <http://en.wikipedia.org/wiki/Local_Shared_Object>} @since: 0.1 """ import pyamf from pyamf import util #: Magic Number - 2 bytes HEADER_VERSION = '\x00\xbf' #: Marker - 10 bytes HEADER_SIGNATURE = 'TCSO\x00\x04\x00\x00\x00\x00' #: Padding - 4 bytes PADDING_BYTE = '\x00' def decode(stream, strict=True): """ Decodes a SOL stream. L{strict} mode ensures that the sol stream is as spec compatible as possible. @return: A C{tuple} containing the C{root_name} and a C{dict} of name, value pairs. """ if not isinstance(stream, util.BufferedByteStream): stream = util.BufferedByteStream(stream) # read the version version = stream.read(2) if version != HEADER_VERSION: raise pyamf.DecodeError('Unknown SOL version in header') # read the length length = stream.read_ulong() if strict and stream.remaining() != length: raise pyamf.DecodeError('Inconsistent stream header length') # read the signature signature = stream.read(10) if signature != HEADER_SIGNATURE: raise pyamf.DecodeError('Invalid signature') length = stream.read_ushort() root_name = stream.read_utf8_string(length) # read padding if stream.read(3) != PADDING_BYTE * 3: raise pyamf.DecodeError('Invalid padding read') decoder = pyamf.get_decoder(stream.read_uchar()) decoder.stream = stream values = {} while 1: if stream.at_eof(): break name = decoder.readString() value = decoder.readElement() # read the padding if stream.read(1) != PADDING_BYTE: raise pyamf.DecodeError('Missing padding byte') values[name] = value return (root_name, values) def encode(name, values, strict=True, encoding=pyamf.AMF0): """ Produces a SharedObject encoded stream based on the name and values. @param name: The root name of the SharedObject. @param values: A `dict` of name value pairs to be encoded in the stream. @param strict: Ensure that the SOL stream is as spec compatible as possible. @return: A SharedObject encoded stream. @rtype: L{BufferedByteStream<pyamf.util.BufferedByteStream>}, a file like object. """ encoder = pyamf.get_encoder(encoding) stream = encoder.stream # write the header stream.write(HEADER_VERSION) if strict: length_pos = stream.tell() stream.write_ulong(0) # write the signature stream.write(HEADER_SIGNATURE) # write the root name name = name.encode('utf-8') stream.write_ushort(len(name)) stream.write(name) # write the padding stream.write(PADDING_BYTE * 3) stream.write_uchar(encoding) for n, v in values.iteritems(): encoder.serialiseString(n) encoder.writeElement(v) # write the padding stream.write(PADDING_BYTE) if strict: stream.seek(length_pos) stream.write_ulong(stream.remaining() - 4) stream.seek(0) return stream def load(name_or_file): """ Loads a sol file and returns a L{SOL} object. @param name_or_file: Name of file, or file-object. @type name_or_file: C{string} """ f = name_or_file opened = False if isinstance(name_or_file, basestring): f = open(name_or_file, 'rb') opened = True elif not hasattr(f, 'read'): raise ValueError('Readable stream expected') name, values = decode(f.read()) s = SOL(name) for n, v in values.iteritems(): s[n] = v if opened is True: f.close() return s def save(sol, name_or_file, encoding=pyamf.AMF0): """ Writes a L{SOL} object to C{name_or_file}. @param name_or_file: Name of file or file-object to write to. @param encoding: AMF encoding type. """ f = name_or_file opened = False if isinstance(name_or_file, basestring): f = open(name_or_file, 'wb+') opened = True elif not hasattr(f, 'write'): raise ValueError('Writable stream expected') f.write(encode(sol.name, sol, encoding=encoding).getvalue()) if opened: f.close() class SOL(dict): """ Local Shared Object class, allows easy manipulation of the internals of a C{sol} file. """ def __init__(self, name): self.name = name def save(self, name_or_file, encoding=pyamf.AMF0): save(self, name_or_file, encoding) def __repr__(self): return '<%s %s %s at 0x%x>' % (self.__class__.__name__, self.name, dict.__repr__(self), id(self)) LSO = SOL
Python
# Copyright (c) The PyAMF Project. # See LICENSE.txt for details. """ AMF0 implementation. C{AMF0} supports the basic data types used for the NetConnection, NetStream, LocalConnection, SharedObjects and other classes in the Adobe Flash Player. @since: 0.1 @see: U{Official AMF0 Specification in English (external) <http://opensource.adobe.com/wiki/download/attachments/1114283/amf0_spec_121207.pdf>} @see: U{Official AMF0 Specification in Japanese (external) <http://opensource.adobe.com/wiki/download/attachments/1114283/JP_amf0_spec_121207.pdf>} @see: U{AMF documentation on OSFlash (external) <http://osflash.org/documentation/amf>} """ import datetime import pyamf from pyamf import util, codec, xml, python #: Represented as 9 bytes: 1 byte for C{0x00} and 8 bytes a double #: representing the value of the number. TYPE_NUMBER = '\x00' #: Represented as 2 bytes: 1 byte for C{0x01} and a second, C{0x00} #: for C{False}, C{0x01} for C{True}. TYPE_BOOL = '\x01' #: Represented as 3 bytes + len(String): 1 byte C{0x02}, then a UTF8 string, #: including the top two bytes representing string length as a C{int}. TYPE_STRING = '\x02' #: Represented as 1 byte, C{0x03}, then pairs of UTF8 string, the key, and #: an AMF element, ended by three bytes, C{0x00} C{0x00} C{0x09}. TYPE_OBJECT = '\x03' #: MovieClip does not seem to be supported by Remoting. #: It may be used by other AMF clients such as SharedObjects. TYPE_MOVIECLIP = '\x04' #: 1 single byte, C{0x05} indicates null. TYPE_NULL = '\x05' #: 1 single byte, C{0x06} indicates null. TYPE_UNDEFINED = '\x06' #: When an ActionScript object refers to itself, such C{this.self = this}, #: or when objects are repeated within the same scope (for example, as the #: two parameters of the same function called), a code of C{0x07} and an #: C{int}, the reference number, are written. TYPE_REFERENCE = '\x07' #: A MixedArray is indicated by code C{0x08}, then a Long representing the #: highest numeric index in the array, or 0 if there are none or they are #: all negative. After that follow the elements in key : value pairs. TYPE_MIXEDARRAY = '\x08' #: @see: L{TYPE_OBJECT} TYPE_OBJECTTERM = '\x09' #: An array is indicated by C{0x0A}, then a Long for array length, then the #: array elements themselves. Arrays are always sparse; values for #: inexistant keys are set to null (C{0x06}) to maintain sparsity. TYPE_ARRAY = '\x0A' #: Date is represented as C{0x0B}, then a double, then an C{int}. The double #: represents the number of milliseconds since 01/01/1970. The C{int} represents #: the timezone offset in minutes between GMT. Note for the latter than values #: greater than 720 (12 hours) are represented as M{2^16} - the value. Thus GMT+1 #: is 60 while GMT-5 is 65236. TYPE_DATE = '\x0B' #: LongString is reserved for strings larger then M{2^16} characters long. It #: is represented as C{0x0C} then a LongUTF. TYPE_LONGSTRING = '\x0C' #: Trying to send values which don't make sense, such as prototypes, functions, #: built-in objects, etc. will be indicated by a single C{00x0D} byte. TYPE_UNSUPPORTED = '\x0D' #: Remoting Server -> Client only. #: @see: L{RecordSet} #: @see: U{RecordSet structure on OSFlash #: <http://osflash.org/documentation/amf/recordset>} TYPE_RECORDSET = '\x0E' #: The XML element is indicated by C{0x0F} and followed by a LongUTF containing #: the string representation of the XML object. The receiving gateway may which #: to wrap this string inside a language-specific standard XML object, or simply #: pass as a string. TYPE_XML = '\x0F' #: A typed object is indicated by C{0x10}, then a UTF string indicating class #: name, and then the same structure as a normal C{0x03} Object. The receiving #: gateway may use a mapping scheme, or send back as a vanilla object or #: associative array. TYPE_TYPEDOBJECT = '\x10' #: An AMF message sent from an AVM+ client such as the Flash Player 9 may break #: out into L{AMF3<pyamf.amf3>} mode. In this case the next byte will be the #: AMF3 type code and the data will be in AMF3 format until the decoded object #: reaches it's logical conclusion (for example, an object has no more keys). TYPE_AMF3 = '\x11' class Context(codec.Context): """ """ def clear(self): codec.Context.clear(self) encoder = self.extra.get('amf3_encoder', None) if encoder: encoder.context.clear() decoder = self.extra.get('amf3_decoder', None) if decoder: decoder.context.clear() def getAMF3Encoder(self, amf0_encoder): encoder = self.extra.get('amf3_encoder', None) if encoder: return encoder encoder = pyamf.get_encoder(pyamf.AMF3, stream=amf0_encoder.stream, timezone_offset=amf0_encoder.timezone_offset) self.extra['amf3_encoder'] = encoder return encoder def getAMF3Decoder(self, amf0_decoder): decoder = self.extra.get('amf3_decoder', None) if decoder: return decoder decoder = pyamf.get_decoder(pyamf.AMF3, stream=amf0_decoder.stream, timezone_offset=amf0_decoder.timezone_offset) self.extra['amf3_decoder'] = decoder return decoder class Decoder(codec.Decoder): """ Decodes an AMF0 stream. """ def buildContext(self): return Context() def getTypeFunc(self, data): # great for coverage, sucks for readability if data == TYPE_NUMBER: return self.readNumber elif data == TYPE_BOOL: return self.readBoolean elif data == TYPE_STRING: return self.readString elif data == TYPE_OBJECT: return self.readObject elif data == TYPE_NULL: return self.readNull elif data == TYPE_UNDEFINED: return self.readUndefined elif data == TYPE_REFERENCE: return self.readReference elif data == TYPE_MIXEDARRAY: return self.readMixedArray elif data == TYPE_ARRAY: return self.readList elif data == TYPE_DATE: return self.readDate elif data == TYPE_LONGSTRING: return self.readLongString elif data == TYPE_UNSUPPORTED: return self.readNull elif data == TYPE_XML: return self.readXML elif data == TYPE_TYPEDOBJECT: return self.readTypedObject elif data == TYPE_AMF3: return self.readAMF3 def readNumber(self): """ Reads a ActionScript C{Number} value. In ActionScript 1 and 2 the C{NumberASTypes} type represents all numbers, both floats and integers. @rtype: C{int} or C{float} """ return _check_for_int(self.stream.read_double()) def readBoolean(self): """ Reads a ActionScript C{Boolean} value. @rtype: C{bool} @return: Boolean. """ return bool(self.stream.read_uchar()) def readString(self, bytes=False): """ Reads a C{string} from the stream. If bytes is C{True} then you will get the raw data read from the stream, otherwise a string that has been B{utf-8} decoded. """ l = self.stream.read_ushort() b = self.stream.read(l) if bytes: return b return self.context.getStringForBytes(b) def readNull(self): """ Reads a ActionScript C{null} value. """ return None def readUndefined(self): """ Reads an ActionScript C{undefined} value. @return: L{Undefined<pyamf.Undefined>} """ return pyamf.Undefined def readMixedArray(self): """ Read mixed array. @rtype: L{pyamf.MixedArray} """ # TODO: something with the length/strict self.stream.read_ulong() # length obj = pyamf.MixedArray() self.context.addObject(obj) attrs = self.readObjectAttributes(obj) for key in attrs.keys(): try: key = int(key) except ValueError: pass obj[key] = attrs[key] return obj def readList(self): """ Read a C{list} from the data stream. """ obj = [] self.context.addObject(obj) l = self.stream.read_ulong() for i in xrange(l): obj.append(self.readElement()) return obj def readTypedObject(self): """ Reads an aliased ActionScript object from the stream and attempts to 'cast' it into a python class. @see: L{pyamf.register_class} """ class_alias = self.readString() try: alias = self.context.getClassAlias(class_alias) except pyamf.UnknownClassAlias: if self.strict: raise alias = pyamf.TypedObjectClassAlias(class_alias) obj = alias.createInstance(codec=self) self.context.addObject(obj) attrs = self.readObjectAttributes(obj) alias.applyAttributes(obj, attrs, codec=self) return obj def readAMF3(self): """ Read AMF3 elements from the data stream. @return: The AMF3 element read from the stream """ return self.context.getAMF3Decoder(self).readElement() def readObjectAttributes(self, obj): obj_attrs = {} key = self.readString(True) while self.stream.peek() != TYPE_OBJECTTERM: obj_attrs[key] = self.readElement() key = self.readString(True) # discard the end marker (TYPE_OBJECTTERM) self.stream.read(1) return obj_attrs def readObject(self): """ Reads an anonymous object from the data stream. @rtype: L{ASObject<pyamf.ASObject>} """ obj = pyamf.ASObject() self.context.addObject(obj) obj.update(self.readObjectAttributes(obj)) return obj def readReference(self): """ Reads a reference from the data stream. @raise pyamf.ReferenceError: Unknown reference. """ idx = self.stream.read_ushort() o = self.context.getObject(idx) if o is None: raise pyamf.ReferenceError('Unknown reference %d' % (idx,)) return o def readDate(self): """ Reads a UTC date from the data stream. Client and servers are responsible for applying their own timezones. Date: C{0x0B T7 T6} .. C{T0 Z1 Z2 T7} to C{T0} form a 64 bit Big Endian number that specifies the number of nanoseconds that have passed since 1/1/1970 0:00 to the specified time. This format is UTC 1970. C{Z1} and C{Z0} for a 16 bit Big Endian number indicating the indicated time's timezone in minutes. """ ms = self.stream.read_double() / 1000.0 self.stream.read_short() # tz # Timezones are ignored d = util.get_datetime(ms) if self.timezone_offset: d = d + self.timezone_offset self.context.addObject(d) return d def readLongString(self): """ Read UTF8 string. """ l = self.stream.read_ulong() bytes = self.stream.read(l) return self.context.getStringForBytes(bytes) def readXML(self): """ Read XML. """ data = self.readLongString() root = xml.fromstring(data) self.context.addObject(root) return root class Encoder(codec.Encoder): """ Encodes an AMF0 stream. @ivar use_amf3: A flag to determine whether this encoder should default to using AMF3. Defaults to C{False} @type use_amf3: C{bool} """ def __init__(self, *args, **kwargs): codec.Encoder.__init__(self, *args, **kwargs) self.use_amf3 = kwargs.pop('use_amf3', False) def buildContext(self): return Context() def getTypeFunc(self, data): if self.use_amf3: return self.writeAMF3 t = type(data) if t is pyamf.MixedArray: return self.writeMixedArray return codec.Encoder.getTypeFunc(self, data) def writeType(self, t): """ Writes the type to the stream. @type t: C{str} @param t: ActionScript type. """ self.stream.write(t) def writeUndefined(self, data): """ Writes the L{undefined<TYPE_UNDEFINED>} data type to the stream. @param data: Ignored, here for the sake of interface. """ self.writeType(TYPE_UNDEFINED) def writeNull(self, n): """ Write null type to data stream. """ self.writeType(TYPE_NULL) def writeList(self, a): """ Write array to the stream. @param a: The array data to be encoded to the AMF0 data stream. """ if self.writeReference(a) != -1: return self.context.addObject(a) self.writeType(TYPE_ARRAY) self.stream.write_ulong(len(a)) for data in a: self.writeElement(data) def writeNumber(self, n): """ Write number to the data stream . @param n: The number data to be encoded to the AMF0 data stream. """ self.writeType(TYPE_NUMBER) self.stream.write_double(float(n)) def writeBoolean(self, b): """ Write boolean to the data stream. @param b: The boolean data to be encoded to the AMF0 data stream. """ self.writeType(TYPE_BOOL) if b: self.stream.write_uchar(1) else: self.stream.write_uchar(0) def serialiseString(self, s): """ Similar to L{writeString} but does not encode a type byte. """ if type(s) is unicode: s = self.context.getBytesForString(s) l = len(s) if l > 0xffff: self.stream.write_ulong(l) else: self.stream.write_ushort(l) self.stream.write(s) def writeBytes(self, s): """ Write a string of bytes to the data stream. """ l = len(s) if l > 0xffff: self.writeType(TYPE_LONGSTRING) else: self.writeType(TYPE_STRING) if l > 0xffff: self.stream.write_ulong(l) else: self.stream.write_ushort(l) self.stream.write(s) def writeString(self, u): """ Write a unicode to the data stream. """ s = self.context.getBytesForString(u) self.writeBytes(s) def writeReference(self, o): """ Write reference to the data stream. @param o: The reference data to be encoded to the AMF0 datastream. """ idx = self.context.getObjectReference(o) if idx == -1 or idx > 65535: return -1 self.writeType(TYPE_REFERENCE) self.stream.write_ushort(idx) return idx def _writeDict(self, o): """ Write C{dict} to the data stream. @param o: The C{dict} data to be encoded to the AMF0 data stream. """ for key, val in o.iteritems(): if type(key) in python.int_types: key = str(key) self.serialiseString(key) self.writeElement(val) def writeMixedArray(self, o): """ Write mixed array to the data stream. @type o: L{pyamf.MixedArray} """ if self.writeReference(o) != -1: return self.context.addObject(o) self.writeType(TYPE_MIXEDARRAY) # TODO: optimise this # work out the highest integer index try: # list comprehensions to save the day max_index = max([y[0] for y in o.items() if isinstance(y[0], (int, long))]) if max_index < 0: max_index = 0 except ValueError: max_index = 0 self.stream.write_ulong(max_index) self._writeDict(o) self._writeEndObject() def _writeEndObject(self): self.stream.write('\x00\x00' + TYPE_OBJECTTERM) def writeObject(self, o): """ Write a Python object to the stream. @param o: The object data to be encoded to the AMF0 data stream. """ if self.writeReference(o) != -1: return self.context.addObject(o) alias = self.context.getClassAlias(o.__class__) alias.compile() if alias.amf3: self.writeAMF3(o) return if alias.anonymous: self.writeType(TYPE_OBJECT) else: self.writeType(TYPE_TYPEDOBJECT) self.serialiseString(alias.alias) attrs = alias.getEncodableAttributes(o, codec=self) if alias.static_attrs and attrs: for key in alias.static_attrs: value = attrs.pop(key) self.serialiseString(key) self.writeElement(value) if attrs: self._writeDict(attrs) self._writeEndObject() def writeDate(self, d): """ Writes a date to the data stream. @type d: Instance of C{datetime.datetime} @param d: The date to be encoded to the AMF0 data stream. """ if isinstance(d, datetime.time): raise pyamf.EncodeError('A datetime.time instance was found but ' 'AMF0 has no way to encode time objects. Please use ' 'datetime.datetime instead (got:%r)' % (d,)) # According to the Red5 implementation of AMF0, dates references are # created, but not used. if self.timezone_offset is not None: d -= self.timezone_offset secs = util.get_timestamp(d) tz = 0 self.writeType(TYPE_DATE) self.stream.write_double(secs * 1000.0) self.stream.write_short(tz) def writeXML(self, e): """ Writes an XML instance. """ self.writeType(TYPE_XML) data = xml.tostring(e) if isinstance(data, unicode): data = data.encode('utf-8') self.stream.write_ulong(len(data)) self.stream.write(data) def writeAMF3(self, data): """ Writes an element in L{AMF3<pyamf.amf3>} format. """ self.writeType(TYPE_AMF3) self.context.getAMF3Encoder(self).writeElement(data) class RecordSet(object): """ I represent the C{RecordSet} class used in Adobe Flash Remoting to hold (amongst other things) SQL records. @ivar columns: The columns to send. @type columns: List of strings. @ivar items: The C{RecordSet} data. @type items: List of lists, the order of the data corresponds to the order of the columns. @ivar service: Service linked to the C{RecordSet}. @type service: @ivar id: The id of the C{RecordSet}. @type id: C{str} @see: U{RecordSet on OSFlash (external) <http://osflash.org/documentation/amf/recordset>} """ class __amf__: alias = 'RecordSet' static = ('serverInfo',) dynamic = False def __init__(self, columns=[], items=[], service=None, id=None): self.columns = columns self.items = items self.service = service self.id = id def _get_server_info(self): ret = pyamf.ASObject(totalCount=len(self.items), cursor=1, version=1, initialData=self.items, columnNames=self.columns) if self.service is not None: ret.update({'serviceName': str(self.service['name'])}) if self.id is not None: ret.update({'id':str(self.id)}) return ret def _set_server_info(self, val): self.columns = val['columnNames'] self.items = val['initialData'] try: # TODO nick: find relevant service and link in here. self.service = dict(name=val['serviceName']) except KeyError: self.service = None try: self.id = val['id'] except KeyError: self.id = None serverInfo = property(_get_server_info, _set_server_info) def __repr__(self): ret = '<%s.%s' % (self.__module__, self.__class__.__name__) if self.id is not None: ret += ' id=%s' % self.id if self.service is not None: ret += ' service=%s' % self.service ret += ' at 0x%x>' % id(self) return ret pyamf.register_class(RecordSet) def _check_for_int(x): """ This is a compatibility function that takes a C{float} and converts it to an C{int} if the values are equal. """ try: y = int(x) except (OverflowError, ValueError): pass else: # There is no way in AMF0 to distinguish between integers and floats if x == x and y == x: return y return x
Python
# Copyright (c) The PyAMF Project. # See LICENSE.txt for details. """ AMF0 Remoting support. @since: 0.1.0 """ import traceback import sys from pyamf import remoting from pyamf.remoting import gateway class RequestProcessor(object): def __init__(self, gateway): self.gateway = gateway def authenticateRequest(self, request, service_request, *args, **kwargs): """ Authenticates the request against the service. @param request: The AMF request @type request: L{Request<pyamf.remoting.Request>} """ username = password = None if 'Credentials' in request.headers: cred = request.headers['Credentials'] username = cred['userid'] password = cred['password'] return self.gateway.authenticateRequest(service_request, username, password, *args, **kwargs) def buildErrorResponse(self, request, error=None): """ Builds an error response. @param request: The AMF request @type request: L{Request<pyamf.remoting.Request>} @return: The AMF response @rtype: L{Response<pyamf.remoting.Response>} """ if error is not None: cls, e, tb = error else: cls, e, tb = sys.exc_info() return remoting.Response(build_fault(cls, e, tb, self.gateway.debug), status=remoting.STATUS_ERROR) def _getBody(self, request, response, service_request, **kwargs): if 'DescribeService' in request.headers: return service_request.service.description return self.gateway.callServiceRequest(service_request, *request.body, **kwargs) def __call__(self, request, *args, **kwargs): """ Processes an AMF0 request. @param request: The request to be processed. @type request: L{Request<pyamf.remoting.Request>} @return: The response to the request. @rtype: L{Response<pyamf.remoting.Response>} """ response = remoting.Response(None) try: service_request = self.gateway.getServiceRequest(request, request.target) except gateway.UnknownServiceError: return self.buildErrorResponse(request) # we have a valid service, now attempt authentication try: authd = self.authenticateRequest(request, service_request, *args, **kwargs) except (SystemExit, KeyboardInterrupt): raise except: return self.buildErrorResponse(request) if not authd: # authentication failed response.status = remoting.STATUS_ERROR response.body = remoting.ErrorFault(code='AuthenticationError', description='Authentication failed') return response # authentication succeeded, now fire the preprocessor (if there is one) try: self.gateway.preprocessRequest(service_request, *args, **kwargs) except (SystemExit, KeyboardInterrupt): raise except: return self.buildErrorResponse(request) try: response.body = self._getBody(request, response, service_request, *args, **kwargs) return response except (SystemExit, KeyboardInterrupt): raise except: return self.buildErrorResponse(request) def build_fault(cls, e, tb, include_traceback=False): """ Builds a L{ErrorFault<pyamf.remoting.ErrorFault>} object based on the last exception raised. If include_traceback is C{False} then the traceback will not be added to the L{remoting.ErrorFault}. """ if hasattr(cls, '_amf_code'): code = cls._amf_code else: code = cls.__name__ details = None if include_traceback: details = traceback.format_exception(cls, e, tb) return remoting.ErrorFault(code=code, description=unicode(e), details=details)
Python
# Copyright (c) The PyAMF Project. # See LICENSE.txt for details. """ Remoting client implementation. @since: 0.1.0 """ import urllib2 import urlparse import pyamf from pyamf import remoting try: from gzip import GzipFile except ImportError: GzipFile = False try: from cStringIO import StringIO except ImportError: from StringIO import StringIO #: Default user agent is `PyAMF/x.x(.x)`. DEFAULT_USER_AGENT = 'PyAMF/%s' % (pyamf.version,) class ServiceMethodProxy(object): """ Serves as a proxy for calling a service method. @ivar service: The parent service. @type service: L{ServiceProxy} @ivar name: The name of the method. @type name: C{str} or C{None} @see: L{ServiceProxy.__getattr__} """ def __init__(self, service, name): self.service = service self.name = name def __call__(self, *args): """ Inform the proxied service that this function has been called. """ return self.service._call(self, *args) def __str__(self): """ Returns the full service name, including the method name if there is one. """ service_name = str(self.service) if self.name is not None: service_name = '%s.%s' % (service_name, self.name) return service_name class ServiceProxy(object): """ Serves as a service object proxy for RPC calls. Generates L{ServiceMethodProxy} objects for method calls. @see: L{RequestWrapper} for more info. @ivar _gw: The parent gateway @type _gw: L{RemotingService} @ivar _name: The name of the service @type _name: L{str} @ivar _auto_execute: If set to C{True}, when a service method is called, the AMF request is immediately sent to the remote gateway and a response is returned. If set to C{False}, a C{RequestWrapper} is returned, waiting for the underlying gateway to fire the L{execute <RemotingService.execute>} method. """ def __init__(self, gw, name, auto_execute=True): self._gw = gw self._name = name self._auto_execute = auto_execute def __getattr__(self, name): return ServiceMethodProxy(self, name) def _call(self, method_proxy, *args): """ Executed when a L{ServiceMethodProxy} is called. Adds a request to the underlying gateway. """ request = self._gw.addRequest(method_proxy, *args) if self._auto_execute: response = self._gw.execute_single(request) if response.status == remoting.STATUS_ERROR: if hasattr(response.body, 'raiseException'): try: response.body.raiseException() except: raise else: raise remoting.RemotingError return response.body return request def __call__(self, *args): """ This allows services to be 'called' without a method name. """ return self._call(ServiceMethodProxy(self, None), *args) def __str__(self): """ Returns a string representation of the name of the service. """ return self._name class RequestWrapper(object): """ A container object that wraps a service method request. @ivar gw: The underlying gateway. @type gw: L{RemotingService} @ivar id: The id of the request. @type id: C{str} @ivar service: The service proxy. @type service: L{ServiceProxy} @ivar args: The args used to invoke the call. @type args: C{list} """ def __init__(self, gw, id_, service, *args): self.gw = gw self.id = id_ self.service = service self.args = args def __str__(self): return str(self.id) def setResponse(self, response): """ A response has been received by the gateway """ self.response = response self.result = self.response.body if isinstance(self.result, remoting.ErrorFault): self.result.raiseException() def _get_result(self): """ Returns the result of the called remote request. If the request has not yet been called, an C{AttributeError} exception is raised. """ if not hasattr(self, '_result'): raise AttributeError( "'RequestWrapper' object has no attribute 'result'") return self._result def _set_result(self, result): self._result = result result = property(_get_result, _set_result) class RemotingService(object): """ Acts as a client for AMF calls. @ivar url: The url of the remote gateway. Accepts C{http} or C{https} as valid schemes. @type url: C{string} @ivar requests: The list of pending requests to process. @type requests: C{list} @ivar request_number: A unique identifier for tracking the number of requests. @ivar amf_version: The AMF version to use. See L{ENCODING_TYPES<pyamf.ENCODING_TYPES>}. @ivar referer: The referer, or HTTP referer, identifies the address of the client. Ignored by default. @type referer: C{string} @ivar user_agent: Contains information about the user agent (client) originating the request. See L{DEFAULT_USER_AGENT}. @type user_agent: C{string} @ivar headers: A list of persistent headers to send with each request. @type headers: L{HeaderCollection<pyamf.remoting.HeaderCollection>} @ivar http_headers: A dict of HTTP headers to apply to the underlying HTTP connection. @type http_headers: L{dict} @ivar strict: Whether to use strict AMF en/decoding or not. @ivar opener: The function used to power the connection to the remote server. Defaults to U{urllib2.urlopen<http:// docs.python.org/library/urllib2.html#urllib2.urlopen}. """ def __init__(self, url, amf_version=pyamf.AMF0, **kwargs): self.original_url = url self.amf_version = amf_version self.requests = [] self.request_number = 1 self.headers = remoting.HeaderCollection() self.http_headers = {} self.proxy_args = None self.user_agent = kwargs.pop('user_agent', DEFAULT_USER_AGENT) self.referer = kwargs.pop('referer', None) self.strict = kwargs.pop('strict', False) self.logger = kwargs.pop('logger', None) self.opener = kwargs.pop('opener', urllib2.urlopen) if kwargs: raise TypeError('Unexpected keyword arguments %r' % (kwargs,)) self._setUrl(url) def _setUrl(self, url): """ """ self.url = urlparse.urlparse(url) self._root_url = url if not self.url[0] in ('http', 'https'): raise ValueError('Unknown scheme %r' % (self.url[0],)) if self.logger: self.logger.info('Connecting to %r', self._root_url) self.logger.debug('Referer: %r', self.referer) self.logger.debug('User-Agent: %r', self.user_agent) def setProxy(self, host, type='http'): """ Set the proxy for all requests to use. @see: U{The Python Docs<http://docs.python.org/library/urllib2.html# urllib2.Request.set_proxy} """ self.proxy_args = (host, type) def addHeader(self, name, value, must_understand=False): """ Sets a persistent header to send with each request. @param name: Header name. """ self.headers[name] = value self.headers.set_required(name, must_understand) def addHTTPHeader(self, name, value): """ Adds a header to the underlying HTTP connection. """ self.http_headers[name] = value def removeHTTPHeader(self, name): """ Deletes an HTTP header. """ del self.http_headers[name] def getService(self, name, auto_execute=True): """ Returns a L{ServiceProxy} for the supplied name. Sets up an object that can have method calls made to it that build the AMF requests. @rtype: L{ServiceProxy} """ if not isinstance(name, basestring): raise TypeError('string type required') return ServiceProxy(self, name, auto_execute) def getRequest(self, id_): """ Gets a request based on the id. :raise LookupError: Request not found. """ for request in self.requests: if request.id == id_: return request raise LookupError("Request %r not found" % (id_,)) def addRequest(self, service, *args): """ Adds a request to be sent to the remoting gateway. """ wrapper = RequestWrapper(self, '/%d' % self.request_number, service, *args) self.request_number += 1 self.requests.append(wrapper) if self.logger: self.logger.debug('Adding request %s%r', wrapper.service, args) return wrapper def removeRequest(self, service, *args): """ Removes a request from the pending request list. """ if isinstance(service, RequestWrapper): if self.logger: self.logger.debug('Removing request: %s', self.requests[self.requests.index(service)]) del self.requests[self.requests.index(service)] return for request in self.requests: if request.service == service and request.args == args: if self.logger: self.logger.debug('Removing request: %s', self.requests[self.requests.index(request)]) del self.requests[self.requests.index(request)] return raise LookupError("Request not found") def getAMFRequest(self, requests): """ Builds an AMF request {LEnvelope<pyamf.remoting.Envelope>} from a supplied list of requests. """ envelope = remoting.Envelope(self.amf_version) if self.logger: self.logger.debug('AMF version: %s' % self.amf_version) for request in requests: service = request.service args = list(request.args) envelope[request.id] = remoting.Request(str(service), args) envelope.headers = self.headers return envelope def _get_execute_headers(self): headers = self.http_headers.copy() headers.update({ 'Content-Type': remoting.CONTENT_TYPE, 'User-Agent': self.user_agent }) if self.referer is not None: headers['Referer'] = self.referer return headers def execute_single(self, request): """ Builds, sends and handles the response to a single request, returning the response. """ if self.logger: self.logger.debug('Executing single request: %s', request) self.removeRequest(request) body = remoting.encode(self.getAMFRequest([request]), strict=self.strict) http_request = urllib2.Request(self._root_url, body.getvalue(), self._get_execute_headers()) if self.proxy_args: http_request.set_proxy(*self.proxy_args) envelope = self._getResponse(http_request) return envelope[request.id] def execute(self): """ Builds, sends and handles the responses to all requests listed in C{self.requests}. """ requests = self.requests[:] for r in requests: self.removeRequest(r) body = remoting.encode(self.getAMFRequest(requests), strict=self.strict) http_request = urllib2.Request(self._root_url, body.getvalue(), self._get_execute_headers()) if self.proxy_args: http_request.set_proxy(*self.proxy_args) envelope = self._getResponse(http_request) return envelope def _getResponse(self, http_request): """ Gets and handles the HTTP response from the remote gateway. """ if self.logger: self.logger.debug('Sending POST request to %s', self._root_url) try: fbh = self.opener(http_request) except urllib2.URLError, e: if self.logger: self.logger.exception('Failed request for %s', self._root_url) raise remoting.RemotingError(str(e)) http_message = fbh.info() content_encoding = http_message.getheader('Content-Encoding') content_length = http_message.getheader('Content-Length') or -1 content_type = http_message.getheader('Content-Type') server = http_message.getheader('Server') if self.logger: self.logger.debug('Content-Type: %r', content_type) self.logger.debug('Content-Encoding: %r', content_encoding) self.logger.debug('Content-Length: %r', content_length) self.logger.debug('Server: %r', server) if content_type != remoting.CONTENT_TYPE: if self.logger: self.logger.debug('Body = %s', fbh.read()) raise remoting.RemotingError('Incorrect MIME type received. ' '(got: %s)' % (content_type,)) bytes = fbh.read(int(content_length)) if self.logger: self.logger.debug('Read %d bytes for the response', len(bytes)) if content_encoding and content_encoding.strip().lower() == 'gzip': if not GzipFile: raise remoting.RemotingError( 'Decompression of Content-Encoding: %s not available.' % ( content_encoding,)) compressedstream = StringIO(bytes) gzipper = GzipFile(fileobj=compressedstream) bytes = gzipper.read() gzipper.close() response = remoting.decode(bytes, strict=self.strict) if self.logger: self.logger.debug('Response: %s', response) if remoting.APPEND_TO_GATEWAY_URL in response.headers: self.original_url += response.headers[remoting.APPEND_TO_GATEWAY_URL] self._setUrl(self.original_url) elif remoting.REPLACE_GATEWAY_URL in response.headers: self.original_url = response.headers[remoting.REPLACE_GATEWAY_URL] self._setUrl(self.original_url) if remoting.REQUEST_PERSISTENT_HEADER in response.headers: data = response.headers[remoting.REQUEST_PERSISTENT_HEADER] for k, v in data.iteritems(): self.headers[k] = v return response def setCredentials(self, username, password): """ Sets authentication credentials for accessing the remote gateway. """ self.addHeader('Credentials', dict(userid=username.decode('utf-8'), password=password.decode('utf-8')), True)
Python
# Copyright (c) The PyAMF Project. # See LICENSE.txt for details. """ AMF3 RemoteObject support. @see: U{RemoteObject on LiveDocs <http://livedocs.adobe.com/flex/3/langref/mx/rpc/remoting/RemoteObject.html>} @since: 0.1.0 """ import calendar import time import uuid import sys import pyamf.python from pyamf import remoting from pyamf.flex import messaging class BaseServerError(pyamf.BaseError): """ Base server error. """ class ServerCallFailed(BaseServerError): """ A catchall error. """ _amf_code = 'Server.Call.Failed' def generate_random_id(): return str(uuid.uuid4()) def generate_acknowledgement(request=None): ack = messaging.AcknowledgeMessage() ack.messageId = generate_random_id() ack.clientId = generate_random_id() ack.timestamp = calendar.timegm(time.gmtime()) if request: ack.correlationId = request.messageId return ack def generate_error(request, cls, e, tb, include_traceback=False): """ Builds an L{ErrorMessage<pyamf.flex.messaging.ErrorMessage>} based on the last traceback and the request that was sent. """ import traceback if hasattr(cls, '_amf_code'): code = cls._amf_code else: code = cls.__name__ details = None rootCause = None if include_traceback: details = traceback.format_exception(cls, e, tb) rootCause = e faultDetail = None faultString = None if hasattr(e, 'message'): faultString = unicode(e.message) elif hasattr(e, 'args') and e.args: if isinstance(e.args[0], pyamf.python.str_types): faultString = unicode(e.args[0]) if details: faultDetail = unicode(details) return messaging.ErrorMessage( messageId=generate_random_id(), clientId=generate_random_id(), timestamp=calendar.timegm(time.gmtime()), correlationId=request.messageId, faultCode=code, faultString=faultString, faultDetail=faultDetail, extendedData=details, rootCause=rootCause) class RequestProcessor(object): def __init__(self, gateway): self.gateway = gateway def buildErrorResponse(self, request, error=None): """ Builds an error response. @param request: The AMF request @type request: L{Request<pyamf.remoting.Request>} @return: The AMF response @rtype: L{Response<pyamf.remoting.Response>} """ if error is not None: cls, e, tb = error else: cls, e, tb = sys.exc_info() return generate_error(request, cls, e, tb, self.gateway.debug) def _getBody(self, amf_request, ro_request, **kwargs): """ @raise ServerCallFailed: Unknown request. """ if isinstance(ro_request, messaging.CommandMessage): return self._processCommandMessage(amf_request, ro_request, **kwargs) elif isinstance(ro_request, messaging.RemotingMessage): return self._processRemotingMessage(amf_request, ro_request, **kwargs) elif isinstance(ro_request, messaging.AsyncMessage): return self._processAsyncMessage(amf_request, ro_request, **kwargs) else: raise ServerCallFailed("Unknown request: %s" % ro_request) def _processCommandMessage(self, amf_request, ro_request, **kwargs): """ @raise ServerCallFailed: Unknown Command operation. @raise ServerCallFailed: Authorization is not supported in RemoteObject. """ ro_response = generate_acknowledgement(ro_request) if ro_request.operation == messaging.CommandMessage.PING_OPERATION: ro_response.body = True return remoting.Response(ro_response) elif ro_request.operation == messaging.CommandMessage.LOGIN_OPERATION: raise ServerCallFailed("Authorization is not supported in RemoteObject") elif ro_request.operation == messaging.CommandMessage.DISCONNECT_OPERATION: return remoting.Response(ro_response) else: raise ServerCallFailed("Unknown Command operation %s" % ro_request.operation) def _processAsyncMessage(self, amf_request, ro_request, **kwargs): ro_response = generate_acknowledgement(ro_request) ro_response.body = True return remoting.Response(ro_response) def _processRemotingMessage(self, amf_request, ro_request, **kwargs): ro_response = generate_acknowledgement(ro_request) service_name = ro_request.operation if hasattr(ro_request, 'destination') and ro_request.destination: service_name = '%s.%s' % (ro_request.destination, service_name) service_request = self.gateway.getServiceRequest(amf_request, service_name) # fire the preprocessor (if there is one) self.gateway.preprocessRequest(service_request, *ro_request.body, **kwargs) ro_response.body = self.gateway.callServiceRequest(service_request, *ro_request.body, **kwargs) return remoting.Response(ro_response) def __call__(self, amf_request, **kwargs): """ Processes an AMF3 Remote Object request. @param amf_request: The request to be processed. @type amf_request: L{Request<pyamf.remoting.Request>} @return: The response to the request. @rtype: L{Response<pyamf.remoting.Response>} """ ro_request = amf_request.body[0] try: return self._getBody(amf_request, ro_request, **kwargs) except (KeyboardInterrupt, SystemExit): raise except: return remoting.Response(self.buildErrorResponse(ro_request), status=remoting.STATUS_ERROR)
Python