def __init__(self, port, gamer): """ generated source for method __init__ """ super(ProxyGamePlayer, self).__init__() # Use a random gamer as our "default" gamer, that we fall back to # in the event that we don't get a message from the client, or if # we need to handle a simple request (START or STOP). self.theDefaultGamer = RandomGamer() self.observers = ArrayList() self.listener = None while self.listener == None: try: self.listener = ServerSocket(port) except Exception as ex: self.listener = None port += 1 GamerLogger.logError("Proxy", "Failed to start gamer on port: " + (port - 1) + " trying port " + port) self.myPort = port # Start up the socket for communicating with clients clientPort = 17147 while self.clientListener == None: try: self.clientListener = ServerSocket(clientPort) except Exception as ex: self.clientListener = None clientPort += 1 GamerLogger.log("Proxy", "[PROXY] Opened client communication socket on port " + clientPort + ".") # Start up the first ProxyClient self.gamerName = gamer.getSimpleName()
def abort(self): """ generated source for method abort """ try: self.stateMachineAbort() except Exception as e: GamerLogger.logStackTrace("GamePlayer", e) raise AbortingException(e)
def process(self, receptionTime): """ generated source for method process """ # Ensure that we aren't already playing a match. If we are, # ignore the message, saying that we're busy. if self.gamer.getMatch() != None: GamerLogger.logError("GamePlayer", "Got start message while already busy playing a game: ignoring.") self.gamer.notifyObservers(GamerUnrecognizedMatchEvent(self.matchId)) return "busy" # Create the new match, and handle all of the associated logistics # in the gamer to indicate that we're starting a new match. match = Match(self.matchId, -1, self.startClock, self.playClock, self.game) self.gamer.setMatch(match) self.gamer.setRoleName(self.roleName) self.gamer.notifyObservers(GamerNewMatchEvent(match, self.roleName)) # Finally, have the gamer begin metagaming. try: self.gamer.notifyObservers(PlayerTimeEvent(self.gamer.getMatch().getStartClock() * 1000)) self.gamer.metaGame(self.gamer.getMatch().getStartClock() * 1000 + receptionTime) except MetaGamingException as e: GamerLogger.logStackTrace("GamePlayer", e) # Upon encountering an uncaught exception during metagaming, # assume that indicates that we aren't actually able to play # right now, and tell the server that we're busy. self.gamer.setMatch(None) self.gamer.setRoleName(None) return "busy" return "ready"
def create(cls, description): """ generated source for method create """ try: GamerLogger.log("StateMachine", "Converting...") return PropNetConverter().convert(Role.computeRoles(description), flatDescription) except Exception as e: GamerLogger.logStackTrace("StateMachine", e) return None
def renderToFile(self, filename): """ generated source for method renderToFile """ try: fout.write(self.__str__()) fout.close() fos.close() except Exception as e: GamerLogger.logStackTrace("StateMachine", e)
def preview(self, game, timeout): """ generated source for method preview """ self.lazilyLoadGamerStub() try: self.theClojureGamer.preview(game, timeout) except GamePreviewException as e: GamerLogger.logError("GamePlayer", "Caught exception in Clojure stateMachineMetaGame:") GamerLogger.logStackTrace("GamePlayer", e)
def lazilyLoadGamerStub(self): """ generated source for method lazilyLoadGamerStub """ if self.thePythonGamer == None: try: # Load in the Python gamer, using a Jython intepreter. interpreter.exec_("from " + self.getPythonGamerModule() + " import " + self.getPythonGamerName()) self.thePythonGamer = PyGamerObject.__tojava__(Gamer.__class__) except Exception as e: GamerLogger.logError("GamePlayer", "Caught exception in Python initialization:") GamerLogger.logStackTrace("GamePlayer", e)
def getGoal(self, state, role): """ generated source for method getGoal """ results = self.prover.askAll(ProverQueryBuilder.getGoalQuery(role), ProverQueryBuilder.getContext(state)) if len(results) != 1: GamerLogger.logError("StateMachine", "Got goal results of size: " + len(results) + " when expecting size one.") raise GoalDefinitionException(state, role) try: return Integer.parseInt(constant.__str__()) except Exception as e: raise GoalDefinitionException(state, role)
def abort(self): """ generated source for method abort """ self.lazilyLoadGamerStub() self.theClojureGamer.setMatch(getMatch()) self.theClojureGamer.setRoleName(getRoleName()) try: self.theClojureGamer.abort() except AbortingException as e: GamerLogger.logError("GamePlayer", "Caught exception in Clojure stateMachineAbort:") GamerLogger.logStackTrace("GamePlayer", e)
def metaGame(self, timeout): """ generated source for method metaGame """ self.lazilyLoadGamerStub() self.theClojureGamer.setMatch(getMatch()) self.theClojureGamer.setRoleName(getRoleName()) try: self.theClojureGamer.metaGame(timeout) except MetaGamingException as e: GamerLogger.logError("GamePlayer", "Caught exception in Clojure stateMachineMetaGame:") GamerLogger.logStackTrace("GamePlayer", e)
def stop(self): """ generated source for method stop """ self.lazilyLoadGamerStub() self.thePythonGamer.setMatch(getMatch()) self.thePythonGamer.setRoleName(getRoleName()) try: self.thePythonGamer.stop() except StoppingException as e: GamerLogger.logError("GamePlayer", "Caught exception in Python stateMachineStop:") GamerLogger.logStackTrace("GamePlayer", e)
def selectMove(self, timeout): """ generated source for method selectMove """ self.lazilyLoadGamerStub() self.theClojureGamer.setMatch(getMatch()) self.theClojureGamer.setRoleName(getRoleName()) try: return self.theClojureGamer.selectMove(timeout) except MoveSelectionException as e: GamerLogger.logError("GamePlayer", "Caught exception in Clojure stateMachineSelectMove:") GamerLogger.logStackTrace("GamePlayer", e) return None
def closeClient(self): """ generated source for method closeClient """ try: self.outConnector.pleaseStop = True self.errConnector.pleaseStop = True self.theClientConnection.close() self.theInput = None self.theOutput = None except IOException as e: GamerLogger.logStackTrace("Proxy", e) self.theClientProcess.destroy()
def lazilyLoadGamerStub(self): """ generated source for method lazilyLoadGamerStub """ if self.theClojureGamer == None: try: # Load the Clojure script -- as a side effect this initializes the runtime. RT.loadResourceScript(self.getClojureGamerFile() + ".clj") # Get a reference to the gamer-generating function. # Call it! self.theClojureGamer = gamerVar.invoke() except Exception as e: GamerLogger.logError("GamePlayer", "Caught exception in Clojure initialization:") GamerLogger.logStackTrace("GamePlayer", e)
def metaGame(self, timeout): """ generated source for method metaGame """ try: stateMachine = self.getInitialStateMachine() stateMachine.initialize(getMatch().getGame().getRules()) currentState = stateMachine.getInitialState() role = stateMachine.getRoleFromConstant(getRoleName()) getMatch().appendState(currentState.getContents()) self.stateMachineMetaGame(timeout) except Exception as e: GamerLogger.logStackTrace("GamePlayer", e) raise MetaGamingException(e)
def attemptLoadingInitialMachine(self): """ generated source for method attemptLoadingInitialMachine """ try: self.theBackingMachine.initialize(self.gameDescription) GamerLogger.log("StateMachine", "Failsafe Machine: successfully activated initial state machine for use!") return True except Exception as e1: pass except ThreadDeath as d: raise d except Error as e2: pass return False
def flatten(self): """ generated source for method flatten """ self.description = DeORer.run(self.description) if noAnnotations(): GamerLogger.log("StateMachine", "Could not find 'base' annotations. Attempting to generate them...") self.description = PropNetAnnotater(self.description).getAugmentedDescription() GamerLogger.log("StateMachine", "Annotations generated.") self.templates = recordTemplates(self.description) self.instantiations = initializeInstantiations(self.description) flatDescription = ArrayList() for constant in templates.keySet(): flatDescription.addAll(getInstantiations(constant)) return flatDescription
def selectMove(self, timeout): """ generated source for method selectMove """ try: stateMachine.doPerMoveWork() if lastMoves != None: for sentence in lastMoves: moves.add(stateMachine.getMoveFromTerm(sentence)) currentState = stateMachine.getNextState(currentState, moves) getMatch().appendState(currentState.getContents()) return self.stateMachineSelectMove(timeout).getContents() except Exception as e: GamerLogger.logStackTrace("GamePlayer", e) raise MoveSelectionException(e)
def stop(self): """ generated source for method stop """ try: stateMachine.doPerMoveWork() if lastMoves != None: for sentence in lastMoves: moves.add(stateMachine.getMoveFromTerm(sentence)) currentState = stateMachine.getNextState(currentState, moves) getMatch().appendState(currentState.getContents()) getMatch().markCompleted(stateMachine.getGoals(currentState)) self.stateMachineStop() except Exception as e: GamerLogger.logStackTrace("GamePlayer", e) raise StoppingException(e)
def proxyProcessRequest(self, theRequest, receptionTime): """ generated source for method proxyProcessRequest """ startSleeping = System.currentTimeMillis() timeToFinish = receptionTime timeToSleep = 0L try: if isinstance(theRequest, (PlayRequest, )): if self.theDefaultGamer.getMatch() != None: timeToFinish = receptionTime + self.theDefaultGamer.getMatch().getPlayClock() * 1000 - self.PLAY_BUFFER else: timeToFinish = System.currentTimeMillis() timeToSleep = timeToFinish - System.currentTimeMillis() if timeToSleep > 0: Thread.sleep(timeToSleep) elif isinstance(theRequest, (StartRequest, )): GamerLogger.startFileLogging(self.theDefaultGamer.getMatch(), self.theDefaultGamer.getRoleName().__str__()) print "Started playing " + self.theDefaultGamer.getMatch().getMatchId() + "." timeToFinish = receptionTime + self.theDefaultGamer.getMatch().getStartClock() * 1000 - self.METAGAME_BUFFER timeToSleep = timeToFinish - System.currentTimeMillis() if timeToSleep > 0: Thread.sleep(timeToSleep) elif isinstance(theRequest, (StopRequest, )) or isinstance(theRequest, (AbortRequest, )): GamerLogger.stopFileLogging() self.needRestart = True except InterruptedException as ie: GamerLogger.log("Proxy", "[PROXY] Got woken up by final move!") GamerLogger.log("Proxy", "[PROXY] Proxy slept for " + (System.currentTimeMillis() - startSleeping) + ", and woke up " + (System.currentTimeMillis() - timeToFinish) + "ms late (started " + (startSleeping - receptionTime) + "ms after receiving message).")
def switchStateMachine(self, newStateMachine): """ generated source for method switchStateMachine """ try: # Attempt to run through the game history in the new machine for nextMove in theMoveHistory: for theSentence in nextMove: theJointMove.add(newStateMachine.getMoveFromTerm(theSentence)) newCurrentState = newStateMachine.getNextStateDestructively(newCurrentState, theJointMove) # Finally, switch over if everything went well. role = newRole currentState = newCurrentState stateMachine = newStateMachine except Exception as e: GamerLogger.log("GamePlayer", "Caught an exception while switching state machine!") GamerLogger.logStackTrace("GamePlayer", e)
def attemptLoadingProverMachine(self): """ generated source for method attemptLoadingProverMachine """ try: theStateMachine.initialize(self.gameDescription) self.theBackingMachine = theStateMachine GamerLogger.log("StateMachine", "Failsafe Machine: successfully loaded traditional prover.") return True except Exception as e1: pass except ThreadDeath as d: raise d except OutOfMemoryError as e: raise e except Error as e2: pass return False
def process(self, receptionTime): """ generated source for method process """ # First, check to ensure that this play request is for the match # we're currently playing. If we're not playing a match, or we're # playing a different match, send back "busy". if self.gamer.getMatch() == None or not self.gamer.getMatch().getMatchId() == self.matchId: self.gamer.notifyObservers(GamerUnrecognizedMatchEvent(self.matchId)) GamerLogger.logError("GamePlayer", "Got play message not intended for current game: ignoring.") return "busy" if self.moves != None: self.gamer.getMatch().appendMoves(self.moves) try: self.gamer.notifyObservers(PlayerTimeEvent(self.gamer.getMatch().getPlayClock() * 1000)) return self.gamer.selectMove(self.gamer.getMatch().getPlayClock() * 1000 + receptionTime).__str__() except MoveSelectionException as e: GamerLogger.logStackTrace("GamePlayer", e) return "nil"
def process(self, receptionTime): """ generated source for method process """ # First, check to ensure that this abort request is for the match # we're currently playing. If we're not playing a match, or we're # playing a different match, send back "busy". if self.gamer.getMatch() == None or not self.gamer.getMatch().getMatchId() == self.matchId: GamerLogger.logError("GamePlayer", "Got abort message not intended for current game: ignoring.") self.gamer.notifyObservers(GamerUnrecognizedMatchEvent(self.matchId)) return "busy" self.gamer.getMatch().markAborted() self.gamer.notifyObservers(GamerAbortedMatchEvent()) try: self.gamer.abort() except AbortingException as e: GamerLogger.logStackTrace("GamePlayer", e) self.gamer.setRoleName(None) self.gamer.setMatch(None) return "aborted"
def failGracefully(self, e1, e2): """ generated source for method failGracefully """ if e1 != None: GamerLogger.logStackTrace("StateMachine", e1) if e2 != None: GamerLogger.logStackTrace("StateMachine", e2) GamerLogger.logError("StateMachine", "Failsafe Machine: graceful failure mode kicking in.") if self.theBackingMachine.__class__ != ProverStateMachine.__class__: GamerLogger.logError( "StateMachine", "Failsafe Machine: online failure for " + self.theBackingMachine.__class__ + ". Attempting to restart with a standard prover.", ) if attemptLoadingProverMachine(): return self.theBackingMachine = None GamerLogger.logError("StateMachine", "Failsafe Machine: online failure for regular prover. Cannot recover.")
def updateDomains(self): """ generated source for method updateDomains """ changedSomething = True itrNum = 0 lastUpdatedDomains = HashSet(self.domains.values()) while changedSomething: GamerLogger.log("StateMachine", "Beginning domain finding iteration: " + itrNum) changedSomething = False for d in domains.values(): for ruleRef in d.ruleRefs: for c in ruleRef.conditions: if lastUpdatedDomains.contains(c.dom): containsUpdatedDomain = True break if not containsUpdatedDomain: continue rulesConsidered += 1 for instantiation in instantiations: for t in ruleRef.productionTemplate: if isinstance(t, (GdlConstant, )): a.add(t) else: a.add(instantiation.get(var)) if not d.assignments.contains(a): currUpdatedDomains.add(d) d.assignments.add(a) changedSomething = True d.addAssignmentToIndex(a) if len(instantiations) == 0: findSatisfyingInstantiations(ruleRef) for t in ruleRef.productionTemplate: if isinstance(t, (GdlConstant, )): a.add(t) else: isVar = True break if not isVar and not d.assignments.contains(a): currUpdatedDomains.add(d) d.assignments.add(a) changedSomething = True d.addAssignmentToIndex(a) itrNum += 1 lastUpdatedDomains = currUpdatedDomains GamerLogger.log("StateMachine", "\tDone with iteration. Considered " + rulesConsidered + " rules.")
def readFrom(cls, theInput): """ generated source for method readFrom """ try: return ProxyMessage(cls.theMessage, cls.messageCode, cls.receptionTime) except SocketException as se: GamerLogger.log("Proxy", "[ProxyMessage Reader] Socket closed: stopping read operation.") raise se except Exception as e: GamerLogger.logStackTrace("Proxy", e) GamerLogger.logError("Proxy", "[ProxyMessage Reader] Could not digest message. Emptying stream.") try: # TODO: Fix this, I suspect it may be buggy. theInput.skip(Long.MAX_VALUE) except SocketException as se: GamerLogger.log("Proxy", "[ProxyMessage Reader] Socket closed: stopping read operation.") raise se except Exception as ie: GamerLogger.logStackTrace("Proxy", ie) return None
def run(self): """ generated source for method run """ while self.theInput != None: try: if self.pleaseStop: return GamerLogger.log("Proxy", "[PROXY] Got message from client: " + in_) if in_ == None: continue processClientResponse(in_, self.parentThread) except SocketException as se: if self.expectStop: return GamerLogger.logStackTrace("Proxy", se) GamerLogger.logError("Proxy", "Shutting down reader as consequence of socket exception. Presumably this is because the gamer client crashed.") break except Exception as e: GamerLogger.logStackTrace("Proxy", e) except Error as e: GamerLogger.logStackTrace("Proxy", e)
def process(self, receptionTime): """ generated source for method process """ # Ensure that we aren't already playing a match. If we are, # ignore the message, saying that we're busy. if self.gamer.getMatch() != None: GamerLogger.logError("GamePlayer", "Got preview message while already busy playing a game: ignoring.") # gamer.notifyObservers(new GamerUnrecognizedMatchEvent(matchId)); return "busy" # Otherwise, if we're not busy, have the gamer start previewing. try: # gamer.notifyObservers(new PlayerTimeEvent(gamer.getMatch().getStartClock() * 1000)); self.gamer.preview(self.game, self.previewClock * 1000 + receptionTime) # gamer.metaGame(gamer.getMatch().getStartClock() * 1000 + receptionTime); except GamePreviewException as e: GamerLogger.logStackTrace("GamePlayer", e) # Upon encountering an uncaught exception during previewing, # assume that indicates that we aren't actually able to play # right now, and tell the server that we're busy. return "busy" return "ready"
def run(self): """ generated source for method run """ while True: try: if self.inputQueue.remainingCapacity() > 0: self.inputQueue.add(ProxyMessage(in_, 0L, receptionTime)) self.inputConnectionQueue.add(connection) GamerLogger.log("Proxy", "[PROXY QueueListener] Got incoming message from game server: " + in_ + ". Added to queue in position " + len(self.inputQueue) + ".") else: GamerLogger.logError("Proxy", "[PROXY QueueListener] Got incoming message from game server: " + in_ + ". Could not add to queue, because queue is full!") except Exception as e: GamerLogger.logStackTrace("Proxy", e) except Error as e: GamerLogger.logStackTrace("Proxy", e)