Пример #1
0
def gen_base():
    global base_list

    new_base_1 = Base.Base()
    new_base_1.x = 0

    new_base_2 = Base.Base()

    base_list = [new_base_1, new_base_2]
Пример #2
0
 def test_base_init(self):
     b1 = Base()
     self.assertEqual(b1.id, 1)
     b2 = Base()
     self.assertEqual(b2.id, 2)
     b3 = Base(12)
     self.assertEqual(b3.id, 12)
     b4 = Base()
     self.assertEqual(b4.id, 3)
    def test_inputs(self):
        """checks for valid input """
        Base._Base__nb_objects = 0

        b_zero = Base()
        self.assertEqual(b_zero.id, 1)

        b_int = Base(17)
        self.assertEqual(b_int.id, 17)

        b_negint = Base(-29)
        self.assertEqual(b_negint.id, -29)
    def test_incrementation(self):
        """ obj id increments """
        Base._Base__nb_objects = 0

        b1 = Base()
        self.assertEqual(b1.id, 1)

        b2 = Base()
        self.assertEqual(b2.id, 2)

        b3 = Base()
        self.assertEqual(b3.id, 3)
Пример #5
0
 def test_base(self):
     temp = Base.Base()
     self.assertEqual(type(temp), Base.Base, 'Base doesn`t work correctly')
     self.assertTrue(temp.hit_points == 10, 'Base doesn`t work correctly')
     self.assertTrue(temp.place == [0, 0], 'Base doesn`t work correctly')
     self.assertFalse(temp.destroyed, 'Base doesn`t work correctly')
     self.assertTrue(temp.type == 'Base', 'Base doesn`t work correctly')
Пример #6
0
 def solve(self):
     startTime = time()
     while (len(self.frontier) > 0):
         closest = min(self.frontier)
         currentState = self.frontier[closest].pop(0)
         if (len(self.frontier[closest]) == 0):
             del (self.frontier[closest])
         currentStateString = currentState.__str__()
         currentState = self.explored[currentStateString]
         moves = currentState.getValidMoves()
         for move in moves:
             newArray = currentState.move(move)
             newCost = currentState.pathCost + 1
             newMove = move
             newState = Base(currentState, newArray, newMove, newCost)
             newStateString = newArray.__str__()
             if (newStateString not in self.explored):
                 self.explored[newStateString] = newState
                 if (newCost > self.maxDepth):
                     self.maxDepth = newCost
                 if (newArray == self.target):
                     solvingTime = time() - startTime
                     solved = round(solvingTime, 3)
                     path = newState.getPath()
                     explored = (len(self.explored) + 1)
                     frontier = len(self.explored) - len(self.frontier)
                     return path, explored, frontier, self.maxDepth, solved
                 if (self.strategy == 'manh'):
                     distance = self.Manhattan(newArray)
                 elif (self.strategy == 'hamm'):
                     distance = self.Hamming(newArray)
                 if (distance not in self.frontier):
                     self.frontier.setdefault(distance, []).append(newArray)
                 else:
                     self.frontier[distance].append(newArray)
Пример #7
0
 def solve(self):
     startTime = time()
     while (self.frontier.qsize() > 0):
         currentState = self.frontier.get()
         currentStateString = currentState.__str__()
         currentState = self.explored[currentStateString]
         moves = currentState.getOrderedMoves(self.strategy)
         for move in moves:
             newArray = currentState.move(move)
             newCost = currentState.pathCost + 1
             newMove = move
             newState = Base(currentState, newArray, newMove, newCost)
             newStateString = newArray.__str__()
             if (newStateString not in self.explored):
                 self.frontier.put(newArray)
                 self.explored[newStateString] = newState
                 if (newCost > self.maxDepth):
                     self.maxDepth = newCost
                 if (newArray == self.target):
                     solvingTime = time() - startTime
                     solved = round(solvingTime, 3)
                     path = newState.getPath()
                     explored = (len(self.explored) + 1)
                     frontier = len(self.explored) - self.frontier._qsize()
                     return path, explored, frontier, self.maxDepth, solved
     solvingTime = time() - startTime
     solved = round(solvingTime, 3)
     explored = (len(self.explored) + 1)
     frontier = len(self.explored) - len(self.frontier)
     return -1, explored, frontier, self.maxDepth + 1, solved
Пример #8
0
    def __init__(self, field_size, width, height):
        self.base = Base.Base()

        self.name = ''
        self.fraction_name = ''

        self.units = Units()

        self.unit_list = []
        self.name_units = []
        self.button_list = []
        self.name_units_text = []
        self.highlighted_cells_list = []
        self.player_list = []
        self.units_behave_list = []
        self.field_info = [[None for i in range(field_size)]
                           for j in range(field_size)]

        self.field_size = field_size
        self.next_turn = False
        self.sound = False
        self.money = 0

        self.width = width
        self.height = height

        self.unit_info_x_coef = 0.6
        self.unit_info_y_coef = 0.2

        self.unit_info = Text.Text('', self.width * self.unit_info_x_coef,
                                   self.height * self.unit_info_y_coef)
Пример #9
0
def update_base_list():
    if -337 < base_list[0].x < -334:
        new_base = Base.Base()
        base_list.append(new_base)

    if base_list[0].x < -336:
        base_list.pop(0)
Пример #10
0
 def createDataBase(self, basedatos: str, modo: int = 1):
     #0: exitoso, 1: error en la operación, 2: base de datos existente
     if self.lista_bases.existeBaseDatos(basedatos):
         return 2
     else:
         self.lista_bases.agregarBase(Base.Base(basedatos))
         return 0
     return 1
Пример #11
0
 def __init__(self, start, target, strategy):
     self.target = target
     self.start = Base(None, start, Direction(5), 0)
     self.strategy = strategy
     self.maxDepth = 0
     if (self.start.state != self.target):
         self.frontier.put(self.start.state)
         self.explored[str(self.start.state)] = self.start
Пример #12
0
def createDataBase(basedatos: str, modo: int = 1, owner=None):
    # 0: exitoso, 1: error en la operación, 2: base de datos existente
    respuesta = JM.createDatabase(basedatos)
    if respuesta != 0:
        return respuesta
    if lista_bases.existeBaseDatos(basedatos):
        return 2
    else:
        lista_bases.agregarBase(Base.Base(basedatos))
        return 0
    return 1
Пример #13
0
def main():
    pygame.init()
    width = 500
    height = 800
    WIN = pygame.display.set_mode((width, height))
    pygame.display.set_icon(
        pygame.image.load(os.path.join("imgs", "bird1.png")))
    pygame.display.set_caption("Flappy Bird")

    run = True
    clock = pygame.time.Clock()

    b = bird.Bird()
    bg = background.bg()
    pipe = Pipe.Pipe()
    pipes = [pipe]
    base = Base.Base()

    score = 0

    while run:
        clock.tick(30)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                print("Your score: " + str(score))
                run = False
                pygame.quit()
                quit()

        add_pipe = False
        rem = []
        for p in pipes:
            if p.collide(b):
                print("Your score: " + str(score))
                run = False

            if not p.passed and p.x < b.x:
                p.passed = True
                add_pipe = True

            if p.x + p.pipe_top.get_width() < 0:
                rem.append(p)

        if add_pipe:
            score += 1
            pipes.append(Pipe.Pipe())

        for r in rem:
            pipes.remove(r)

        move(WIN, b, pipes, base)
        draw(WIN, b, bg, pipes, base, score)
Пример #14
0
    def sample00(self, data):

        base = Base.Base(
        )  # using Base class for its XML specific common functions. (getXMLXPathValue, getXMLNodeValue, getXMLNode)
        xmlDOM = data['mdcs']  # access to MDCS config file
        command_used = base.getXMLNodeValue(xmlDOM, 'Command')

        workspace = data['workspace']
        md = data['mosaicdataset']

        log = data['log']
        log.Message('%s\\%s' % (workspace, md), 0)

        return True
Пример #15
0
 def __init__(self, start, target, strategy):
     self.target = target
     self.strategy = strategy
     self.start = Base(None, start, Direction(5), 0)
     self.maxDepth = 0
     self.rows = len(start)
     self.columns = len(start[0])
     if (self.start.state != self.target):
         if (self.strategy == 'manh'):
             distance = self.Manhattan(self.start.state)
         elif (self.strategy == 'hamm'):
             distance = self.Hamming(self.start.state)
         self.frontier.setdefault(distance, []).append(self.start.state)
         self.explored[str(self.start.state)] = self.start
Пример #16
0
 def solve(self):
     startTime = time()
     while (len(self.frontier) > 0):
         currentState = self.frontier.pop()
         currentStateString = currentState.__str__()
         currentState = self.explored[currentStateString]
         if (currentState.pathCost <= self.maxDepth):
             moves = currentState.getOrderedMoves(self.strategy)
             moves.reverse()
             for move in moves:
                 newArray = currentState.move(move)
                 newCost = currentState.pathCost + 1
                 newMove = move
                 newState = Base(currentState, newArray, newMove, newCost)
                 newStateString = newArray.__str__()
                 if (newStateString not in self.explored):
                     self.frontier.append(newArray)
                     self.explored[newStateString] = newState
                     if (newCost > self.DepthToFile):
                         self.DepthToFile = newCost
                     if (newArray == self.target):
                         solvingTime = time() - startTime
                         solved = round(solvingTime, 3)
                         path = newState.getPath()
                         explored = (len(self.explored) + 1)
                         frontier = len(self.explored) - len(self.frontier)
                         return path, explored, frontier, self.DepthToFile, solved
                 if (newStateString in self.explored):
                     oldCost = self.explored[newStateString].pathCost
                     if (newCost < oldCost):
                         if ((oldCost - newCost) >= 1):
                             self.frontier.append(newArray)
     solvingTime = time() - startTime
     solved = round(solvingTime, 3)
     explored = (len(self.explored) + 1)
     frontier = len(self.explored) - len(self.frontier)
     return -1, explored, frontier, self.DepthToFile + 1, solved
Пример #17
0
def main(genomes, config):

    # the network
    nets = []
    # the set of genomes
    ge = []
    # the list of birds
    birds = []

    # by accessing genomes in Neat module, we can create each bird for each genome, we can keep track of the fitness of
    # each bird and we can then create the training progress
    for _, g in genomes:
        net = neat.nn.FeedForwardNetwork.create(g, config)
        nets += [net]
        birds += [Bird(200, 200)]
        g.fitness = 0
        ge += [g]

    window = pygame.display.set_mode((WIDTH, HEIGHT))
    clock = pygame.time.Clock()

    base = Base()
    pipes = [Pipe(500)]
    running = 1
    # there is only one necessary pipe at one time. which is the pipe on the screen
    # we use a integer to access this pipe in the pipe list
    pipe_count = 0
    # count the score
    score = 0
    while running:

        clock.tick(30)
        event = pygame.event.poll()
        if event.type == pygame.QUIT:
            running = 0

        pipes[pipe_count].move()
        base.move()
        draw_window(window, birds, pipes[pipe_count], base)

        # end the generation if no birds left
        if len(birds) == 0:
            running = False
            break

        # moves for each bird each frame
        for i, bird in enumerate(birds):
            bird.move()
            # reward when the bird move(live for one more frame)
            ge[i].fitness += 0.1
            # activate the neural network using the output of how far the bird is from the gap for next pipe
            output = nets[i].activate(
                (bird.y, abs(bird.y - pipes[pipe_count].height),
                 abs(bird.y - pipes[pipe_count].bottom)))
            if output[0] > 0.5:
                bird.jump()

            # remove the bird, the genome from the network and give punishments when the bird collides with any pipe or
            # off the screen
            if pipes[pipe_count].collision(bird) or bird.y > 700 or bird.y < 0:
                ge[i].fitness -= 1
                birds.pop(i)
                nets.pop(i)
                ge.pop(i)

        # increment score when the bird pass a pipe. Need to round pipe.x because difference
        # between real time and the frame in the game
        if pipes[pipe_count].x // 5 * 5 == 200:
            score += 1
            # reward the birds that pass a pipe
            for g in ge:
                g.fitness += 5
            print(score)
        # Add a new pipe when the last one is off the screen
        if pipes[pipe_count].x == -80:
            pipes += [Pipe(500)]
            pipe_count += 1

        if score > 30:
            running = 0
            break
Пример #18
0
 def __init__(self):
     self.base = Base.Base()
 def test_id(self):
     base = Base()
     self.assertEqual(base.id, 1)
Пример #20
0
def main():
    max_score = 0
    loop = 0

    global cur_pipe
    pygame.init()

    screen = pygame.display.set_mode((screen_width, screen_heigh))
    pygame.display.set_caption('Flappy Bird')

    scene = Scene.Scene(pygame)
    bird = Bird.Bird(int(screen_width * 0.2), int(screen_heigh * 0.4),
                     scene.birdImgs)

    pygame.display.set_icon(bird.getIcon())
    screen.blit(scene.background, (0, 0))

    base = Base.Base(scene.base, 0, screen_heigh - 112,
                     scene.base.get_width() - scene.background.get_width())

    pipeList = []
    pipePosX = 0

    # Q Learing Code -- Begin
    m_state = {'vertical_distance': 0, 'horizontal_distance': 0}
    m_state_dash = {'vertical_distance': 0, 'horizontal_distance': 0}
    action_to_perform = 'do_nothing'
    explore = 0.0
    resolution = 4
    alpha_QL = 0.7
    vertical_distance_range = [-350, 190]
    horizontal_distance_range = [0, 180]

    Q = []
    for vert_dist in range(
            int((vertical_distance_range[1] - vertical_distance_range[0]) /
                resolution)):
        tmp = []
        for hori_dist in range(
                int((horizontal_distance_range[1] -
                     horizontal_distance_range[0]) / resolution)):
            tmp.append({'click': 0, 'do_nothing': 0})
        Q.append(tmp)

    vaild = False
    reward = 0
    # Q Learing Code -- End

    for i in range(100):
        if i == 0:
            pipePosX = screen_width - 250
        pipePosX += screen_width - 80
        pipe = Pipe.Pipe(scene.pipeImg, pipePosX, random.randint(0, 120),
                         screen_heigh)
        pipeList.append(pipe)

    score = 0

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.KEYDOWN and (event.key == pygame.K_SPACE):
                scene.Sounds['wing'].play()
                # 按下空格,小鸟处于“振翅”状态,即需要往上飞
                bird.birdFlapped = True
                # 小鸟最初的速度最大=10,逐步递减
                bird.bird_vel_y = 10
        if bird.bird_state == bird.BIRD_BEGIN:
            vaild = False
            score = 0
            pipePosX = 0
            pipeList.clear()

            for i in range(2):
                if i == 0:
                    pipePosX = screen_width - 250
                pipePosX += screen_width - 50
                pipe = Pipe.Pipe(scene.pipeImg, pipePosX,
                                 random.randint(0, 120), screen_heigh)
                pipeList.append(pipe)

            bird.bird_state = bird.BIRD_RUNNING

        elif bird.bird_state == bird.BIRD_RUNNING:
            # Q Learing Code -- Begin
            vaild = True
            reward = 1
            # Q Learing Code -- End
            screen.blit(scene.background, (0, 0))

            # “振翅”状态,且速度没到最大速度
            if bird.birdFlapped and bird.bird_vel_y > bird.BIRD_MIN_VEL_Y:
                bird.bird_vel_y -= bird.BIRD_ACC_Y
                bird.posY -= bird.bird_vel_y

            # 往上飞到达最大速度,此时应该下降,即脱离“振翅”状态
            if bird.birdFlapped and bird.bird_vel_y <= bird.BIRD_MIN_VEL_Y:
                bird.bird_vel_y = 1
                bird.birdFlapped = False

            # 处于非振翅状态时,小鸟下落
            if not bird.birdFlapped:
                bird.bird_vel_y += bird.BIRD_ACC_Y
                bird.posY += bird.bird_vel_y

            screen.blit(bird.getBirdImg(), (bird.posX, bird.posY))

            # 显示柱子
            for p in pipeList:
                p.posX -= REMOVE_SPEED

                if pipeList[0].posX + pipeList[0].pipeImg[0].get_width() < 0:
                    newPipe = Pipe.Pipe(
                        scene.pipeImg,
                        pipeList[len(pipeList) - 1].posX + screen_width - 80,
                        random.randint(0, 120), screen_heigh)
                    pipeList.append(newPipe)
                    pipeList.remove(p)

                screen.blit(p.pipeImg[0], (p.posX, p.posY[0]))
                screen.blit(p.pipeImg[1], (p.posX, p.posY[1]))

            # 在X方向移动地面图片
            base.pos_x = -((-base.pos_x + REMOVE_SPEED) % base.shift)
            screen.blit(scene.base, (base.pos_x, base.pos_y))

            rect_bird = pygame.Rect(bird.posX, bird.posY, bird.birdImgWidth,
                                    bird.birdImgHeight)
            # pygame.draw.rect(screen, (255, 0, 0), rect_bird, 1)

            rect_base = pygame.Rect(base.pos_x, base.pos_y, base.width,
                                    base.height)
            # 碰撞检测1:检查是否与地面相碰
            if rect_bird.colliderect(rect_base):
                bird.bird_state = bird.BIRD_DIE
                scene.Sounds['hit'].play()

            # 碰撞检测2:检测是否与当前屏幕显示的柱子碰撞
            cur_pipe = pipeList[0]
            for p in pipeList:
                if p.posX < screen_width and p.isOver == False:
                    cur_pipe = p
                    rect_pipe_up = pygame.Rect(cur_pipe.posX, cur_pipe.posY[0],
                                               cur_pipe.imgWidth,
                                               cur_pipe.imgHeight)
                    rect_pipe_down = pygame.Rect(cur_pipe.posX,
                                                 cur_pipe.posY[1],
                                                 cur_pipe.imgWidth,
                                                 cur_pipe.imgHeight)

                    # pygame.draw.rect(screen, (255, 0, 0), rect_pipe_up, 1)
                    # pygame.draw.rect(screen, (255, 0, 0), rect_pipe_down, 1)

                    if rect_bird.colliderect(rect_pipe_up):
                        bird.bird_state = bird.BIRD_DIE
                        scene.Sounds['hit'].play()
                        break

                    if rect_bird.colliderect(rect_pipe_down):
                        bird.bird_state = bird.BIRD_DIE
                        scene.Sounds['hit'].play()
                        break
                    break

            # 越过柱子得分+1
            if bird.posX > cur_pipe.posX + cur_pipe.imgWidth:
                scene.Sounds['point'].play()
                score += 1
                cur_pipe.isOver = True

            # 显示分数
            score_digits = [int(x) for x in list(str(score))]
            total_width = 0  # total width of all numbers to be printed

            for digit in score_digits:
                total_width += scene.number[digit].get_width()

            x_offset = (screen_width - total_width) / 2

            for digit in score_digits:
                screen.blit(scene.number[digit],
                            (x_offset, screen_heigh * 0.1))
                x_offset += scene.number[digit].get_width()

        elif bird.bird_state == bird.BIRD_DIE:
            # Q Learing Code -- Begin
            max_score = max(max_score, score)
            loop = loop + 1

            print('第', loop + 1, '轮, ', '最高分:', max_score)

            vaild = True
            reward = -1000
            # Q Learing Code -- End
            bird.posY = int(screen_heigh * 0.4)
            bird.bird_vel_y = 1
            bird.bird_state = bird.BIRD_BEGIN

        # Q Learing Code -- Begin
        if vaild:
            horizontal_distance = cur_pipe.posX + cur_pipe.imgWidth - bird.posX
            vertical_distance = bird.posY - cur_pipe.posY[1]
            m_state_dash['vertical_distance'] = vertical_distance
            m_state_dash['horizontal_distance'] = horizontal_distance

            state_bin_v = max(
                min(
                    int((vertical_distance_range[1] -
                         vertical_distance_range[0] - 1) / resolution),
                    int((m_state['vertical_distance'] -
                         vertical_distance_range[0]) / resolution)), 0)

            state_bin_h = max(
                min(
                    int((horizontal_distance_range[1] -
                         horizontal_distance_range[0] - 1) / resolution),
                    int((m_state['horizontal_distance'] -
                         horizontal_distance_range[0]) / resolution)), 0)

            state_dash_bin_v = max(
                min(
                    int((vertical_distance_range[1] -
                         vertical_distance_range[0] - 1) / resolution),
                    int((m_state_dash['vertical_distance'] -
                         vertical_distance_range[0]) / resolution)), 0)

            state_dash_bin_h = max(
                min(
                    int((horizontal_distance_range[1] -
                         horizontal_distance_range[0] - 1) / resolution),
                    int((m_state_dash['horizontal_distance'] -
                         horizontal_distance_range[0]) / resolution)), 0)

            click_v = Q[state_dash_bin_v][state_dash_bin_h]["click"]
            do_nothing_v = Q[state_dash_bin_v][state_dash_bin_h]["do_nothing"]
            V_s_dash_a_dash = max(click_v, do_nothing_v)

            Q_s_a = Q[state_bin_v][state_bin_h][action_to_perform]
            Q[state_bin_v][state_bin_h][
                action_to_perform] = Q_s_a + alpha_QL * (
                    reward + V_s_dash_a_dash - Q_s_a)

            m_state = copy.deepcopy(m_state_dash)

            if random.random() - 0.5 < explore:
                action_to_perform = 'click' if random.randint(
                    0, 2) == 0 else 'do_nothing'

            else:
                state_bin_v = max(
                    min(
                        int((vertical_distance_range[1] -
                             vertical_distance_range[0] - 1) / resolution),
                        int((m_state['vertical_distance'] -
                             vertical_distance_range[0]) / resolution)), 0)
                state_bin_h = max(
                    min(
                        int((horizontal_distance_range[1] -
                             horizontal_distance_range[0] - 1) / resolution),
                        int((m_state['horizontal_distance'] -
                             horizontal_distance_range[0]) / resolution)), 0)

                click_v = Q[state_bin_v][state_bin_h]['click']
                do_nothing_v = Q[state_bin_v][state_bin_h]['do_nothing']
                action_to_perform = 'click' if click_v > do_nothing_v else 'do_nothing'

                if action_to_perform == "click":
                    scene.Sounds['wing'].play()
                    # 按下空格,小鸟处于“振翅”状态,即需要往上飞
                    bird.birdFlapped = True
                    # 小鸟最初的速度最大=10,逐步递减
                    bird.bird_vel_y = 10
            # Q Learing Code -- End

        pygame.display.update()
        pygame.time.Clock().tick(FPS)
Пример #21
0
def main(argc, argv):

    if (argc < 2):
        # command-line argument codes.
        # -i:config file.
        # -c:command codes
        # -m:mosaic dataset name
        # -s:Source data paths. (as inputs to command (AR).
        # -l:Full path to log file (including file name)
        user_args = \
            [
                "-m: Mosaic dataset path including GDB and MD name [e.g. c:\WorldElevation.gdb\Portland]",
                "-s: Source data paths. (As inputs to command (AR). -s: can be repeated to add multiple paths",
                "-l: Log file output path [path+file name]",
                "-artdem: Update DEM path in ART file"
            ]
        print ("\nMDCS.py v5.9 [20170425]\nUsage: MDCS.py -c:<Optional:command> -i:<config_file>"
               "\n\nFlags to override configuration values,")
        for arg in user_args:
            print (arg)
        print (
            "\nNote: Commands can be combined with '+' to do multiple operations."
            "\nAvailable commands:")
        user_cmds = solutionsLib.Solutions().getAvailableCommands()
        for key in user_cmds:
            print ("\t" + key + ' = ' + user_cmds[key]['desc'])
        sys.exit(1)
    base = Base.Base()
    if (not g_cli_callback is None):
        base.m_cli_callback_ptr = g_cli_callback
    if (not g_cli_msg_callback is None):
        base.m_cli_msg_callback_ptr = g_cli_msg_callback
    global log
    log = logger.Logger(base)
    base.setLog(log)
    argIndx = 0
    md_path_ = artdem = config = com = log_folder = code_base = ''
    PathSeparator = ';'
    while(argIndx < argc):
        (values) = argv[argIndx].split(':')
        if (len(values[0]) < 2 or
            values[0][:1] != '-' and
                values[0][:1] != '#'):
            argIndx += 1
            continue
        exSubCode = values[0][1:len(values[0])].lower()
        subCode = values.pop(0)[1].lower()
        value = ':'.join(values).strip()
        if (subCode == 'c'):
            com = value.replace(' ', '')  # remove spaces in between.
        elif(subCode == 'i'):
            config = value
        elif(subCode == 'm'):
            md_path_ = value
        elif(subCode == 's'):
            base.m_sources += value + PathSeparator
        elif(subCode == 'l'):
            log_folder = value
        elif(subCode == 'b'):
            code_base = value
        elif(exSubCode == 'artdem'):
            artdem = value
        elif(exSubCode == 'gprun'):
            log.isGPRun = True                  # direct log messages also to (arcpy.AddMessage)
        elif(subCode == 'p'):
            pMax = value.rfind('$')
            if (pMax == -1):
                pMax = value.rfind('@')
            if (pMax == -1):
                argIndx += 1
                continue
            dynamic_var = value[pMax + 1:].upper()
            v = value[0: pMax]
            if (dynamic_var.strip() != ''):
                if ((dynamic_var in base.m_dynamic_params.keys()) == False):
                    base.m_dynamic_params[dynamic_var] = v
        argIndx += 1
    if (base.m_sources.endswith(PathSeparator)):
        base.m_sources = base.m_sources[:len(base.m_sources) - 1]
    if (code_base != ''):
        base.setCodeBase(code_base)
    if (md_path_ != ''):
        (p, f) = os.path.split(md_path_)
        f = f.strip()
        const_gdb_ext_len_ = len(base.const_geodatabase_ext)
        ext = p[-const_gdb_ext_len_:].lower()
        if ((ext == base.const_geodatabase_ext.lower() or
             ext == base.const_geodatabase_SDE_ext.lower()) and
                f != ''):
            p = p.replace('\\', '/')
            w = p.split('/')
            workspace_ = ''
            for i in range(0, len(w) - 1):
                workspace_ += w[i] + '/'
            gdb_ = w[len(w) - 1]
            base.m_workspace = workspace_
            base.m_geodatabase = w[len(w) - 1]
            base.m_mdName = f
    configName, ext = os.path.splitext(config)
    configName = os.path.basename(configName)
    # setup log
    log.Project('MDCS')
    log.LogNamePrefix(configName)
    log.StartLog()
    log_output_folder = os.path.join(os.path.dirname(solutionLib_path), 'logs')
    if (log_folder != ''):
        (path, fileName) = os.path.split(log_folder)
        if (path != ''):
            log_output_folder = path
        if (fileName != ''):
            log.LogFileName(fileName)

    log.SetLogFolder(log_output_folder)
    # ends
    # Source version check.
    versionCheck = ProgramCheckAndUpdate()
    log.Message('Checking for updates..', logger.Logger.const_general_text)
    verMessage = versionCheck.run(solutionLib_path)
    if (verMessage is not None):
        log.Message(verMessage, logger.Logger.const_warning_text)
    # ends
    if (os.path.isfile(config) == False):
        log.Message('Input config file is not specified/not found! ({})'.format(config), logger.Logger.const_critical_text)
        log.Message(base.CCMD_STATUS_FAILED, logger.Logger.const_status_text)    # set (failed) status
        log.WriteLog('#all')
        return False
    if (artdem != ''):
        (base.m_art_ws, base.m_art_ds) = os.path.split(artdem)
        base.m_art_apply_changes = True
    comInfo = {
        'AR': {'cb': postAddData}  # assign a callback function to run custom user code when adding rasters.
    }
    if (com == ''):
        com = base.const_cmd_default_text
    solutions = solutionsLib.Solutions(base)
    results = solutions.run(config, com, comInfo)
    log.Message("Done...", log.const_general_text)
    log.WriteLog('#all')  # persist information/errors collected.
    return results
Пример #22
0
	public:
		Bulk_quote() = default;
		Bulk_quote(const std::string& book, double price,
		          std::size_t qty, double disc):
		      Disc_quote(book, price, qty, disc) { }
		double net_price(std::size_t) const override;
	};
	Bulk_quote bulk;
	Bulk_quote *bulkP = &bulk; // 静态类型和动态类型都是Bulk_quote
	Quote *itemP = &bulk;      // 静态类型是Quote,动态类型是Bulk_quote
	bulkP->discount_policy();  // 正确,bulkP的静态类型是Bulk_quote,在Bulk_quote作用域中寻找discount_policy,找不到就在Disc_quote中找discount_policy,找到了
	itemP->discount_policy();  // 错误,itemP的静态类型是Quote作用域中找,找不到了

#名字在作用域中冲突
struct Base {
    Base(): mem(0) { }
protected:
    int mem;
};
struct Derived : Base {
    Derived(int i): mem(i) { } //用i初始化派生类的mem,基类的mem采用默认初始化
    int get_mem() { return mem; }  // returns Derived::mem
protected:
    int mem;   #隐藏了基类的men
};
#很重要:名字查找优先于类型检查
	————即先名字匹配,匹配到了再做类型检查,即便类型检查失败,也不在往后进行名字检查了

15、明白函数调用的解析过程:p->men()或p.men()
		1)先确定p的静态类型
		2)在其静态类型对应的类中查找men,若找不到,则向基类查找,直到到达继承链的顶层,如果还是找不到,编译器保错;若找到,则进行类型检查,以确定本次调用是否合法
Пример #23
0
def run():

    pygame.init()
    screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)

    world = World()

    w, h = SCREEN_SIZE

    clock = pygame.time.Clock()

    # --- Load images ---
    blue_base_image = pygame.image.load("assets/blue_base.png").convert_alpha()
    blue_orc_image = pygame.image.load("assets/blue_orc_32_32.png").convert_alpha()
    blue_tower_image = pygame.image.load("assets/blue_tower.png").convert_alpha()
    blue_rock_image = pygame.image.load("assets/blue_rock.png").convert_alpha()
    #blue_knight_image = pygame.image.load("assets/blue_knight_32_32.png").convert_alpha()
    blue_archer_image = pygame.image.load("assets/blue_archer_32_32.png").convert_alpha()
    blue_arrow_image = pygame.image.load("assets/blue_arrow.png").convert_alpha()
    #blue_wizard_image = pygame.image.load("assets/blue_wizard_32_32.png").convert_alpha()
    #blue_explosion_image = pygame.image.load("assets/blue_explosion.png").convert_alpha()

    red_base_image = pygame.image.load("assets/red_base.png").convert_alpha()
    red_orc_image = pygame.image.load("assets/red_orc_32_32.png").convert_alpha()
    red_tower_image = pygame.image.load("assets/red_tower.png").convert_alpha()
    red_rock_image = pygame.image.load("assets/red_rock.png").convert_alpha()
    red_knight_image = pygame.image.load("assets/red_knight_32_32.png").convert_alpha()
    red_archer_image = pygame.image.load("assets/red_archer_32_32.png").convert_alpha()
    red_arrow_image = pygame.image.load("assets/red_arrow.png").convert_alpha()
    red_wizard_image = pygame.image.load("assets/red_wizard_32_32.png").convert_alpha()
    red_explosion_image = pygame.image.load("assets/red_explosion.png").convert_alpha()

    grey_tower_image = pygame.image.load("assets/grey_tower.png").convert_alpha()
    grey_projectile_image = pygame.image.load("assets/grey_rock.png").convert_alpha()
    mountain_image_1 = pygame.image.load("assets/mountain_1.png").convert_alpha()
    mountain_image_2 = pygame.image.load("assets/mountain_2.png").convert_alpha()
    plateau_image = pygame.image.load("assets/plateau.png").convert_alpha()


    # --- Initialize Blue buildings and units ---
    blue_base = Base(world, blue_base_image, blue_orc_image, blue_rock_image, 0, 4)
    blue_base.position = Vector2(68, 68)
    blue_base.team_id = 0
    blue_base.max_hp = BASE_MAX_HP
    blue_base.min_target_distance = BASE_MIN_TARGET_DISTANCE
    blue_base.projectile_range = BASE_PROJECTILE_RANGE
    blue_base.projectile_speed = BASE_PROJECTILE_SPEED
    blue_base.ranged_damage = BASE_RANGED_DAMAGE
    blue_base.ranged_cooldown = BASE_RANGED_COOLDOWN
    blue_base.current_hp = blue_base.max_hp
    blue_base.brain.set_state("base_state")
    world.add_entity(blue_base)

    blue_tower_1 = Tower(world, blue_tower_image, blue_rock_image)
    blue_tower_1.position = Vector2(200, 100)
    blue_tower_1.team_id = 0
    blue_tower_1.max_hp = TOWER_MAX_HP
    blue_tower_1.min_target_distance = TOWER_MIN_TARGET_DISTANCE
    blue_tower_1.projectile_range = TOWER_PROJECTILE_RANGE
    blue_tower_1.projectile_speed = TOWER_PROJECTILE_SPEED
    blue_tower_1.ranged_damage = TOWER_RANGED_DAMAGE
    blue_tower_1.ranged_cooldown = TOWER_RANGED_COOLDOWN
    blue_tower_1.current_hp = blue_tower_1.max_hp
    blue_tower_1.brain.set_state("tower_state")
    world.add_entity(blue_tower_1)

    blue_tower_2 = Tower(world, blue_tower_image, blue_rock_image)
    blue_tower_2.position = Vector2(105, 190)
    blue_tower_2.team_id = 0
    blue_tower_2.max_hp = TOWER_MAX_HP
    blue_tower_2.min_target_distance = TOWER_MIN_TARGET_DISTANCE
    blue_tower_2.projectile_range = TOWER_PROJECTILE_RANGE
    blue_tower_2.projectile_speed = TOWER_PROJECTILE_SPEED
    blue_tower_2.ranged_damage = TOWER_RANGED_DAMAGE
    blue_tower_2.ranged_cooldown = TOWER_RANGED_COOLDOWN
    blue_tower_2.current_hp = blue_tower_2.max_hp
    blue_tower_2.brain.set_state("tower_state")
    world.add_entity(blue_tower_2)

    #blue_knight = Knight_TeamA(world, blue_knight_image, blue_base, Vector2(blue_base.spawn_position))
    #blue_knight.team_id = 0
    #blue_knight.max_hp = KNIGHT_MAX_HP
    #blue_knight.min_target_distance = KNIGHT_MIN_TARGET_DISTANCE
##    blue_knight.melee_damage = KNIGHT_MELEE_DAMAGE
##    blue_knight.melee_cooldown = KNIGHT_MELEE_COOLDOWN
##    blue_knight.current_hp = blue_knight.max_hp
##    #world.add_entity(blue_knight)

    blue_archer = Archer_TeamA(world, blue_archer_image, blue_arrow_image, blue_base, Vector2(blue_base.spawn_position))
    blue_archer.team_id = 0
    blue_archer.max_hp = ARCHER_MAX_HP
    blue_archer.maxSpeed = ARCHER_MAX_SPEED
    blue_archer.min_target_distance = ARCHER_MIN_TARGET_DISTANCE
    blue_archer.projectile_range = ARCHER_PROJECTILE_RANGE
    blue_archer.projectile_speed = ARCHER_PROJECTILE_SPEED
    blue_archer.ranged_damage = ARCHER_RANGED_DAMAGE
    blue_archer.ranged_cooldown = ARCHER_RANGED_COOLDOWN
    blue_archer.current_hp = blue_archer.max_hp
    world.add_entity(blue_archer)
##
##    blue_wizard = Wizard_TeamA(world, blue_wizard_image, blue_rock_image, blue_base, Vector2(blue_base.spawn_position), blue_explosion_image)
##    blue_wizard.team_id = 0
##    blue_wizard.max_hp = WIZARD_MAX_HP
##    blue_wizard.maxSpeed = WIZARD_MAX_SPEED
##    blue_wizard.min_target_distance = WIZARD_MIN_TARGET_DISTANCE
##    blue_wizard.projectile_range = WIZARD_PROJECTILE_RANGE
##    blue_wizard.projectile_speed = WIZARD_PROJECTILE_SPEED
##    blue_wizard.ranged_damage = WIZARD_RANGED_DAMAGE
##    blue_wizard.ranged_cooldown = WIZARD_RANGED_COOLDOWN
##    blue_wizard.current_hp = blue_wizard.max_hp
    #world.add_entity(blue_wizard)


    # --- Initialize Red buildings and units ---
    red_base = Base(world, red_base_image, red_orc_image, red_rock_image, 4, 0)
    red_base.position = Vector2(SCREEN_WIDTH - 68, SCREEN_HEIGHT - 68)
    red_base.team_id = 1
    red_base.max_hp = BASE_MAX_HP * RED_MULTIPLIER
    red_base.min_target_distance = BASE_MIN_TARGET_DISTANCE
    red_base.projectile_range = BASE_PROJECTILE_RANGE
    red_base.projectile_speed = BASE_PROJECTILE_SPEED
    red_base.ranged_damage = BASE_RANGED_DAMAGE * RED_MULTIPLIER
    red_base.ranged_cooldown = BASE_RANGED_COOLDOWN
    red_base.current_hp = red_base.max_hp
    red_base.brain.set_state("base_state")
    world.add_entity(red_base)

    red_tower_1 = Tower(world, red_tower_image, red_rock_image)
    red_tower_1.position = Vector2(820, 660)
    red_tower_1.team_id = 1
    red_tower_1.max_hp = TOWER_MAX_HP * RED_MULTIPLIER
    red_tower_1.min_target_distance = TOWER_MIN_TARGET_DISTANCE
    red_tower_1.projectile_range = TOWER_PROJECTILE_RANGE
    red_tower_1.projectile_speed = TOWER_PROJECTILE_SPEED
    red_tower_1.ranged_damage = TOWER_RANGED_DAMAGE * RED_MULTIPLIER
    red_tower_1.ranged_cooldown = TOWER_RANGED_COOLDOWN
    red_tower_1.current_hp = red_tower_1.max_hp
    red_tower_1.brain.set_state("tower_state")
    world.add_entity(red_tower_1)

    red_tower_2 = Tower(world, red_tower_image, red_rock_image)
    red_tower_2.position = Vector2(910, 570)
    red_tower_2.team_id = 1
    red_tower_2.max_hp = TOWER_MAX_HP * RED_MULTIPLIER
    red_tower_2.min_target_distance = TOWER_MIN_TARGET_DISTANCE
    red_tower_2.projectile_range = TOWER_PROJECTILE_RANGE
    red_tower_2.projectile_speed = TOWER_PROJECTILE_SPEED
    red_tower_2.ranged_damage = TOWER_RANGED_DAMAGE * RED_MULTIPLIER
    red_tower_2.ranged_cooldown = TOWER_RANGED_COOLDOWN
    red_tower_2.current_hp = red_tower_2.max_hp
    red_tower_2.brain.set_state("tower_state")
    world.add_entity(red_tower_2)

##    red_knight = Knight_TeamB(world, red_knight_image, red_base, Vector2(red_base.spawn_position))
##    red_knight.team_id = 1
##    red_knight.max_hp = KNIGHT_MAX_HP * RED_MULTIPLIER
##    red_knight.min_target_distance = KNIGHT_MIN_TARGET_DISTANCE
##    red_knight.melee_damage = KNIGHT_MELEE_DAMAGE * RED_MULTIPLIER
##    red_knight.melee_cooldown = KNIGHT_MELEE_COOLDOWN
##    red_knight.current_hp = red_knight.max_hp
##    world.add_entity(red_knight)
##
    red_archer = Archer_TeamB(world, red_archer_image, red_arrow_image, red_base, Vector2(red_base.spawn_position))
    red_archer.team_id = 1
    red_archer.max_hp = ARCHER_MAX_HP * RED_MULTIPLIER
    red_archer.maxSpeed = ARCHER_MAX_SPEED
    red_archer.min_target_distance = ARCHER_MIN_TARGET_DISTANCE
    red_archer.projectile_range = ARCHER_PROJECTILE_RANGE
    red_archer.projectile_speed = ARCHER_PROJECTILE_SPEED
    red_archer.ranged_damage = ARCHER_RANGED_DAMAGE * RED_MULTIPLIER
    red_archer.ranged_cooldown = ARCHER_RANGED_COOLDOWN
    red_archer.current_hp = red_archer.max_hp
    world.add_entity(red_archer)

##    red_wizard = Wizard_TeamB(world, red_wizard_image, red_rock_image, red_base, Vector2(red_base.spawn_position), red_explosion_image)
##    red_wizard.team_id = 1
##    red_wizard.max_hp = WIZARD_MAX_HP * RED_MULTIPLIER
##    red_wizard.maxSpeed = WIZARD_MAX_SPEED
##    red_wizard.min_target_distance = WIZARD_MIN_TARGET_DISTANCE
##    red_wizard.projectile_range = WIZARD_PROJECTILE_RANGE
##    red_wizard.projectile_speed = WIZARD_PROJECTILE_SPEED
##    red_wizard.ranged_damage = WIZARD_RANGED_DAMAGE * RED_MULTIPLIER
##    red_wizard.ranged_cooldown = WIZARD_RANGED_COOLDOWN
##    red_wizard.current_hp = red_wizard.max_hp
##    world.add_entity(red_wizard)
##    

    # --- Initialize other entities in the world ---
    mountain_1 = Obstacle(world, mountain_image_1)
    mountain_1.position = Vector2(410, 460)
    mountain_1.team_id = 2
    world.add_entity(mountain_1)
    world.obstacles.append(mountain_1)

    mountain_2 = Obstacle(world, mountain_image_2)
    mountain_2.position = Vector2(620, 280)
    mountain_2.team_id = 2
    world.add_entity(mountain_2)
    world.obstacles.append(mountain_2)

    plateau = Obstacle(world, plateau_image)
    plateau.position = Vector2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)
    plateau.team_id = 2
    world.add_entity(plateau)
    world.obstacles.append(plateau)

    grey_tower = Tower(world, grey_tower_image, grey_projectile_image)
    grey_tower.position = Vector2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 10)
    grey_tower.team_id = 2
    grey_tower.min_target_distance = GREY_TOWER_MIN_TARGET_DISTANCE
    grey_tower.projectile_range = GREY_TOWER_PROJECTILE_RANGE
    grey_tower.projectile_speed = GREY_TOWER_PROJECTILE_SPEED
    grey_tower.ranged_damage = GREY_TOWER_RANGED_DAMAGE
    grey_tower.ranged_cooldown = GREY_TOWER_RANGED_COOLDOWN
    grey_tower.brain.set_state("tower_state")
    world.add_entity(grey_tower)


    while True:

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

            if pygame.mouse.get_pressed()[0]:
                print(pygame.mouse.get_pos())

        # check for end of game
        if not world.game_end:
            time_passed = clock.tick(100000)
            world.process(time_passed)

        world.render(screen)
        
        pygame.display.update()
Пример #24
0
# -*-coding:utf-8 -*-

import SimHttp
import BaiduRank
import Cookie
import sqliteconn
import time
import Base

cookie = Cookie.SimpleCookie()
sim = SimHttp.SimBrowser(cookie)
base = Base.Base()

host_name = 'http://keys.tu1001.com:1110'

def clean_tag(src):
    ret = src
    #print ret
    while True:
        s = ret.find('<')
        if s == -1:
            return ret
        e = ret.find('>')
        ret = ret[:s] + ret[e+1:]
    return ret

def get_baidu_loadurl(key_word, target_url):
    '''得到百度着陆页'''
    host = 'http://www.baidu.com/s'
    url = host + '?wd=site%3A' + target_url + '+' + key_word
    re, content = sim.request(url, 'GET')
Пример #25
0
def main(argc, argv):

    argc = len(argv)
    if (argc < 2):

    #command-line argument codes.
    #-i:config file.
    #-c:command codes
    #-m:mosaic dataset name
    #-s:Source data paths. (as inputs to command (AR/AR)
    #-l:Full path to log file (including file name)

        user_args = \
        [
        "-m: Mosaic dataset path including GDB and MD name [e.g. c:\WorldElevation.gdb\Portland]",
        "-s: Source data paths. (As inputs to command (AR)",
        "-l: Log file output path [path+file name]",
        "-artdem: Update DEM path in ART file"
        ]

        print "\nMDCS.py v5.6 [20130801]\nUsage: MDCS.py -c:<Optional:command> -i:<config_file>" \
        "\n\nFlags to override configuration values," \

        for arg in user_args:
            print arg

        print \
        "\nNote: Commands can be combined with '+' to do multiple operations." \
        "\nAvailable commands:"

        user_cmds = solutionsLib.Solutions().getAvailableCommands()
        for key in user_cmds:
            print "\t" + key + ' = ' + user_cmds[key]['desc']

        sys.exit(1)


    base = Base.Base()
    global log
    log = logger.Logger();
    base.setLog(log)


    argIndx = 1
    md_path_ = artdem = config = com = log_folder = ''

    while(argIndx < argc):
        (values) = argv[argIndx].split(':')
        if (len(values[0]) < 2 or
            values[0][:1] != '-' and
            values[0][:1] != '#'):
            argIndx += 1
            continue

        exSubCode = values[0][1:len(values[0])].lower()
        subCode = values.pop(0)[1].lower()

        value = ':'.join(values).strip()

        if (subCode == 'c'):
            com = value.replace(' ', '')        #remove spaces in between.
        elif(subCode == 'i'):
            config = value
        elif(subCode == 'm'):
            md_path_ = value
        elif(subCode == 's'):
            base.m_sources = value
        elif(subCode == 'l'):
            log_folder =  value
        elif(exSubCode == 'artdem'):
            artdem =  value
        elif(subCode == 'p'):
            pMax = value.rfind('$')
            if (pMax == -1):
                argIndx += 1
                continue

            dynamic_var = value[pMax + 1:].upper()
            v =  value[0: pMax]
            if (dynamic_var.strip() != ''):
                if (base.m_dynamic_params.has_key(dynamic_var) == False):
                    base.m_dynamic_params[dynamic_var] = v

        argIndx += 1


    if (md_path_ != ''):
        (p, f) = os.path.split(md_path_)
        f = f.strip()
        const_gdb_ext_len_ = len(base.const_geodatabase_ext)
        ext = p[-const_gdb_ext_len_:].lower()
        if ((ext == base.const_geodatabase_ext.lower() or
            ext == base.const_geodatabase_SDE_ext.lower()) and
            f != ''):
            p = p.replace('\\', '/')
            w = p.split('/')
            workspace_ = ''
            for i in range(0, len(w) - 1):
                workspace_ += w[i] + '/'

            gdb_ = w[len(w) -1]
            base.m_workspace = workspace_
            base.m_geodatabase = w[len(w) - 1]
            base.m_mdName = f


    if (os.path.isfile(config) == False):
        errMessage = u"Error: Input config file is not specified/not found! " + config
        arcpy.AddMessage(errMessage)
        return False


    if (artdem != ''):
        (base.m_art_ws, base.m_art_ds) = os.path.split(artdem)
        base.m_art_apply_changes = True


    comInfo = {
    'AR' : { 'cb' : postAddData }       #assign a callback function to run custom user code when adding rasters.
    }


    configName, ext = os.path.splitext(config)
    configName = os.path.basename(configName)



    if (com == ''):
        com = base.const_cmd_default_text

    if (argv[1].lower() == '#gprun'):
        log.isGPRun = True
    log.Project ('MDCS')
    log.LogNamePrefix(configName)
    log.StartLog()

    log_output_folder  = os.path.join(os.path.dirname(solutionLib_path), 'logs')

    if (log_folder != ''):
        (path, fileName) = os.path.split(log_folder)
        if (path != ''):
            log_output_folder = path
        if (fileName != ''):
            log.LogFileName(fileName)

    log.SetLogFolder(log_output_folder)
    solutions = solutionsLib.Solutions(base)
    success = solutions.run(config, com, comInfo)

    log.WriteLog('#all')   #persist information/errors collected.

    print "Done..."
Пример #26
0
def run():

    pygame.init()
    screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)

    world = World()

    w, h = SCREEN_SIZE

    # --- Load images ---
    blue_base_image = pygame.image.load("assets/blue_base.png").convert_alpha()
    blue_orc_image = pygame.image.load("assets/blue_orc_32_32.png").convert_alpha()
    blue_tower_image = pygame.image.load("assets/blue_tower.png").convert_alpha()
    blue_rock_image = pygame.image.load("assets/blue_rock.png").convert_alpha()
    blue_knight_image = pygame.image.load("assets/blue_knight_32_32.png").convert_alpha()
    blue_archer_image = pygame.image.load("assets/blue_archer_32_32.png").convert_alpha()
    blue_arrow_image = pygame.image.load("assets/blue_arrow.png").convert_alpha()
    blue_wizard_image = pygame.image.load("assets/blue_wizard_32_32.png").convert_alpha()
    blue_explosion_image = pygame.image.load("assets/blue_explosion.png").convert_alpha()

    red_base_image = pygame.image.load("assets/red_base.png").convert_alpha()
    red_orc_image = pygame.image.load("assets/red_orc_32_32.png").convert_alpha()
    red_tower_image = pygame.image.load("assets/red_tower.png").convert_alpha()
    red_rock_image = pygame.image.load("assets/red_rock.png").convert_alpha()
    red_knight_image = pygame.image.load("assets/red_knight_32_32.png").convert_alpha()
    red_archer_image = pygame.image.load("assets/red_archer_32_32.png").convert_alpha()
    red_arrow_image = pygame.image.load("assets/red_arrow.png").convert_alpha()
    red_wizard_image = pygame.image.load("assets/red_wizard_32_32.png").convert_alpha()
    red_explosion_image = pygame.image.load("assets/red_explosion.png").convert_alpha()

    grey_tower_image = pygame.image.load("assets/grey_tower.png").convert_alpha()
    grey_projectile_image = pygame.image.load("assets/grey_rock.png").convert_alpha()
    mountain_image_1 = pygame.image.load("assets/mountain_1.png").convert_alpha()
    mountain_image_2 = pygame.image.load("assets/mountain_2.png").convert_alpha()
    plateau_image = pygame.image.load("assets/plateau.png").convert_alpha()


    # --- Initialize Blue buildings and units ---
    blue_base = Base(world, blue_base_image, blue_orc_image, blue_rock_image, 0, 4)
    blue_base.position = Vector2(68, 68)
    blue_base.team_id = 0
    blue_base.max_hp = BASE_MAX_HP
    blue_base.min_target_distance = BASE_MIN_TARGET_DISTANCE
    blue_base.projectile_range = BASE_PROJECTILE_RANGE
    blue_base.projectile_speed = BASE_PROJECTILE_SPEED
    blue_base.ranged_damage = BASE_RANGED_DAMAGE
    blue_base.ranged_cooldown = BASE_RANGED_COOLDOWN
    blue_base.current_hp = blue_base.max_hp
    blue_base.brain.set_state("base_state")
    world.add_entity(blue_base)

    blue_tower_1 = Tower(world, blue_tower_image, blue_rock_image)
    blue_tower_1.position = Vector2(200, 100)
    blue_tower_1.team_id = 0
    blue_tower_1.max_hp = TOWER_MAX_HP
    blue_tower_1.min_target_distance = TOWER_MIN_TARGET_DISTANCE
    blue_tower_1.projectile_range = TOWER_PROJECTILE_RANGE
    blue_tower_1.projectile_speed = TOWER_PROJECTILE_SPEED
    blue_tower_1.ranged_damage = TOWER_RANGED_DAMAGE
    blue_tower_1.ranged_cooldown = TOWER_RANGED_COOLDOWN
    blue_tower_1.current_hp = blue_tower_1.max_hp
    blue_tower_1.brain.set_state("tower_state")
    world.add_entity(blue_tower_1)

    blue_tower_2 = Tower(world, blue_tower_image, blue_rock_image)
    blue_tower_2.position = Vector2(105, 190)
    blue_tower_2.team_id = 0
    blue_tower_2.max_hp = TOWER_MAX_HP
    blue_tower_2.min_target_distance = TOWER_MIN_TARGET_DISTANCE
    blue_tower_2.projectile_range = TOWER_PROJECTILE_RANGE
    blue_tower_2.projectile_speed = TOWER_PROJECTILE_SPEED
    blue_tower_2.ranged_damage = TOWER_RANGED_DAMAGE
    blue_tower_2.ranged_cooldown = TOWER_RANGED_COOLDOWN
    blue_tower_2.current_hp = blue_tower_2.max_hp
    blue_tower_2.brain.set_state("tower_state")
    world.add_entity(blue_tower_2)

    blue_knight = Knight_PIRANHAGUN(world, blue_knight_image, blue_base, Vector2(blue_base.spawn_position))
    blue_knight.team_id = 0
    blue_knight.max_hp = KNIGHT_MAX_HP
    blue_knight.min_target_distance = KNIGHT_MIN_TARGET_DISTANCE
    blue_knight.melee_damage = KNIGHT_MELEE_DAMAGE
    blue_knight.melee_cooldown = KNIGHT_MELEE_COOLDOWN
    blue_knight.current_hp = blue_knight.max_hp
    world.add_entity(blue_knight)

    blue_archer = Archer_PIRANHAGUN(world, blue_archer_image, blue_arrow_image, blue_base, Vector2(blue_base.spawn_position))
    blue_archer.team_id = 0
    blue_archer.max_hp = ARCHER_MAX_HP
    blue_archer.maxSpeed = ARCHER_MAX_SPEED
    blue_archer.min_target_distance = ARCHER_MIN_TARGET_DISTANCE
    blue_archer.projectile_range = ARCHER_PROJECTILE_RANGE
    blue_archer.projectile_speed = ARCHER_PROJECTILE_SPEED
    blue_archer.ranged_damage = ARCHER_RANGED_DAMAGE
    blue_archer.ranged_cooldown = ARCHER_RANGED_COOLDOWN
    blue_archer.current_hp = blue_archer.max_hp
    world.add_entity(blue_archer)

    blue_wizard = Wizard_PIRANHAGUN(world, blue_wizard_image, blue_rock_image, blue_base, Vector2(blue_base.spawn_position), blue_explosion_image)
    blue_wizard.team_id = 0
    blue_wizard.max_hp = WIZARD_MAX_HP
    blue_wizard.maxSpeed = WIZARD_MAX_SPEED
    blue_wizard.min_target_distance = WIZARD_MIN_TARGET_DISTANCE
    blue_wizard.projectile_range = WIZARD_PROJECTILE_RANGE
    blue_wizard.projectile_speed = WIZARD_PROJECTILE_SPEED
    blue_wizard.ranged_damage = WIZARD_RANGED_DAMAGE
    blue_wizard.ranged_cooldown = WIZARD_RANGED_COOLDOWN
    blue_wizard.current_hp = blue_wizard.max_hp
    world.add_entity(blue_wizard)


    # --- Initialize Red buildings and units ---
    red_base = Base(world, red_base_image, red_orc_image, red_rock_image, 4, 0)
    red_base.position = Vector2(SCREEN_WIDTH - 68, SCREEN_HEIGHT - 68)
    red_base.team_id = 1
    red_base.max_hp = BASE_MAX_HP * RED_MULTIPLIER
    red_base.min_target_distance = BASE_MIN_TARGET_DISTANCE
    red_base.projectile_range = BASE_PROJECTILE_RANGE
    red_base.projectile_speed = BASE_PROJECTILE_SPEED
    red_base.ranged_damage = BASE_RANGED_DAMAGE * RED_MULTIPLIER
    red_base.ranged_cooldown = BASE_RANGED_COOLDOWN
    red_base.current_hp = red_base.max_hp
    red_base.brain.set_state("base_state")
    world.add_entity(red_base)

    red_tower_1 = Tower(world, red_tower_image, red_rock_image)
    red_tower_1.position = Vector2(820, 660)
    red_tower_1.team_id = 1
    red_tower_1.max_hp = TOWER_MAX_HP * RED_MULTIPLIER
    red_tower_1.min_target_distance = TOWER_MIN_TARGET_DISTANCE
    red_tower_1.projectile_range = TOWER_PROJECTILE_RANGE
    red_tower_1.projectile_speed = TOWER_PROJECTILE_SPEED
    red_tower_1.ranged_damage = TOWER_RANGED_DAMAGE * RED_MULTIPLIER
    red_tower_1.ranged_cooldown = TOWER_RANGED_COOLDOWN
    red_tower_1.current_hp = red_tower_1.max_hp
    red_tower_1.brain.set_state("tower_state")
    world.add_entity(red_tower_1)

    red_tower_2 = Tower(world, red_tower_image, red_rock_image)
    red_tower_2.position = Vector2(910, 570)
    red_tower_2.team_id = 1
    red_tower_2.max_hp = TOWER_MAX_HP * RED_MULTIPLIER
    red_tower_2.min_target_distance = TOWER_MIN_TARGET_DISTANCE
    red_tower_2.projectile_range = TOWER_PROJECTILE_RANGE
    red_tower_2.projectile_speed = TOWER_PROJECTILE_SPEED
    red_tower_2.ranged_damage = TOWER_RANGED_DAMAGE * RED_MULTIPLIER
    red_tower_2.ranged_cooldown = TOWER_RANGED_COOLDOWN
    red_tower_2.current_hp = red_tower_2.max_hp
    red_tower_2.brain.set_state("tower_state")
    world.add_entity(red_tower_2)

    red_knight = Knight_TeamB(world, red_knight_image, red_base, Vector2(red_base.spawn_position))
    red_knight.team_id = 1
    red_knight.max_hp = KNIGHT_MAX_HP * RED_MULTIPLIER
    red_knight.min_target_distance = KNIGHT_MIN_TARGET_DISTANCE
    red_knight.melee_damage = KNIGHT_MELEE_DAMAGE * RED_MULTIPLIER
    red_knight.melee_cooldown = KNIGHT_MELEE_COOLDOWN
    red_knight.current_hp = red_knight.max_hp
    world.add_entity(red_knight)

    red_archer = Archer_TeamB(world, red_archer_image, red_arrow_image, red_base, Vector2(red_base.spawn_position))
    red_archer.team_id = 1
    red_archer.max_hp = ARCHER_MAX_HP * RED_MULTIPLIER
    red_archer.maxSpeed = ARCHER_MAX_SPEED
    red_archer.min_target_distance = ARCHER_MIN_TARGET_DISTANCE
    red_archer.projectile_range = ARCHER_PROJECTILE_RANGE
    red_archer.projectile_speed = ARCHER_PROJECTILE_SPEED
    red_archer.ranged_damage = ARCHER_RANGED_DAMAGE * RED_MULTIPLIER
    red_archer.ranged_cooldown = ARCHER_RANGED_COOLDOWN
    red_archer.current_hp = red_archer.max_hp
    world.add_entity(red_archer)

    red_wizard = Wizard_TeamB(world, red_wizard_image, red_rock_image, red_base, Vector2(red_base.spawn_position), red_explosion_image)
    red_wizard.team_id = 1
    red_wizard.max_hp = WIZARD_MAX_HP * RED_MULTIPLIER
    red_wizard.maxSpeed = WIZARD_MAX_SPEED
    red_wizard.min_target_distance = WIZARD_MIN_TARGET_DISTANCE
    red_wizard.projectile_range = WIZARD_PROJECTILE_RANGE
    red_wizard.projectile_speed = WIZARD_PROJECTILE_SPEED
    red_wizard.ranged_damage = WIZARD_RANGED_DAMAGE * RED_MULTIPLIER
    red_wizard.ranged_cooldown = WIZARD_RANGED_COOLDOWN
    red_wizard.current_hp = red_wizard.max_hp
    world.add_entity(red_wizard)
    

    # --- Initialize other entities in the world ---
    mountain_1 = Obstacle(world, mountain_image_1)
    mountain_1.position = Vector2(410, 460)
    mountain_1.team_id = 2
    world.add_entity(mountain_1)
    world.obstacles.append(mountain_1)

    mountain_2 = Obstacle(world, mountain_image_2)
    mountain_2.position = Vector2(620, 280)
    mountain_2.team_id = 2
    world.add_entity(mountain_2)
    world.obstacles.append(mountain_2)

    plateau = Obstacle(world, plateau_image)
    plateau.position = Vector2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)
    plateau.team_id = 2
    world.add_entity(plateau)
    world.obstacles.append(plateau)

    grey_tower = Tower(world, grey_tower_image, grey_projectile_image)
    grey_tower.position = Vector2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 10)
    grey_tower.team_id = 2
    grey_tower.min_target_distance = GREY_TOWER_MIN_TARGET_DISTANCE
    grey_tower.projectile_range = GREY_TOWER_PROJECTILE_RANGE
    grey_tower.projectile_speed = GREY_TOWER_PROJECTILE_SPEED
    grey_tower.ranged_damage = GREY_TOWER_RANGED_DAMAGE
    grey_tower.ranged_cooldown = GREY_TOWER_RANGED_COOLDOWN
    grey_tower.brain.set_state("tower_state")
    world.add_entity(grey_tower)

    # Splash screen

    if SHOW_SPLASH:
        while True:

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

            pressed_keys = pygame.key.get_pressed()

            if pressed_keys[K_SPACE]:
                break

            screen.blit(world.background, (0, 0))
            font = pygame.font.SysFont("arial", 60, True)

            title = font.render("Heroes of Ancient Legends", True, (0, 255, 255))
            screen.blit(title, (w/2 - title.get_width()/2, 100))
            team1 = font.render(TEAM_NAME[0] + " (blue)", True, (0, 0, 255))
            screen.blit(team1, (w/2 - team1.get_width()/2, 200))
            vs = font.render("vs.", True, (0, 255, 255))
            screen.blit(vs, (w/2 - vs.get_width()/2, 300))
            team2 = font.render(TEAM_NAME[1] + " (red)", True, (255, 0, 0))
            screen.blit(team2, (w/2 - team2.get_width()/2, 400))

            pygame.display.update()

    clock = pygame.time.Clock()
    # print(world)
    while True:

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

            if pygame.mouse.get_pressed()[0]:
                print(pygame.mouse.get_pos())

        # check for end of game
        if not world.game_end:
            time_passed = clock.tick(30)
            world.process(time_passed)

        world.render(screen)
        
        pygame.display.update()
from constantes import *
from Base import *
from algo import *

base = Base()
#base.destroy()
#base.init()
cursor = base.db.cursor()

#for a in SPORTS:
#cursor.execute("SELECT sport.name, pack.name FROM sport INNER JOIN pack WHERE sport.name LIKE ?",(a,))
#cursor.execute("SELECT sport.name, pack.name FROM sport INNER JOIN pack WHERE pack.id = sport.id_pack AND sport.name LIKE ?",(a,))
#cursor.execute("SELECT pack.name FROM sport INNER JOIN pack WHERE sport.name LIKE ?",(a,))
#for row in cursor:
#row = cursor.fetchall()
#print a,'  ->  ',row

#cursor.execute("SELECT * FROM user")
#for row in cursor: print row


def printAlpha(base, id1, id2):
    cursor.execute("SELECT * FROM user WHERE id = ?", (id1, ))
    for row in cursor:
        print row
    cursor.execute("SELECT * FROM user WHERE id = ?", (id2, ))
    for row in cursor:
        print row

    print '\n--tour id1:', id1
    cursor.execute(
Пример #28
0
def main(genomes, config):
    global GEN
    GEN += 1

    nets = []
    ge = []
    birds = []

    for _, g in genomes:
        net = neat.nn.FeedForwardNetwork.create(g, config)
        nets.append(net)
        birds.append(Bird(230, 350))
        g.fitness = 0
        ge.append(g)

    base = Base(BASE_LVL)
    pipes = [Pipe(WIN_WIDTH)]
    win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
    clock = pygame.time.Clock()

    score = 0
    run = True
    while run:
        clock.tick(45)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run == False
                pygame.quit()
                quit()
            # if event.type == pygame.KEYDOWN:
            #     if event.key == pygame.K_SPACE:
            #         bird.jump()

        pipe_ind = 0
        if len(birds) > 0:
            if len(pipes) > 1 and birds[
                    0].x > pipes[0].x + pipes[0].PIPE_TOP.get_width():
                pipe_ind = 1
        else:
            run = False
            break

        for x, bird in enumerate(birds):
            bird.move()
            ge[x].fitness += 0.1

            output = nets[x].activate(
                (bird.y, abs(bird.y - pipes[pipe_ind].height),
                 abs(bird.y - pipes[pipe_ind].bottom)))

            if output[0] > 0.5:
                bird.jump()

        rem = []
        add_pipe = False
        for pipe in pipes:
            for x, bird in enumerate(birds):
                if pipe.collide(bird):
                    ge[x].fitness -= 1
                    birds.pop(x)
                    nets.pop(x)
                    ge.pop(x)

                if not pipe.passed and pipe.x < bird.x:
                    pipe.passed = True
                    add_pipe = True

            if pipe.x + pipe.PIPE_TOP.get_width() < 0:
                rem.append(pipe)

            pipe.move()

        if add_pipe:
            score += 1
            for g in ge:
                g.fitness += 5
            pipes.append(Pipe(WIN_WIDTH))

        for r in rem:
            pipes.remove(r)

        for x, bird in enumerate(birds):
            if bird.y + bird.img.get_height() >= BASE_LVL or bird.y < 0:
                birds.pop(x)
                nets.pop(x)
                ge.pop(x)

        base.move()
        draw_window(win, birds, pipes, base, score, GEN)
from controller import Robot, Supervisor, Field, Node
from Arm import *
from Gripper import *
from Base import *
import numpy as np

import math

robot = Supervisor()
timestep = int(robot.getBasicTimeStep())

# Initialize the base, arm and gripper of the youbot robot
base = Base(robot)
arm = Arm(robot)
gripper = Gripper(robot)

# Enable compass/gps modules
compass = robot.getDevice('compass')
compass.enable(timestep)
gps = robot.getDevice('gps')
gps.enable(timestep)

# Initialize waypoints and state machine initial state
waypoints = [(22.26, 24.61), (22.2, 24.6), (22.03, 26.06), (26.0, 26.4),
             (28.7, 25.0)]  #(25.5, 25.0),
current_waypoint = waypoints.pop(0)
state = 'lower arm'

# Establish the gains for feedback controls
x_gain = 1.5
theta_gain = 2.0
Пример #30
0
 def __init__(self):
     self.base = Base()
     self.base.step_left(174)
     self.cap = cv2.VideoCapture(0)