Esempio n. 1
0
    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)
Esempio n. 2
0
File: layout.py Progetto: fha/RL
 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)
Esempio n. 3
0
	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
Esempio n. 4
0
 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
Esempio n. 5
0
File: layout.py Progetto: fha/RL
 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
Esempio n. 6
0
    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"
        }
Esempio n. 7
0
    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]
Esempio n. 8
0
    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
Esempio n. 9
0
    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)))
Esempio n. 10
0
 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)
Esempio n. 11
0
 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"
     }
Esempio n. 12
0
    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)))
Esempio n. 13
0
    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
Esempio n. 14
0
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())))
Esempio n. 15
0
 def chooseAction(self, observedState):
     legalActs = observedState.getLegalPacmanActions()
     return random.choice(legalActs)
Esempio n. 16
0
 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)
Esempio n. 17
0
    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
Esempio n. 18
0
 def random(self):
     return random.choice(self.all)
Esempio n. 19
0
 def random_tag(self, tag):
     if tag not in self.tags:
         return ""
     return random.choice(self.tags[tag])
Esempio n. 20
0
 def random_uncountable(self):
     return random.choice(self.uncountable)
Esempio n. 21
0
	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
Esempio n. 22
0
 def getAction( self, state ):
     """
     Ghost moves randomly given the set of possible moves
     """
     return random.choice( state.getLegalActions( self.index ) )
Esempio n. 23
0
	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)
Esempio n. 24
0
 def getAction(self, state):
     """
     Ghost moves randomly given the set of possible moves
     """
     return random.choice(state.getLegalActions(self.index))
Esempio n. 25
0
	def random(self):
		return random.choice(self.all)
Esempio n. 26
0
	def random_tag(self, tag):
		if tag not in self.tags:
			return ""
		return random.choice(self.tags[tag])
Esempio n. 27
0
	def random_uncountable(self):
		return random.choice(self.uncountable)
Esempio n. 28
0
File: layout.py Progetto: fha/RL
 def getRandomCorner(self):
     poses = [(1,1), (1, self.height - 2), (self.width - 2, 1), (self.width - 2, self.height - 2)]
     return random.choice(poses)
Esempio n. 29
0
 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