コード例 #1
0
    def apply_command_session(self, cmd):
        coords = cmd[1]
        coord = cmd[2]
        obs_coords = cmd[3]

        self.logger.add_message("Session starting !")
        players_coords = coords.split("|")
        for p in players_coords:
            [name, pos] = p.split(":")
            pos = parse_coord(pos)
            if (name in self.arena.players):
                self.arena.players[name].reset()
                self.arena.players[name].moveTo(pos[0], pos[1])
                self.arena.players[name].to_display = True
            else:
                self.arena.players[name] = Player("enemy.png", name, pos, True)
        goals_coord = coord.split("|")
        goalx, goaly = parse_coord(goals_coord[0])
        if (len(goals_coord) == 2):
            nextgoalx, nextgoaly = parse_coord(goals_coord[1])
            self.arena.next_goal = Goal(nextgoalx, nextgoaly, True)

        self.arena.goal = Goal(goalx, goaly)

        if (len(obs_coords) > 0):
            for o in obs_coords.split("|"):
                pos = parse_coord(o)
                self.arena.obstacles.append(Obstacle(pos[0], pos[1]))

        self.session_state = "jeu"
コード例 #2
0
ファイル: die.py プロジェクト: evanjtravis/dice
 def set_goal(self, goal):
     """Sets the goal of the dice to be used as a default for rolls.
     """
     if isinstance(goal, Goal):
         self.__goal = goal
     else:
         self.__goal = Goal(value=goal)
コード例 #3
0
ファイル: die.py プロジェクト: evanjtravis/dice
 def __check_goal(self):
     """Dice's goal should be checked by Goal class verification.
     """
     if isinstance(self.__goal, Goal):
         self.__goal.check_vars()
     elif self.__goal != None:
         self.__goal = Goal(self.__goal)
コード例 #4
0
    def apply_command_welcome(self, cmd):
        phase = cmd[1]
        scores = cmd[2]
        coord = cmd[3]
        obs_coords = cmd[4]

        if (phase == "attente"):
            self.logger.add_message("Waiting to start session")
            self.logger.add_message("Type /race to start a race next")
            self.session_state = "attente"
        elif (phase == "jeu" or phase == "ingame_race"):
            self.logger.add_message("Joining a game")
            self.session_state = "jeu"
            goals_coord = coord.split("|")
            goalx, goaly = parse_coord(goals_coord[0])
            if (len(goals_coord) == 2):
                nextgoalx, nextgoaly = parse_coord(goals_coord[1])
                self.arena.next_goal = Goal(nextgoalx, nextgoaly, True)
            else:
                self.arena.next_goal = None
            self.arena.goal = Goal(goalx, goaly)
            self.main_player.to_display = False  # Wait to get coord before displaying
            for s in scores.split("|"):
                [name, score] = s.split(":")
                if (name in self.arena.players):
                    self.arena.players[name].score = int(score)
                else:
                    new_player = Player("enemy.png", name)
                    new_player.score = int(score)
                    self.arena.players[name] = new_player

            if (len(obs_coords) > 0):
                for o in obs_coords.split("|"):
                    pos = parse_coord(o)
                    self.arena.obstacles.append(Obstacle(pos[0], pos[1]))
コード例 #5
0
 def __init__(self, owner):
     Goal.__init__(self, owner)
     self.process = None
     self._child_conn = multiprocessing.Pipe()
     self._term_event = multiprocessing.Event()
     self.process = multiprocessing.Process()
     self._start_time = None
コード例 #6
0
def getGoalArea(image):
    gol = Goal()
    tol = gol.find_goal_single_image(image)
    print("goal is at x = {}".format(tol))
    area = tol[2] * tol[3]
    print("The area is {}".format(area))

    return area
コード例 #7
0
ファイル: gengoal.py プロジェクト: mclumd/erewhon_systems
	def gen_goals(self, verbose):
		arsonist = self.free_arsonist()
		anomalous = self.mem.get(self.memKeys.MEM_ANOM)
		anomalous = anomalous and anomalous[-1]
		if arsonist and anomalous:
			goal = Goal(Goal.GOAL_APPREHEND, [arsonist])
			goal.priority = 2 #highest used
			return [goal]
		return []
コード例 #8
0
 def initialize_agent(self):
     """Initializing all parameters which require the field info"""
     self.my_goal = Goal(self.team, self.get_field_info())
     self.their_goal = Goal(1 - self.team, self.get_field_info())
     init_boostpads(self)
     """Setting all the mechanics to not none"""
     self.drive = Drive(self.info.my_car)
     self.dodge = Dodge(self.info.my_car)
     self.halfflip = HalfFlip(self.info.my_car)
コード例 #9
0
 def __init__(self, type):
     if type == "skills":
         self.goals.append(Goal(["blue", "blue"]))
         self.goals.append(Goal(["blue"]))
         self.goals.append(Goal(["blue", "blue"]))
         self.goals.append(Goal(["blue"]))
         self.goals.append(Goal(["blue", "blue", "blue"]))
         self.goals.append(Goal(["blue"]))
         self.goals.append(Goal(["blue", "blue"]))
         self.goals.append(Goal(["blue"]))
         self.goals.append(Goal(["blue", "blue"]))
         self.rows.append(Row([self.goals[0], self.goals[1],
                               self.goals[2]]))
         self.rows.append(Row([self.goals[3], self.goals[4],
                               self.goals[5]]))
         self.rows.append(Row([self.goals[6], self.goals[7],
                               self.goals[8]]))
         self.rows.append(Row([self.goals[0], self.goals[3],
                               self.goals[6]]))
         self.rows.append(Row([self.goals[1], self.goals[4],
                               self.goals[7]]))
         self.rows.append(Row([self.goals[2], self.goals[5],
                               self.goals[8]]))
         self.rows.append(Row([self.goals[0], self.goals[4],
                               self.goals[8]]))
         self.rows.append(Row([self.goals[2], self.goals[4],
                               self.goals[6]]))
コード例 #10
0
ファイル: user.py プロジェクト: julianpistorius/back-end-api
 def delete_goal(self, goal_id):
     user_node = self.user_node
     goal = Goal()
     goal.id = goal_id
     # have to remove all relationships before deleteing a node
     goal.delete_all_interests()
     goal_node = goal.goal_node
     user_goal_rel = self._graph_db.match_one(start_node=user_node,
                                             rel_type=GraphRelationship.HAS_GOAL,
                                             end_node=goal_node)
     self._graph_db.delete(user_goal_rel)
     self._graph_db.delete(goal_node)
コード例 #11
0
ファイル: gengoal.py プロジェクト: mclumd/erewhon_systems
	def gen_goals(self, verbose):
		world = self.mem.get(self.memKeys.MEM_STATES)[-1]
		block = self.random_fired_block(world)
		if not block:
			return []
		blocks = blockstate.get_block_list(world)
		for realblock in blocks:
			if realblock.id == block.name:
				block = realblock
				break
		goal = Goal(Goal.GOAL_NO_FIRE, [block])
		goal.priority = 1 #higher than stacking
		return [goal]
コード例 #12
0
    def apply_command_newobj(self, cmd):
        coord = cmd[1]
        scores = cmd[2]
        for s in scores.split("|"):
            [name, score] = s.split(":")
            self.arena.players[name].score = int(score)

        goals_coord = coord.split("|")
        goalx, goaly = parse_coord(goals_coord[0])
        if (len(goals_coord) == 2):
            nextgoalx, nextgoaly = parse_coord(goals_coord[1])
            self.arena.next_goal = Goal(nextgoalx, nextgoaly, True)
        else:
            self.arena.next_goal = None
        self.arena.goal = Goal(goalx, goaly)
コード例 #13
0
 def createWalls(self):
     for y in range(self.canv.getHeight()):
         for x in range(self.canv.getWidth()):
             if(x==0 or  y==0 or y == self.canv.getHeight() -1):
                 self.walls.append(Wall(x,y))
             if( x == self.canv.getWidth()-1):
                 self.goals.append(Goal(x,y))
コード例 #14
0
    def creategoal(self, goalimagelist, worth, name):
        """
        Create a new goal object (recursive until no longer blocked)

        :param goalimagelist: (Dict) Dict of images to create the goal (should contain one, keyed on 'image'))
        :param worth: (int) Points value of the goal
        :param name: (string) Name of the goal
        :return: (Goal) Goal object
        """
        goal = Goal(goalimagelist, worth, name, self.screen.get_width(), self.screen.get_height())
        if not pygame.sprite.spritecollide(goal, self.blocklist, False, pygame.sprite.collide_circle):
            self.blocklist.add(goal)
        else:
            goal.kill()
            goal = self.creategoal(goalimagelist, worth, name)
        return goal
コード例 #15
0
ファイル: environment.py プロジェクト: thanusiv/A.I-Dots
    def __init__(self, environment_width, environment_height):
        self.white = (255,255,255)
        self.environment_width = environment_width
        self.environment_height = environment_height

        pygame.init()
        self.game_display = pygame.display.set_mode((environment_width, environment_height))
        self.clear_screen()

        self.goal_x = environment_width // 2
        self.goal_y = 30
        self.goal_radius = 5
        self.goal = Goal(self.goal_x, self.goal_y, self.goal_radius, self.game_display)

        self.population = Population(environment_width, environment_height, self.goal_x, self.goal_y, self.goal_radius, self.game_display)
        self.obstacle = Obstacle(environment_width, environment_height, self.game_display)
コード例 #16
0
ファイル: die.py プロジェクト: evanjtravis/dice
 def __check_goal(self):
     """Dice's goal should be checked by Goal class verification.
     """
     if isinstance(self.__goal, Goal):
         self.__goal.check_vars()
     elif self.__goal != None:
         self.__goal = Goal(self.__goal)
コード例 #17
0
ファイル: main.py プロジェクト: sm00k3y/dots-genetic
def main_loop():

    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    font = pygame.font.SysFont("dejavusansmono", 17)
    clock = pygame.time.Clock()
    game_loop = True

    generation = font.render("Population: 1", True, (0, 0, 0))
    gen_rect = generation.get_rect()
    gen_rect.center = (WIDTH - 90, 15)

    dots = Population(400, BRAIN_SIZE)
    goal = Goal(int(WIDTH / 2), 20)
    obstacles = Obstacle_Generator(level=2)

    while game_loop:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_loop = False

        if dots.all_dead():
            dots.calculate_fitness(goal)
            dots.natural_selection(BRAIN_SIZE, MUTATION_RATE)
            generation = font.render("Population: {}".format(dots.generation),
                                     True, (0, 0, 0))
        else:
            dots.update(WIDTH, HEIGHT, goal, obstacles)
            draw_window(screen, dots, goal, obstacles, generation, gen_rect)

        clock.tick(FPS)
コード例 #18
0
ファイル: die.py プロジェクト: evanjtravis/dice
 def set_goal(self, goal):
     """Sets the goal of the dice to be used as a default for rolls.
     """
     if isinstance(goal, Goal):
         self.__goal = goal
     else:
         self.__goal = Goal(value=goal)
コード例 #19
0
ファイル: game.py プロジェクト: alr888rav/pyball
 def __init__(self):
     self.bg = pygame.image.load("images/bg.jpg")
     self.bg = pygame.transform.scale(self.bg,
                                      (SCREEN_WIDTH, SCREEN_HEIGHT))
     self.bgrect = self.bg.get_rect()
     self.ball = Ball()
     self.human = Human()
     self.robot = Robot()
     self.goal = Goal(0)
     self.win = Win(0)
     self.lose = Lose(0)
     self.menu = Menu()
     self.mouse = (0, 0)
     self.sounds = Sounds()
     self.sounds.music()
     self.status = Game.MENU
     self.reset()
コード例 #20
0
 def __check_goal(self):
     """A goal should either be a Goal object or an integer that is then
     used to create a Goal object.
     """
     if isinstance(self.goal, Goal):
         return
     else:
         self.goal = Goal(self.goal)
コード例 #21
0
ファイル: population.py プロジェクト: nik312123/Genetic
 def __init__(self, size, x, y):
     self.setup_done = False
     self.start = None
     self.turtles = []
     self.fitness_sum = 0
     self.gen = 1
     self.best_turtle = None
     self.original_x = x
     self.original_y = y
     self.min_step = size
     self.size = size
     self.is_changing = False
     for i in range(size):
         self.turtles.append(EvolvingTurtle(x, y, self))
     self.goal = Goal(0, 275)
     self.setup_done = True
     print(f"Generation {self.gen}")
コード例 #22
0
    def buildGoal(self, e, pos, relation, restriction):
        ''' create a goal based on a pair of objects or lists of objects
            by adding relations to a new goal'''
        ori,dst,q = e

        if isinstance(ori, basestring): ori = [ori]
        if isinstance(dst, basestring): dst = [dst]

        g = Goal()

        if restriction and (restriction[0] not in ori + dst):
            g.addRestriction(restriction[0],restriction[1])
        
        if q == 'any' and "".join(sorted(ori)) == "".join(sorted(dst)):
            dst.pop()
        
        for o in ori:
            if q == 'any':
                n_dst = copy.deepcopy(dst)
                nn_dst = copy.deepcopy(n_dst)
                for d in n_dst:
                    if d == o or not Physics().checkPhysicalLaws(o, d, relation, False):
                        nn_dst.remove(d)
                if len(nn_dst) > 0:
                    g.addRelation(o,nn_dst,pos)
            else:
                for d in dst:
                    if d == o or not Physics().checkPhysicalLaws(o, d, relation, False):
                        return None
                    g.addRelation(o,d,pos)

        if not len(g.relations):
            return None
       
        return g
コード例 #23
0
 def setUp(self) :
     board, = Board.load_from_json(GRID_FILENAME)
     robots = Robot_group()
     r1 = Robot(robots, RColors.RED, (5,0))
     r2 = Robot(robots, RColors.BLUE, (11,1))
     r3 = Robot(robots, RColors.GREEN, (2,15))
     r4 = Robot(robots, RColors.YELLOW, (10,13))   
     goal = Goal(RColors.RED, (0,7)) 
     self.game = Game(board,robots,goal)
コード例 #24
0
ファイル: user.py プロジェクト: julianpistorius/back-end-api
    def add_goal(self, goal_properties):
        """
        Add goal to user
        :param goal_id: string uuid
        :return: List of user goals
        """
        #TODO exception handling
        goal = Goal()
        goal.set_goal_properties(goal_properties=goal_properties)
        goal.create_goal()
        # create relationship between user and interest node
        user_goal_relationship = Relationship(self.user_node,
                                              GraphRelationship.HAS_GOAL,
                                              goal.goal_node)

        self._graph_db.create_unique(user_goal_relationship)
        #TODO set properties on the relationship -- may use a unique id as the key
        return self.user_goals
コード例 #25
0
ファイル: user.py プロジェクト: julianpistorius/back-end-api
    def user_goals(self):
        """ get user interests
        :return: list of interests
        """
        #TODO do not need a list of interests -- HATEOAS -- MMD 3/8/2015
        user_goals = self._graph_db.match(start_node=self.user_node, rel_type=GraphRelationship.HAS_GOAL,
                                         end_node=None)
        goals_list = []
        goal_interests_list = []
        for rel in user_goals:
            goal_properties = dict(rel.end_node.properties)
            goal = Goal()
            goal.id = goal_properties['id']
            interests = goal.goal_interests
            interests_list = []
            for interest in interests:
                interests_list.append(interest['name'])
            goal_properties['interests'] = interests_list
            goals_list.append(goal_properties)

        return goals_list
コード例 #26
0
def initialize_goals():
    np.random.seed(SEED_GOAL)
    goals = []
    for i in range(INITIAL_GOALS):
        pos_x = np.random.randint(0, GRID_HEIGHT)
        pos_y = np.random.randint(0, GRID_WIDTH)
        goal = Goal(pos_x,
                    pos_y,
                    id=i,
                    capacity=np.random.randint(1, MAX_GOAL_CAPACITY))
        goals.append(goal)
    return goals
コード例 #27
0
ファイル: __init__.py プロジェクト: pierg/crome
    def composition(nodes: Set[Node], name: str = None, description: str = None) -> Node:

        try:
            new_goal = Goal.composition(nodes, name, description)
        except GoalException as e:
            raise CGGOperationFail(nodes=nodes, operation=CGGFailOperations.algebra_op, goal_ex=e)

        new_node = Node(goal=new_goal)

        new_node.add_children(link=Link.COMPOSITION, nodes=set(nodes))

        return new_node
コード例 #28
0
ファイル: __init__.py プロジェクト: pierg/crome
    def disjunction(nodes: Set[Node], name: str = None, description: str = None) -> Node:

        try:
            new_goal = Goal.disjunction(nodes, name, description)
        except GoalException as e:
            raise CGGOperationFail(nodes=nodes, operation=CGGFailOperations.algebra_op, goal_ex=e)

        new_node = Node(goal=new_goal)

        new_node.add_children(link=Link.DISJUNCTION, nodes=nodes)

        return new_node
コード例 #29
0
ファイル: environment.py プロジェクト: thanusiv/A.I-Dots
class Environment():

    def __init__(self, environment_width, environment_height):
        self.white = (255,255,255)
        self.environment_width = environment_width
        self.environment_height = environment_height

        pygame.init()
        self.game_display = pygame.display.set_mode((environment_width, environment_height))
        self.clear_screen()

        self.goal_x = environment_width // 2
        self.goal_y = 30
        self.goal_radius = 5
        self.goal = Goal(self.goal_x, self.goal_y, self.goal_radius, self.game_display)

        self.population = Population(environment_width, environment_height, self.goal_x, self.goal_y, self.goal_radius, self.game_display)
        self.obstacle = Obstacle(environment_width, environment_height, self.game_display)
       
    def update(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        if self.population.are_all_dots_dead():
            fitness_sum = self.population.calculate_fitness_sum()
            self.population.natural_selection(fitness_sum)
            self.population.mutate_offsprings()
        else:
            self.clear_screen()
            self.obstacle.show()
            self.goal.show()
            self.population.update()
            pygame.time.wait(20)
            pygame.display.update()

    def clear_screen(self):
        self.game_display.fill(self.white)
コード例 #30
0
def _random_valid_moves(block: Block, goal: Goal) -> \
        Tuple[Optional[Tuple[str, Optional[int], Block]], int]:
    """
     This is a helper functions for the generate_move methods for both Random
     Player and Smart Player that takes the player's goal a blocks then returns
     a random valid move that can be preformed on the block
    """
    temp_board = block.create_copy()

    random_level = random.randint(0, block.max_depth)
    random_position_x = random.randint(0, block.position[0] + block.size)
    random_position_y = random.randint(0, block.position[1] + block.size)

    new_block = _get_block(temp_board, (random_position_x, random_position_y),\
                           random_level)
    if new_block:
        new_block = new_block.create_copy()
    else:
        return _random_valid_moves(block, goal)

    random_move = random.randint(1, 7)

    if random_move == 1:
        if new_block.rotate(1):
            score = goal.score(temp_board)
            return _create_move(ROTATE_CLOCKWISE, new_block), score
    if random_move == 2:
        if new_block.rotate(3):
            score = goal.score(temp_board)
            return _create_move(ROTATE_COUNTER_CLOCKWISE, new_block), score
    if random_move == 3:
        if new_block.swap(0):
            score = goal.score(temp_board)
            return _create_move(SWAP_HORIZONTAL, new_block), score
    if random_move == 4:
        if new_block.swap(1):
            score = goal.score(temp_board)
            return _create_move(SWAP_VERTICAL, new_block), score
    if random_move == 5:
        if new_block.smash():
            score = goal.score(temp_board)
            return _create_move(SMASH, new_block), score
    if random_move == 6:
        if new_block.combine():
            score = goal.score(temp_board)
            return _create_move(COMBINE, new_block), score
    if random_move == 7:
        random_color = goal.colour
        if new_block.paint(random_color):
            score = goal.score(temp_board)
            return _create_move(PAINT, new_block), score

    return _random_valid_moves(block, goal)
コード例 #31
0
    def generate_goal(self, reward):
        """
        Desc: Generate goal on the gridworld. This is done by choosing a
            random spot.

        Input(s):
            reward: reward designated for this goal
        Output(s):
            none
        """
        initial_pos = self.choose_spot()
        logging.info("Goal pos: (%d, %d)" % (initial_pos[0], initial_pos[1]))
        self.spots[initial_pos[1], initial_pos[0], 2] = 2
        return Goal(initial_pos, reward)
コード例 #32
0
    def __init__(self, width: int, height: int):
        """Initializes a new world object.

        Args:
            width (float): The width of the world in meters.
            height (float): The height of the world in meters.

        """
        self.width: int = width
        self.height: int = height
        self.cars: List[Car] = []
        self.goal: Goal = Goal(0.0, 0.0, False)
        self.collision_distribution: List[int] = []
        self.flocking_performance_distribution: List[float] = []
コード例 #33
0
ファイル: singlegame.py プロジェクト: shengxu1/hockey_game
    def __init__(self):
        super().__init__()
        self.time = settings.fps_duration

        self.num_font = pygame.font.SysFont("arialblack", settings.font_size)

        self.field_img = pygame.transform.scale(
            pygame.image.load("images/field.png").convert_alpha(),
            settings.field_size)
        self.left_goal_img = pygame.transform.scale(
            pygame.image.load("images/left-goal.png").convert_alpha(),
            settings.goal_size)
        self.right_goal_img = pygame.transform.scale(
            pygame.image.load("images/right-goal.png").convert_alpha(),
            settings.goal_size)

        player1 = Player("red", settings.player1_keyconfig,
                         settings.player1_start_pos, Side.RIGHT)
        player2 = Player("blue", settings.player2_keyconfig,
                         settings.player2_start_pos, Side.LEFT)
        self.players = [player1, player2]

        goalie1 = Goalie(settings.goalie1_startx, settings.goalie_starty,
                         Side.RIGHT, "red", settings.goalie1_keyconfig)
        goalie2 = Goalie(settings.goalie2_startx, settings.goalie_starty,
                         Side.LEFT, "blue", settings.goalie2_keyconfig)
        self.goalies = [goalie1, goalie2]

        self.ball = Ball(settings.ball_start_pos)
        self.left_team = Team(Side.LEFT)  # left team attacks right goal
        self.right_team = Team(Side.RIGHT)  # right team attacks left goal
        self.goals = [
            Goal(0, self.right_team),
            Goal(settings.rightwall, self.left_team)
        ]

        self.kickoff()
コード例 #34
0
ファイル: _printing.py プロジェクト: pierg/crome
def __str__(self, level=0):
    """Print current Goal"""
    ret = Goal.pretty_print_goal(self, level)

    if self.children is not None:

        for link, goals in self.children.items():

            ret += "\t" * level + "|  " + link.name + "\n"
            level += 1
            for child in goals:
                try:
                    ret += child.__str__(level + 1)
                except:
                    print("ERROR IN PRINT")
    return ret
コード例 #35
0
    def generate_maze(self):
        maze = [[0 for x in range(self.length)] for x in range(self.length)]

        for row in range(self.length):
            for column in range(self.length):
                maze[row][column] = Wall(row, column)

        maze[0][0] = Clear(0, 0)
        maze[0][1] = Clear(0, 1)
        maze[0][2] = Clear(0, 2)
        maze[1][2] = Clear(1, 2)
        maze[2][2] = Clear(2, 2)
        maze[3][2] = Clear(3, 2)
        maze[3][3] = Goal(3, 3)

        return maze
コード例 #36
0
 def __init__(self):
     self.algorithm = ''
     self.heuristic = ''
     self.file = ''
     self.check_arguments(sys.argv[1:])
     self.start = []
     self.size = 0
     self.puzzle_parsing(self.file)
     self.goal = Goal(self.size)
     self.h = self.choose_heuristic_function()
     self.cost_function = self.create_cost_function()
     self.create_cost_function()
     goal_solvability = self.is_solvable(self.goal.puzzle)
     start_solvability = self.is_solvable(self.start)
     if goal_solvability is False:
         start_solvability = not start_solvability
     if start_solvability is False:
         raise Exception("Error: Puzzle is unsolvable")
コード例 #37
0
ファイル: bar.py プロジェクト: bitpit/Gravity
 def __init__(self,x,y,friends,place,other,goal,image=str('taskbar.png')):
     Bar.__init__(self,x,y,friends,place,image)
     self.lives = Lives(self.rect.x+353,self.rect.y+71,self.group,self.screen,str('5lives.png'))
     self.goRect = pygame.Rect(717,658,118,75)
     self.barGoal = Goal(self.rect.x+605,self.rect.y+70,self.group)
     self.barGoal.resize(40,40)
     self.score = Score(250,665,friends,self.screen,2000,26,(0,0,0))
     self.arrow = Arrow(872,665,friends,self.screen)
     self.menuWidget = MenuWidget(self.rect.x+694,723,self.group,self.screen,self.arrow)
     self.itemsTab = ItemsTab(self.rect.x-912,self.rect.y+15,self.group,self.screen,-917,-954,-3)
     self.game = other
     self.grabbed = None
     self.item_one_reset()
     self.items_one_limit = 1
     self.items_one_placed = 0
     self.items_two_limit = 0
     self.items_two_placed = 0
     self.items_three_placed = 0
     self.items_three_limit = 0
     self.goal = goal
コード例 #38
0
    def loadLevel(self):
        """
      Loads the level specified by the level argument.
      """

        #Try open the level, if it doesn't exist go to the win screen
        try:
            f = open("data/levels/level_%03d" % self.level)
        except IOError:
            self.gameEngine.scene = GameOver(self.gameEngine, True)
            return

        del self.gameObjects[:]

        x = y = 0
        while 1:
            row = f.readline()
            if not row:
                break
            for col in row:

                obj = None  #object to be added at the end of each iteration

                if col == "W":
                    obj = Wall(self, x, y)
                if col == "E":
                    obj = Goal(self, x, y)
                if col == "L":
                    obj = FreeLife(self, x, y)
                if col == "B":
                    obj = Player(self, x, y)
                    self.spawn = (x, y)

                if obj is not None:
                    self.gameObjects.append(obj)

                x += 16

            y += 16
            x = 0
コード例 #39
0
    def create_or_update(cls, connection, **values):
        """Create or Update an activity row in 'activity_goal' table

        :param connection: DB connection object
        :param values: activity_goal payload
            {
                'user_id': <user-id>,
                'goal_id': <goal-id>,
            }
        :return: boolean output
        """
        session = connection.SESSION
        create_or_update = True
        try:
            activity_obj = session.query(schema.ActivityGoal).filter_by(**values).one()
            goal_count = Goal.get(connection, values.get(GOAL_ID_KEY)).get(COUNT_KEY)

            if goal_count < activity_obj.frequency + 1:
                raise Exception("Reached the required goal count")

            setattr(activity_obj, FREQUENCY_KEY, activity_obj.frequency + 1)
            completed_on = literal_eval(activity_obj.completed_on)
            completed_on[str(activity_obj.frequency)] = get_utc_time().strftime(TIME_FORMAT)
            setattr(activity_obj, COMPLETED_ON_KEY, completed_on)
            setattr(activity_obj, LAST_UPDATED_AT_KEY, get_utc_time())

            if goal_count == activity_obj.frequency:
                setattr(activity_obj, COMPLETED_KEY, True)
            session.commit()
        except NoResultFound as _:
            values[COMPLETED_ON_KEY] = dict([(str(1), get_utc_time().strftime(TIME_FORMAT))])
            session.add(schema.ActivityGoal(**values))
            session.commit()
        except Exception as e:
            print "Exception occurred during querying (INSERT/UPDATE) the activity_goal table: %s" % e
            session.rollback()
            create_or_update = False
        finally:
            session.close()
        return create_or_update
コード例 #40
0
    def get_by_goal_name(cls, connection, goal_name, week, completed=None):
        """Get all activities with goal_name from 'activity_goal' table on <week> of all users

        :param connection: DB connection object
        :param goal_name: goal name
        :param week: week number
        :param completed: status of the activity (True/False/None)
                True - returns all the completed goal_name goals of all users
                False - return all the in-progress goal_name goals of all user
                None - return all the goals_name goals of all users
        :return: list of activities of all users with goal_name
            [{
                'user_id': <user-id>,
                'goal_id': <goal-id>,
                'frequency': <number-of-times-goal-performed> (3),
                'last_updated': <datetime>,
                'completed_on': {1: <datetime>, 2: <datetime>, 3: <datetime>},
                'completed': True (or) False
            }]
        """
        goal_id = Goal.get_goal_id(connection, goal_name, week)
        return cls.get_by_goal_id(connection, goal_id, completed=completed)
コード例 #41
0
ファイル: bar.py プロジェクト: bitpit/Gravity
class ToolBar(Bar):
    def __init__(self,x,y,friends,place,other,goal,image=str('taskbar.png')):
        Bar.__init__(self,x,y,friends,place,image)
        self.lives = Lives(self.rect.x+353,self.rect.y+71,self.group,self.screen,str('5lives.png'))
        self.goRect = pygame.Rect(717,658,118,75)
        self.barGoal = Goal(self.rect.x+605,self.rect.y+70,self.group)
        self.barGoal.resize(40,40)
        self.score = Score(250,665,friends,self.screen,2000,26,(0,0,0))
        self.arrow = Arrow(872,665,friends,self.screen)
        self.menuWidget = MenuWidget(self.rect.x+694,723,self.group,self.screen,self.arrow)
        self.itemsTab = ItemsTab(self.rect.x-912,self.rect.y+15,self.group,self.screen,-917,-954,-3)
        self.game = other
        self.grabbed = None
        self.item_one_reset()
        self.items_one_limit = 1
        self.items_one_placed = 0
        self.items_two_limit = 0
        self.items_two_placed = 0
        self.items_three_placed = 0
        self.items_three_limit = 0
        self.goal = goal
                
    def lives_over(self):
        self.lives.no_lives()

    def lives_update(self):
        self.lives.update()

    def reset_lives(self):
        #print "resetting lives"
        self.lives.back_to_three(False)

    def reset_lives_over(self):
        self.lives.back_to_three(True)

    def update(self,pos=(0,0)):
        if self.grabbed != None:
            self.grabbed.update(pos,self)

    def clear_grabbed(self):
        if self.grabbed != None:
            self.grabbed.dropped()
            self.grabbed = None

    def collision_test(self,pos,player,button):
        if self.goRect.collidepoint(pos) and not self.itemsTab.open and not self.menuWidget.open and button == 1:
            player.makeANew = True
        elif self.goRect.collidepoint(pos) and not self.itemsTab.open and not self.menuWidget.open and button == 3:
            return True
        elif self.itemsTab.items_rect.collidepoint(pos) and not self.menuWidget.open:
            self.grabbed = self.itemsTab
        elif self.menuWidget.widget_rect.collidepoint(pos) and not self.itemsTab.open:
            self.grabbed = self.menuWidget
        elif self.menuWidget.quit_rect.collidepoint(pos):
            self.game.quit()
        elif self.items_one.collidepoint(pos) and self.itemsTab.open and self.items_one_placed < self.items_one_limit:
            x,y = pos
            x -= 30
            y -= 30
            self.grabbed = UserPlanet(x,y,60,60,25,self.game.userPlacedObjects,self.group,self.game.obstacles,self,player,1,self.goal,str('rockplanet.png'))
            self.items_one_placed += 1
            if self.items_one_placed >= self.items_one_limit:
                self.items_one.x = -30
                self.itemsTab.rock_item.dark()
        elif self.itemsTab.earth_item.rect.collidepoint(pos) and self.itemsTab.open and self.itemsTab.earth_item and self.items_two_placed < self.items_two_limit:
            #print "touch earth"
            x,y = pos
            x -= 30
            y -= 30
            self.grabbed = UserPlanet(x,y,65,65,30,self.game.userPlacedObjects,self.group,self.game.obstacles,self,player,2,self.goal,str('ringed.png'))
            self.items_two_placed += 1
            #print self.items_two_placed
            if self.items_two_placed >= self.items_two_limit:
                self.itemsTab.earth_item.dark()
        elif self.itemsTab.venus_item.rect.collidepoint(pos) and self.itemsTab.open and self.itemsTab.venus_item and self.items_three_placed < self.items_three_limit:
            #print "touch venus"
            x,y = pos
            x -= 30
            y -= 30
            self.grabbed = UserPlanet(x,y,68,68,40,self.game.userPlacedObjects,self.group,self.game.obstacles,self,player,3,self.goal,str('venus.png'))
            self.items_three_placed += 1
            if self.items_three_placed >= self.items_three_limit:
                self.itemsTab.venus_item.dark()
        elif self.menuWidget.instructions_rect.collidepoint(pos) and self.menuWidget.open:
            self.game.inStructionees()
        elif self.menuWidget.save_rect.collidepoint(pos) and self.menuWidget.open:
            self.game.saveFile()
        return False

    def item_one_reset(self):
        self.items_one_placed = 0
        self.items_one = pygame.Rect(119,667,55,45)
        self.itemsTab.rock_item.light()

    def item_two_reset(self):
        self.items_two_placed = 0
        self.itemsTab.earth_item.light()

    def item_three_reset(self):
        self.items_three_placed = 0
        self.itemsTab.venus_item.light()
        
    def next_level(self,level,reset_lives_bool):
        #print level-2
        self.barGoal.change_image(self.images[level-2])
        if level != 3:
            self.barGoal.resize(40,40)
        else:
            self.barGoal.resize(57,40)
        self.item_one_reset()
        if reset_lives_bool:
            self.reset_lives()
        self.nextPosition += 1
        if level == 2:
            self.item_two_reset()
            self.items_two_limit = 1
        elif level == 3:
            self.item_three_reset()
            self.items_two_limit = 1
            self.items_three_limit = 1
            self.item_two_reset()
            self.item_one_reset()
        elif level == 4:
            self.item_three_reset()
            self.items_two_limit = 1
            self.items_three_limit = 1
            self.item_two_reset()
            self.item_one_reset()
コード例 #42
0
ファイル: board.py プロジェクト: ragtz/6.804-mazegame
 def addGoal(self, x, y):
     if self._valid(x, y):
         self.goal = Goal(x, y, self.cell_size)
コード例 #43
0
 def __init__(self, owner):
     Goal.__init__(self, owner)
     self.subgoals = []
コード例 #44
0
 def __init__(self, owner):
     Goal.__init__(self, owner)
コード例 #45
0
 def __init__(self, owner):
     Goal.__init__(self, owner)
     self.dc = [9, 15, 39, 45]
コード例 #46
0
 def __init__(self, owner):
     Goal.__init__(self, owner)
     self.dc = [8, 13, 27, 32]
コード例 #47
0
ファイル: die.py プロジェクト: evanjtravis/dice
class Die(object):
    """This class specifies dice used in games.
    """
    def __init__(
            self,
            max_roll,
            name=DEF_NAME,
            offset=DEF_OFFSET,
            mod=DEF_MOD):
        """Dice have a max roll, an offset, and a name.
        """
        self.max_roll = max_roll
        self.offset = offset
        self.name = name
        self.mod = mod
        self.__goal = None
        self.__func = None
        self.__rolls = []

        self.check_vars()

        DICE.append(self)

    def __str__(self):
        """The print-out of a Dice object.
        """
        self.check_vars()
        message = '%s: ' % self.name
        message += 'd%d' % self.max_roll
        if self.offset > 0:
            message += '+'
        if self.offset != 0:
            message += '%d, ' % self.offset
        if self.mod != 0:
            message += 'mod: %d, ' % self.mod
        return message

    ########################################################################
    # Public Methods
    ########################################################################
    def roll(self, count=1, goal=None):
        """Appends a roll to the dice's rolls list.
        """
        self.check_vars()
        result = None
        if goal == None and self.__goal != None:
            goal = self.__goal

        for _ in range(count):
            value = randint(
                self.offset + 1,
                self.max_roll + self.offset + 1
            )
            if self.__func != None:
                result = self.__func(value)
            self.__rolls.insert(
                0,
                Roll(self, value, goal=goal, result=result)
            )

    def rolls(self):
        """Returns the list of rolls for the dice.
        """
        return self.__rolls

    def set_goal(self, goal):
        """Sets the goal of the dice to be used as a default for rolls.
        """
        if isinstance(goal, Goal):
            self.__goal = goal
        else:
            self.__goal = Goal(value=goal)

    def set_function(self, func, clear_rolls=True):
        """This method assigns a function to a dice, which is executed
        with each roll, and recieves a the Roll object as an argument.

        Optional argument clear_rolls sets __rolls to an empty list if
        True.
        """
        if isinstance(func, types.FunctionType):
            if func == self.__func:
                return
            self.__func = func
            if clear_rolls == True:
                self.__rolls = []
            self.__check_func()
        else:
            self.__func = None

    def possible_rolls(self):
        """Returns a list of possible roll values, not including Mod.
        """
        possible_rolls = []
        for num in range(self.offset + 1, self.offset + self.max_roll + 1):
            possible_rolls.append(num)
        return possible_rolls

    def check_vars(self):
        """Maintain the validity of Dice variables.
        """
        self.__check_max_roll()
        self.__check_offset()
        self.__check_name()
        self.__check_modifier()
        self.__check_rolls()
        self.__check_goal()
        self.__check_func()

    ########################################################################
    # Private Methods
    ########################################################################


    def __check_max_roll(self):
        """Make sure that any changes made to max_roll are valid.
        """
        try:
            self.max_roll = int(self.max_roll)
        except ValueError:
            self.max_roll = DEF_MAX
        if self.max_roll <= CRITICAL_FAIL:
            self.max_roll = DEF_MAX

    def __check_offset(self):
        """Make sure that when and if the offset is changed, that it
        is still positive and a number.
        """
        try:
            self.offset = int(self.offset)
        except ValueError:
            self.offset = DEF_OFFSET
        if self.offset <= -1:
            self.offset = DEF_OFFSET

    def __check_name(self):
        """If the name is None, then the name displayed on print should be
        NA.
        """
        if self.name == 'None':
            return
        if self.name == None:
            self.name = DEF_NAME
        try:
            self.name = str(self.name)
        except ValueError:
            self.name = DEF_NAME

    def __check_modifier(self):
        """Make sure that when and if the moddifier is changed, that it is
        still an integer.
        """
        try:
            self.mod = int(self.mod)
        except ValueError:
            self.mod = DEF_MOD

    def __check_rolls(self):
        """Dice's rolls list length shouldn't exceed DEF_ROLLS_LENGTH
        """
        self.__rolls = self.__rolls[:DEF_ROLLS_LENGTH]

    def __check_goal(self):
        """Dice's goal should be checked by Goal class verification.
        """
        if isinstance(self.__goal, Goal):
            self.__goal.check_vars()
        elif self.__goal != None:
            self.__goal = Goal(self.__goal)

    def __check_func(self):
        """Dice's function should be a FunctionType and be able to take an
        integer argument.
        """
        message = "Function %s() does not accept integer arguments."
        if isinstance(self.__func, types.FunctionType):
            try:
                temp = self.__func(1)
            except ValueError:
                del temp
                raise InvalidDieFunction(message % self.__func)
        else:
            self.__func = None
コード例 #48
0
ファイル: board.py プロジェクト: ragtz/6.804-mazegame
class Board:
    def __init__(self, width, height, cell_size):
        self.w = width
        self.h = height
        self.cell_size = cell_size
        self.start = None
        self.goal = None
        self.player = None
        self.obstacles = []
        self.flags = []
        self.captured_flags = []
    
    def _valid(self, x, y):
        return x >= 0 and x < self.w and y >= 0 and y < self.h
        
    def _collide(self, x, y):
        return Obj(x,y) in self.obstacles
        
    def _checkFlags(self):
        if self.player in self.flags:
            self.flags.remove(self.player)
            self.captured_flags.append(Flag(self.player.x, self.player.y, self.cell_size/2))
    
    def _checkGoal(self):
        if self.player == self.goal:
            self.player.update(self.start[0], self.start[1])
            if self.flags == []:
                self.flags = list(self.captured_flags)
            else:
                self.flags.extend(self.captured_flags)
            self.captured_flags = []
    
    def addStart(self, x, y):
        if self._valid(x, y):
            self.start = (x, y)
    
    def addGoal(self, x, y):
        if self._valid(x, y):
            self.goal = Goal(x, y, self.cell_size)
        
    def addPlayer(self, x, y):
        if self._valid(x, y):
            self.player = Player(x, y, self.cell_size/2)
    
    def addObstacle(self, x, y):
        if self._valid(x, y):
            self.obstacles.append(Obstacle(x, y, self.cell_size))
    
    def addObstacles(self, obstacles):
        for (x,y) in obstacles:
            self.addObstacle(x, y)
    
    def addFlag(self, x, y):
        if self._valid(x, y):
            self.flags.append(Flag(x, y, self.cell_size/2))
    
    def addFlags(self, flags):
        for (x,y) in flags:
            self.addFlag(x, y)
            
    def moveUp(self):
        if self._valid(self.player.x,self.player.y-1) and not self._collide(self.player.x,self.player.y-1):
            self.player.update(self.player.x,self.player.y-1)
            
        self._checkFlags()
        self._checkGoal()
    
    def moveDown(self):
        if self._valid(self.player.x,self.player.y+1) and not self._collide(self.player.x,self.player.y+1):
            self.player.update(self.player.x,self.player.y+1)
            
        self._checkFlags()
        self._checkGoal()
    
    def moveRight(self):
        if self._valid(self.player.x+1,self.player.y) and not self._collide(self.player.x+1,self.player.y):
            self.player.update(self.player.x+1,self.player.y)
            
        self._checkFlags()
        self._checkGoal()
                
    def moveLeft(self):
        if self._valid(self.player.x-1,self.player.y) and not self._collide(self.player.x-1,self.player.y):
            self.player.update(self.player.x-1,self.player.y)
        
        self._checkFlags()
        self._checkGoal()
   
    def display(self, screen):
        self.player.display(screen)
        self.goal.display(screen)
        
        for flag in self.flags:
            flag.display(screen)
            
        for obstacle in self.obstacles:
            obstacle.display(screen)
コード例 #49
0
 def __init__(self, owner):
     Goal.__init__(self, owner)
     self.child_conn = owner.controller.child_conn
     self._term_event = multiprocessing.Event()
     self._process = None