def run(self): """ 项目主程序外部调用接口 """ distance = config.getfloat("Joyrun", "distance") # 总距离 km pace = config.getfloat("Joyrun", "pace") # 速度 min/km stride_frequncy = config.getint("Joyrun", "stride_frequncy") # 步频 step/min record_type = config.get("Joyrun", "record_type") # 跑步记录类型 record_number = config.getint("Joyrun", "record_number") # 跑步记录编号 if record_type == "54": record_instances = record.__Record_54_Instance__ elif record_type == "wmlake": record_instances = record.__Record_WMLake_Instance__ elif record_type == "random": record_instances = getattr( record, random.choice( ["__Record_54_Instance__", "__Record_WMLake_Instance__"])) else: raise RecordTypeError( "unsupport record type '%s' ! valid type = ['54','wmlake','random']" % record_type) if record_number == 0: Record = getattr(record, random.choice(record_instances)) elif record_number < 0 or record_number > len(record_instances): raise RecordNumberError( "invalid record number '%s' ! valid range = [0,%s]" % (record_number, len(record_instances))) else: Record = getattr(record, record_instances[record_number - 1]) _record = Record(distance, pace, stride_frequncy) self.upload_record(_record)
def getRandomLegalPosition(self): x = random.choice(range(self.width)) y = random.choice(range(self.height)) while self.isWall( (x, y) ): x = random.choice(range(self.width)) y = random.choice(range(self.height)) return (x,y)
def random(self): out = random.choice(self.starts) while len(out) < 20: ctx = self.chain for symb in out[-self.order:]: if symb not in ctx: return out ctx = ctx[symb] out.append(random.choice(ctx.keys())) return out
def getRandomDistinctLegalPositions(self, k): """ k is the number of distinct positions; useful if you need to place things that can't overlap (e.g., capsules) returns a set of positions """ chosen = set() xs = range(self.width) ys = range(self.height) while len(chosen) < k: x = random.choice(xs) y = random.choice(ys) if not self.isWall((x,y)): chosen.add((x,y)) return chosen
def __build_classtime_action(self, data): # cards in play: actor_data = self._get_me(data) cards_in_play = actor_data["in_play_effects"]["cards_in_play"] cards_in_play_names = ", ".join(["'{}'".format(c["template"]["name"]) for c in cards_in_play]) self.__think("My cards in play: {}".format(cards_in_play_names)) turn = data["public"]["turn"] card_id = self.__get_card_id(turn, actor_data["hand"]) prompt = turn["prompt"] open_items = list(prompt["open"].items()) for answer_key, open_prompt in open_items: prompt_options = open_prompt["options"] self.__enumerate_options(answer_key, prompt_options) if not prompt_options: self.__think("Skipping prompt", prompt["id"], "for card", card_id, "... no options") self.__set_card_prompt_map(prompt["id"], None) return selection = choice(prompt_options) prompt = self.answer(answer_key, prompt, selection) return { "card_id": card_id, "prompt": prompt, "type": "ActionCardAction" }
def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [ self.evaluationFunction(gameState, action) for action in legalMoves ] bestScore = max(scores) bestIndices = [ index for index in range(len(scores)) if scores[index] == bestScore ] chosenIndex = random.choice( bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex]
def chooseAction(self, observedState): legalActs = [a for a in observedState.getLegalPacmanActions()] # print legalActs act = random.choice(legalActs) # print (act,response_lst[dir_dict[act]]) # g_pos = map(lambda x : x.getPosition(),observedState.getGhostStates()) # p_pos = observedState.getPacmanPosition() # if(filter(lambda x: x == p_pos,g_pos) != []): # print g_pos # print p_pos print observedState.getNumMovesLeft() return act
def praise_eq(self, ch): items = ch.items fancy_items = [item for item in items if item.cost > 50000 and item.isWorn] if not fancy_items: return item = random.choice(fancy_items) desc = item.short_desc if desc.startswith("an"): desc = desc[3:] elif desc.startswith("a"): desc = desc[2:] elif desc.startswith("the"): desc = desc[4:] self.say("Oh, that's a nice {+%s{= you have there, %s." % (desc, self.pers(ch)))
def execute(self, data, start): register_exit_hook(data["public"]["game_id"]) if not data["complete"]: actors = self.__generate_actors(data) Logger.log("Starting game", data["public"]["game_id"], level=LogLevel.Info, log_type=LogType.TestRunner) actor = choice(actors) while True: actor_id = actor.take_turn_if_possible() if not actor_id: break actor = self.get_actor_by_id(actor_id, actors) elapsed = datetime.utcnow() - start complete_msg = "Done! Game ID: {}".format(data["public"]["game_id"]) Logger.log(complete_msg, level=LogLevel.Info, log_type=LogType.TestRunner) performance_msg = "Processing took {}s".format(elapsed.total_seconds()) Logger.log(performance_msg, level=LogLevel.Info, log_type=LogType.TestRunner)
def __build_dismissal_action(self, data): turn = data["public"]["turn"] prompt = turn["prompt"] open_items = list(prompt["open"].items()) for answer_key, open_prompt in open_items: prompt_options = open_prompt["options"] self.__enumerate_options(answer_key, prompt_options) if not prompt_options: self.__think("Skipping discipline prompt", prompt["pending"], "... no options") return selection = choice(prompt_options) prompt = self.answer(answer_key, prompt, selection) return { "prompt": prompt, "type": "DisciplineAction" }
def praise_eq(self, ch): items = ch.items fancy_items = [ item for item in items if item.cost > 50000 and item.isWorn ] if not fancy_items: return item = random.choice(fancy_items) desc = item.short_desc if desc.startswith("an"): desc = desc[3:] elif desc.startswith("a"): desc = desc[2:] elif desc.startswith("the"): desc = desc[4:] self.say("Oh, that's a nice {+%s{= you have there, %s." % (desc, self.pers(ch)))
def getAction( self, state): from graphicsUtils import keys_waiting from graphicsUtils import keys_pressed keys = keys_waiting() + keys_pressed() if keys != []: self.keys = keys legal = state.getLegalActions(self.index) move = self.getMove(legal) if move == Directions.STOP: # Try to move in the same direction as before if self.lastMove in legal: move = self.lastMove if (self.STOP_KEY in self.keys) and Directions.STOP in legal: move = Directions.STOP if move not in legal: move = random.choice(legal) self.lastMove = move return move
def compile(): global markov_names, nouns, adjectives, prefixes, verbs markov_names = create_generator("lang/names.txt", 3) nouns = _Nouns("lang/nouns.txt") adjectives = _load_data("lang/adjectives.txt") prefixes = _load_data("lang/name_prefixes.txt") verbs = _Verbs("lang/verbs.txt") ################################################# _noun = Func(lambda: nouns.random().singular) # Names _rname = Func(lambda: "".join(markov_names.random())[:7].capitalize()) _radjective = Func(lambda: random.choice(adjectives).capitalize()) _rprefix = Func(lambda: random.choice(prefixes).capitalize()) random_name = Choice( Phrase( _rprefix, Choice(Concat(_radjective, _noun), _rname, _radjective), ), Phrase(_rname, _rname), Phrase(_rname, "the", _radjective)) # Items item_name = Choice( Phrase(Func(lambda: nouns.random().singular.capitalize()), "of", Func(lambda: verbs.random().pres_particip.capitalize())), Phrase(_radjective, Func(lambda: nouns.random().singular.capitalize())), Phrase(Func(lambda: verbs.random().past.capitalize()), Func(lambda: nouns.random().singular.capitalize())))
def chooseAction(self, observedState): legalActs = observedState.getLegalPacmanActions() return random.choice(legalActs)
def evaluate(self, args): if len(self.data) == 1 and hasattr(self.data[0], "__getitem__"): return self.string(random.choice(self.data[0]), args) return self.string(random.choice(self.data), args)
def chooseActionByHeuristic(self, observedState): global badGhost pacDirs = [d for d in observedState.getLegalPacmanActions() if d != Directions.STOP] rDir = random.choice(pacDirs) if not badGhost: return rDir pacPos = observedState.getPacmanPosition() bgPos = badGhost.getPosition() bgDist = self.distancer.getDistance(pacPos, bgPos) goodGhosts = self.getGoodGhostInfo(observedState) goodCaps = self.getGoodCapInfo(observedState) if observedState.scaredGhostPresent(): for c in goodCaps: capBadDist = self.distancer.getDistance(c[1],bgPos) if c[0] + capBadDist == bgDist: dirs = self.getClosestDirs( observedState, pacDirs, c[1], c[0]) if dirs: return dirs[0] else: return rDir dirs = self.getClosestDirs( observedState, pacDirs, bgPos, bgDist) if dirs: return dirs[0] else: return rDir else: goodCaps = [c for c in goodCaps if c[0] < self.distancer.getDistance(c[1],bgPos)] if goodCaps: c = min(goodCaps) dirs = self.getClosestDirs(observedState,pacDirs,c[1],c[0]) if c[0] > 1 or bgDist <= BG_RANGE: if dirs: return dirs[0] else: return rDir else: return random.choice([d for d in pacDirs if d not in dirs]) else: if bgDist > HEUR_BG_RANGE: g = min(goodGhosts) dirs = self.getClosestDirs( observedState, pacDirs, g[1].getPosition(), g[0]) # TODO in ties? if dirs: return dirs[0] else: return rDir else: # TODO in tie - go toward bad capsule dirs = self.getFarthestDirs( observedState, pacDirs, bgPos, bgDist) if dirs: return dirs[0] else: return rDir
def random(self): return random.choice(self.all)
def random_tag(self, tag): if tag not in self.tags: return "" return random.choice(self.tags[tag])
def random_uncountable(self): return random.choice(self.uncountable)
global markov_names, nouns, adjectives, prefixes, verbs markov_names = create_generator("lang/names.txt", 3) nouns = _Nouns("lang/nouns.txt") adjectives = _load_data("lang/adjectives.txt") prefixes = _load_data("lang/name_prefixes.txt") verbs = _Verbs("lang/verbs.txt") ################################################# _noun = Func(lambda: nouns.random().singular) # Names _rname = Func(lambda: "".join(markov_names.random())[:7].capitalize()) _radjective = Func(lambda: random.choice(adjectives).capitalize()) _rprefix = Func(lambda: random.choice(prefixes).capitalize()) random_name = Choice( Phrase( _rprefix, Choice( Concat(_radjective, _noun), _rname, _radjective ), ), Phrase(_rname, _rname), Phrase(_rname, "the", _radjective) ) # Items
def getAction( self, state ): """ Ghost moves randomly given the set of possible moves """ return random.choice( state.getLegalActions( self.index ) )
def getAction(self, state): """ Ghost moves randomly given the set of possible moves """ return random.choice(state.getLegalActions(self.index))
def getRandomCorner(self): poses = [(1,1), (1, self.height - 2), (self.width - 2, 1), (self.width - 2, self.height - 2)] return random.choice(poses)
def __choose_card(self, hand): card_names = ", ".join(["'{}'".format(c["template"]["name"]) for c in hand]) self.__think("My hand: {}".format(card_names)) card_id = choice([ac["id"] for ac in hand]) self.__think("I choose card:", self.__get_card_details(card_id, hand)) return card_id