예제 #1
0
파일: test.py 프로젝트: yabb85/hexagone
def convert_pixel_to_coord(position):
    """docstring for convert_pixel_to_coord"""
    hexa = Hexagon((0, 0), SIZE, RED, BORDER)
    x_coord = (position[0] - MARGIN) / (hexa.get_radius() * 1.5)
    y_coord = (position[1] - MARGIN + x_coord + hexa.get_apothem()) / \
        (hexa.get_radius() * 2)
    return (x_coord, y_coord)
예제 #2
0
파일: test.py 프로젝트: yabb85/hexagone
def convert_coord_to_pixel(coord):
    """docstring for convert_coord_to_pixel"""
    hexa = Hexagon((0, 0), SIZE, RED, BORDER)
    y_pos = MARGIN + coord[1] * hexa.get_apothem() * 2 - coord[0] * \
        hexa.get_apothem()
    x_pos = MARGIN + coord[0] * hexa.get_radius() * 1.5
    return (x_pos, y_pos)
예제 #3
0
    def get_clicked_hex(self, x, y):
        for hex in Hexagon.get_all_hexagons():
            if hex.is_pathable():
                hex.clear_select_color()

        x = int(x)
        y = int(y)
        c_hex_obj = controller_lib.Controller_get_clicked_hex(c_int(x), c_int(y))
        return Hexagon.get_hexagon(c_hex_obj)
예제 #4
0
    def get_clicked_hex(self, x, y):
        for hex in Hexagon.get_all_hexagons():
            if hex.is_pathable():
                hex.clear_select_color()

        x = int(x)
        y = int(y)
        c_hex_obj = controller_lib.Controller_get_clicked_hex(
            c_int(x), c_int(y))
        return Hexagon.get_hexagon(c_hex_obj)
예제 #5
0
def generate_court(size=50,
                   col_rows=10,
                   col_cols=17,
                   start_posx=0,
                   start_posy=0):
    hexes = Group()
    id, x = 0, 0
    posy = start_posy
    posx = start_posx
    for j in range(col_cols):
        posx += size // 1.45
        y = 0
        for i in range(col_rows):
            posy += size // 1.24
            hexes.add(
                Hexagon(posx=posx,
                        posy=posy,
                        id_and_pos=(id, x, y),
                        width=size,
                        height=size))
            x += 2
            y += 1
        id += 1
        if posy == size // 1.24 * col_rows + start_posy:
            posy = size // 2.4 + start_posy
            x = 1
        elif posy == size // 1.24 * col_rows + size // 2.4 + start_posy:
            posy = start_posy
            x = 0
    return hexes
예제 #6
0
class TestHexagon(unittest.TestCase):
    def setUp(self):
        self.hexagon = Hexagon(10, 11, 12, 13, 14, 15)

    # Return sum of perimeter
    def test_calculate_perimeter(self):
        self.assertEqual(75, self.hexagon.calculate_perimeter())
예제 #7
0
    def set_destination(self, dest_hex):
        from hexagon import Hexagon

        start_hex = self.get_base_hex()

        # self.curr_path = a_star(start_hex, dest_hex)
        self.curr_path = Hexagon.find_path(start_hex, dest_hex)
예제 #8
0
    def set_destination(self, dest_hex):
        from hexagon import Hexagon

        start_hex = self.get_base_hex()

        # self.curr_path = a_star(start_hex, dest_hex)
        self.curr_path = Hexagon.find_path(start_hex, dest_hex)
예제 #9
0
class TestHexagon(unittest.TestCase):
    """
    Test Hexagon class
    """
    def setUp(self):
        """intialize the environment for all tests"""
        self.hexagon = Hexagon((0, 0), 50, sf.Color(127, 127, 127),
                               sf.Color(127, 127, 127))

    def test_radius(self):
        """test the radius value of hexagon"""
        radius = self.hexagon.get_radius()
        self.assertEqual(radius, 50)

    def test_apothem(self):
        """test the apothem value of hexagon"""
        apothem = self.hexagon.get_apothem()
        self.assertAlmostEqual(apothem, 43.301270189)
예제 #10
0
 def make_hexagon(self, x, y, radius, phase=math.pi / 2):
     """Create an hexagon given its position in pixels and its radius."""
     points = []
     for a in range(6):
         points.append(
             (
                 int(x + radius * math.cos(a * 60 * math.pi / 180 + phase)),
                 int(y + radius * math.sin(a * 60 * math.pi / 180 + phase)),
             )
         )
     return Hexagon(points)
예제 #11
0
 def gen_grid(self):
     grid = []
     for x in range(-self.rad, self.rad + 1):
         for y in range(-self.rad, self.rad + 1):
             for z in range(-self.rad, self.rad + 1):
                 if (x + y + z == 0):
                     hexagon = Hexagon(self.myCanvas,
                                       x,
                                       y,
                                       z,
                                       size=self.size,
                                       rot=self.rot)
                     grid.append(hexagon)
     print("foo")
     return (grid)
예제 #12
0
    def link_segments(self):
        for i in range(GlobalConsts.BOARD_WIDTH):
            offset = self.get_neighbor_offset(i)

            for j in range(GlobalConsts.BOARD_HEIGHT):
                neighbor_dict = {}
                curr_hex = self.get_hexagon(i, j)

                for pos, (i_offset, j_offset) in offset.iteritems():
                    new_seg_i = i + i_offset
                    new_seg_j = j + j_offset

                    neighbor_hex = self.get_hexagon(new_seg_i, new_seg_j)

                    assert neighbor_hex not in neighbor_dict.values()
                    neighbor_dict[pos] = neighbor_hex

                curr_hex.set_neighbors(neighbor_dict)

        for curr_hex in Hexagon.get_all_hexagons():
            curr_hex.link_verticies()
예제 #13
0
    def link_segments(self):
        for i in range(GlobalConsts.BOARD_WIDTH):
            offset = self.get_neighbor_offset(i)

            for j in range(GlobalConsts.BOARD_HEIGHT):
                neighbor_dict = {}
                curr_hex = self.get_hexagon(i, j)

                for pos, (i_offset, j_offset) in offset.iteritems():
                    new_seg_i = i + i_offset
                    new_seg_j = j + j_offset

                    neighbor_hex = self.get_hexagon(new_seg_i, new_seg_j)

                    assert neighbor_hex not in neighbor_dict.values()
                    neighbor_dict[pos] = neighbor_hex

                curr_hex.set_neighbors(neighbor_dict)

        for curr_hex in Hexagon.get_all_hexagons():
            curr_hex.link_verticies()
예제 #14
0
    def generate(start_seg, stop_seg):#, distance, height_range=(0, 2)):
        from hexagon import Hexagon

        # for curr_seg in a_star(start_seg, stop_seg):
        for curr_seg in Hexagon.find_path(start_seg, stop_seg):
            curr_seg.set_improvement('road', True)
예제 #15
0
class HexagonTest(unittest.TestCase):
    def setUp(self):
        path = tempfile.mktemp('.ldb')
        db = leveldb.LevelDB(path)
        self.triangle = Hexagon(db)

    def test_it_exists(self):
        self.assertTrue(self.triangle)

    def test_insertion(self):
        wb = mock.Mock()
        self.triangle.db = mock.Mock()
        with mock.patch('hexagon.core.leveldb.WriteBatch', return_value=wb):
            self.triangle.insert(s='Daniel', p='loves', o='Cheese')
            self.assertEqual(
                sorted(i[0][0] for i in wb.Put.call_args_list),
                sorted([
                    'spo::Daniel::loves::Cheese', 'sop::Daniel::Cheese::loves',
                    'pso::loves::Daniel::Cheese', 'pos::loves::Cheese::Daniel',
                    'osp::Cheese::Daniel::loves', 'ops::Cheese::loves::Daniel'
                ]))

    def test_retreival(self):
        self.triangle.insert(s='Daniel', p='loves', o='Cheese')
        self.triangle.insert(s='Daniel', p='loves', o='Sushi')
        self.assertEqual(set(self.triangle.start(s='Daniel')),
                         {('Daniel', 'loves', 'Cheese'),
                          ('Daniel', 'loves', 'Sushi')})
        self.assertEqual(set(self.triangle.start(o='Sushi')),
                         {('Daniel', 'loves', 'Sushi')})

    def test_retreival_2(self):
        self.triangle.insert(s='Daniel', p='loves', o='Cheese')
        self.triangle.insert(s='Daniel', p='loves', o='Sushi')
        self.assertEqual(
            set(self.triangle.start(s='Daniel').traverse(o='Cheese')), {
                ('Daniel', 'loves', 'Cheese'),
            })

    def test_batch_insert(self):
        with self.triangle.batch_insert() as f:
            f.insert(s='Daniel', p='loves', o='Cheese')
            f.insert(s='Daniel', p='loves', o='Sushi')
        self.assertEqual(set(self.triangle.start(s='Daniel')),
                         {('Daniel', 'loves', 'Cheese'),
                          ('Daniel', 'loves', 'Sushi')})

    def test_exception_rolls_back(self):
        try:
            with self.triangle.batch_insert() as f:
                f.insert(s='Daniel', p='loves', o='Cheese')
                f.insert(s='Daniel', p='loves', o='Sushi')
                0 / 0
        except ZeroDivisionError:
            pass
        self.assertEqual(len(set(self.triangle.start(s='Daniel'))), 0)

    def test_graph_of_the_gods(self):
        path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                            'data/graph_of_the_gods.json')
        with open(path) as f:
            graph = json.loads(f.read())

            vertex_map = {}
            for v in graph['node']:
                vertex_map[v['-id']] = v['data'][1]['#text'] + ':' + v['data'][
                    0]['#text']

            with self.triangle.batch_insert() as h:
                for e in graph['edge']:
                    s = vertex_map[e['-source']]
                    o = vertex_map[e['-target']]
                    p = e['-label']
                    h.insert(s=s, p=p, o=o)

        # Where do gods live?
        self.assertEqual(
            sorted(list(self.triangle.start(s='god').traverse(p='lives'))),
            sorted([('god:jupiter', 'lives', 'location:sky'),
                    ('god:neptune', 'lives', 'location:sea'),
                    ('god:pluto', 'lives', 'location:tartarus')]))

        # Usually gods live in the sky
        self.assertEqual(
            list(
                self.triangle.start(s='god').traverse(p='lives').traverse(
                    o='location:sky')),
            [('god:jupiter', 'lives', 'location:sky')])

        result = (vs(self.triangle.start(s='demigod')) & vs(
            self.triangle.start(p='mother').traverse(o='human:alcmene')))
        self.assertEqual(result, {'demigod:hercules'})
예제 #16
0
파일: test.py 프로젝트: PirosB3/Hexagon
 def setUp(self):
     path = tempfile.mktemp('.ldb')
     db = leveldb.LevelDB(path)
     self.triangle = Hexagon(db)
예제 #17
0
 def setUp(self):
     path = tempfile.mktemp('.ldb')
     db = leveldb.LevelDB(path)
     self.triangle = Hexagon(db)
예제 #18
0
                    _openings = list(
                        map(lambda x: str(int(x) + 1),
                            row['Openings'].strip().split(',')))
                except Exception as e:
                    import ipdb
                    ipdb.set_trace(context=5)
                    print(e)
            else:
                _openings = row['Openings'].strip().split(',')

            _new_hex = Hexagon(
                id=_hexagon_id,
                spreadsheet_row=row_id + 2,
                center=row['Center'].strip(),
                openings=_openings,
                link1=row['Link1'].strip(),
                link2=row['Link2'].strip(),
                link3=row['Link3'].strip(),
                link4=row['Link4'].strip(),
                link5=row['Link5'].strip(),
                link6=row['Link6'].strip(),
            )
            if _dup_hash.get(_new_hex.get_hash(), False):
                continue
            _dup_hash[_new_hex.get_hash()] = True

            _hexagons.append(_new_hex)
            for _missing_link_num in _hexagons[-1].get_available_links():
                _link_name = convert_num_to_link_name(_missing_link_num)
                _hexagon_missing_links[_link_name].append(_hexagon_id)

            _hexagon_id += 1
예제 #19
0
파일: test.py 프로젝트: PirosB3/Hexagon
class HexagonTest(unittest.TestCase):

    def setUp(self):
        path = tempfile.mktemp('.ldb')
        db = leveldb.LevelDB(path)
        self.triangle = Hexagon(db)

    def test_it_exists(self):
        self.assertTrue(self.triangle)

    def test_insertion(self):
        wb = mock.Mock()
        self.triangle.db = mock.Mock()
        with mock.patch('hexagon.core.leveldb.WriteBatch', return_value=wb):
            self.triangle.insert(s='Daniel', p='loves', o='Cheese')
            self.assertEqual(
                sorted(i[0][0] for i in wb.Put.call_args_list),
                sorted(['spo::Daniel::loves::Cheese',
                        'sop::Daniel::Cheese::loves',
                        'pso::loves::Daniel::Cheese',
                        'pos::loves::Cheese::Daniel',
                        'osp::Cheese::Daniel::loves',
                        'ops::Cheese::loves::Daniel'])
            )

    def test_retreival(self):
        self.triangle.insert(s='Daniel', p='loves', o='Cheese')
        self.triangle.insert(s='Daniel', p='loves', o='Sushi')
        self.assertEqual(set(self.triangle.start(s='Daniel')), {
            ('Daniel', 'loves', 'Cheese'),
            ('Daniel', 'loves', 'Sushi')
        })
        self.assertEqual(set(self.triangle.start(o='Sushi')), {
            ('Daniel', 'loves', 'Sushi')
        })

    def test_retreival_2(self):
        self.triangle.insert(s='Daniel', p='loves', o='Cheese')
        self.triangle.insert(s='Daniel', p='loves', o='Sushi')
        self.assertEqual(set(self.triangle.start(s='Daniel').traverse(o='Cheese')), {
            ('Daniel', 'loves', 'Cheese'),
        })

    def test_batch_insert(self):
        with self.triangle.batch_insert() as f:
            f.insert(s='Daniel', p='loves', o='Cheese')
            f.insert(s='Daniel', p='loves', o='Sushi')
        self.assertEqual(set(self.triangle.start(s='Daniel')), {
            ('Daniel', 'loves', 'Cheese'),
            ('Daniel', 'loves', 'Sushi')
        })

    def test_exception_rolls_back(self):
        try:
            with self.triangle.batch_insert() as f:
                f.insert(s='Daniel', p='loves', o='Cheese')
                f.insert(s='Daniel', p='loves', o='Sushi')
                0/0
        except ZeroDivisionError:
            pass
        self.assertEqual(len(set(self.triangle.start(s='Daniel'))), 0)

    def test_graph_of_the_gods(self):
        path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            'data/graph_of_the_gods.json'
        )
        with open(path) as f:
            graph = json.loads(f.read())

            vertex_map = {}
            for v in graph['node']:
                vertex_map[v['-id']] = v['data'][1]['#text'] + ':' + v['data'][0]['#text']

            with self.triangle.batch_insert() as h:
                for e in graph['edge']:
                    s = vertex_map[e['-source']]
                    o = vertex_map[e['-target']]
                    p = e['-label']
                    h.insert(s=s, p=p, o=o)

        # Where do gods live?
        self.assertEqual(
            sorted(list(self.triangle.start(s='god').traverse(p='lives'))),
            sorted([('god:jupiter', 'lives', 'location:sky'),
                   ('god:neptune', 'lives', 'location:sea'),
                   ('god:pluto', 'lives', 'location:tartarus')])
        )

        # Usually gods live in the sky
        self.assertEqual(
            list(self.triangle.start(s='god').traverse(p='lives').traverse(o='location:sky')),
            [('god:jupiter', 'lives', 'location:sky')]
        )

        result = (
            vs(self.triangle.start(s='demigod')) &
            vs(self.triangle.start(p='mother').traverse(o='human:alcmene'))
        )
        self.assertEqual(result, {'demigod:hercules'})
예제 #20
0
    def generate(start_seg, stop_seg):  #, distance, height_range=(0, 2)):
        from hexagon import Hexagon

        # for curr_seg in a_star(start_seg, stop_seg):
        for curr_seg in Hexagon.find_path(start_seg, stop_seg):
            curr_seg.set_improvement('road', True)
예제 #21
0
    def __init__(self,
                 robot_id,
                 hex_internal_list,
                 hex_external_list,
                 ball,
                 hist_curve,
                 np_file='/tmp/magnetic_ground_truth.np',
                 height=40,
                 battery=99999,
                 debug=True):
        self.robot_id = robot_id
        self.debug = debug
        self.status = 'GOING_TO_NEXT_HEX'
        self.hex_index = 0
        self.base_battery = battery
        self.battery = self.base_battery

        self.movement_mode = 0
        self.max_delta = 10
        self.step_p = 0.6  # 0.06
        self.ball = ball

        self.np_file = np_file
        np_mat = np.loadtxt(self.np_file)
        np_mat *= 255.0 / np_mat.max()
        self.np_mat = np_mat

        self.height = height

        self.hex_external_list = hex_external_list
        self.hex_polygon = dict()

        for key in hex_internal_list.keys():
            hex_obj = Hexagon(hex_internal_list[key],
                              external_points=self.hex_external_list[key])
            self.hex_polygon[key] = hex_obj

        self.hex_internal_list = hex_internal_list

        self.hist_curve = hist_curve
        self.last_position = [ball.y, ball.x, ball.z]

        self.print_message("Starting pos: {0} {1} {2}".format(
            ball.x, ball.y, ball.z))

        self.home_position = self.last_position
        self.home_route = []
        self.return_to_route = []

        self.history = []
        self.wp_index = 0

        # Define first route to reach hexagon
        next_wp = self.hex_internal_list[self.hex_index][self.wp_index]
        go_next_wp = math_helper.get_line_points(self.last_position,
                                                 next_wp,
                                                 step=20)
        go_next_wp_3d = math_helper.get_3d_coverage_points(go_next_wp,
                                                           self.height,
                                                           self.np_file,
                                                           np_mat=self.np_mat)
        self.next_hexagon_route = go_next_wp_3d
        pass
예제 #22
0
 def get_base_hex(self):
     from hexagon import Hexagon
     hex_ptr = board_object_lib.BoardObject_get_base_hex(self._c_pointer)
     return Hexagon.get_hexagon(hex_ptr)
예제 #23
0
 def setUp(self):
     self.hexagon = Hexagon(10, 11, 12, 13, 14, 15)
예제 #24
0
 def get_hexagon(self, i, j):
     curr_c_hex = controller_lib.Controller_get_hexagon(c_int(i), c_int(j))
     return Hexagon.get_hexagon(curr_c_hex)
예제 #25
0
 def setUp(self):
     """intialize the environment for all tests"""
     self.hexagon = Hexagon((0, 0), 50, sf.Color(127, 127, 127),
                            sf.Color(127, 127, 127))
예제 #26
0
 def get_hexagon(self, i, j):
     curr_c_hex = controller_lib.Controller_get_hexagon(c_int(i), c_int(j))
     return Hexagon.get_hexagon(curr_c_hex)
예제 #27
0
    def init_board(self):
        from player_input import PlayerInput
        self.player_input = PlayerInput()
        controller_lib.Controller_set_player_input(
            self.player_input._c_pointer)

        self.zoom = GlobalConsts.START_ZOOM
        self.rotation = GlobalConsts.START_ROTATION
        self.view_range = GlobalConsts.BOARD_WIDTH

        print 'Creating Board...'
        for j in range(GlobalConsts.BOARD_HEIGHT):
            for i in range(GlobalConsts.BOARD_WIDTH):
                x = i * 1.5
                y = j if not i % 2 else j + 0.5

                curr_hex = Hexagon(x * GlobalConsts.COS_60,
                                   y * GlobalConsts.SIN_60)

                controller_lib.Controller_push_hexagon(curr_hex._c_pointer)

        print "Linking Segments..."
        self.link_segments()

        if GlobalConsts.GENERATE_HILLS:
            print 'Generating hills',
            for i in range(int(20 * (GlobalConsts.BOARD_WIDTH / 100.0))):
                print '.',
                x_start = int(random() * GlobalConsts.BOARD_WIDTH)
                y_start = int(random() * GlobalConsts.BOARD_WIDTH)
                RollingHillsGen.generate(self.get_hexagon(x_start, y_start),
                                         750 *
                                         (GlobalConsts.BOARD_WIDTH / 100.0),
                                         height_range=(0, 0.015))
                RollingHillsGen.generate(self.get_hexagon(x_start, y_start),
                                         750 *
                                         (GlobalConsts.BOARD_WIDTH / 100.0),
                                         height_range=(0, -0.0225))
            print

        if GlobalConsts.GENERATE_MOUNTAINS:
            print 'Generating mountains',
            for i in range(int(7 * (GlobalConsts.BOARD_WIDTH / 100.0))):
                print '.',
                x_start = int(random() * GlobalConsts.BOARD_WIDTH)
                y_start = int(random() * GlobalConsts.BOARD_WIDTH)
                MountainRangeGen.generate(
                    self.get_hexagon(x_start, y_start),
                    Hexagon.NEIGHBOR_DIRECTION[int(
                        random() * len(Hexagon.NEIGHBOR_DIRECTION))],
                    60 * (GlobalConsts.BOARD_WIDTH / 100.0),
                    2,
                    height_range=(0.25, 1.0))
            print

        road_hexagons = []
        for i in range(3):
            while True:
                curr_hex = self.get_hexagon(
                    int(random() * GlobalConsts.BOARD_WIDTH),
                    int(random() * GlobalConsts.BOARD_HEIGHT))
                if curr_hex.is_pathable():
                    road_hexagons.append(curr_hex)
                    break

        RoadGen.generate(road_hexagons[0], road_hexagons[1])
        RoadGen.generate(road_hexagons[1], road_hexagons[2])
        RoadGen.generate(road_hexagons[2], road_hexagons[0])

        from timeit import Timer
        from functools import partial

        def get_execution_time(function, *args, **kwargs):
            """Return the execution time of a function in seconds."""
            numberOfExecTime = kwargs.pop('numberOfExecTime', 20)
            return Timer(partial(function, *args,
                                 **kwargs)).timeit(numberOfExecTime)

        from util import a_star
        # return a_star(hex_a, hex_b)

        for i in range(3):
            print 'cpp:', get_execution_time(Hexagon.find_path,
                                             road_hexagons[i - 1],
                                             road_hexagons[i])
            print 'pyc:', get_execution_time(a_star, road_hexagons[i - 1],
                                             road_hexagons[i])
            print '---'

        # while True:
        #     curr_hex = self.get_hexagon(int(random() * GlobalConsts.BOARD_WIDTH), int(random() * GlobalConsts.BOARD_HEIGHT))
        #     if curr_hex.is_pathable():
        #         break

        # # print 'dist: ', dist_between(curr_hex, curr_hex.get_neighbor('N').get_neighbor('N')), 'should be 2'
        # # print 'dist: ', dist_between(curr_hex, curr_hex.get_neighbor('S').get_neighbor('S')), 'should be 2'
        # # print 'dist: ', dist_between(curr_hex, curr_hex.get_neighbor('S').get_neighbor('S').get_neighbor('SE').get_neighbor('SE')), 'should be 3ish'

        # RoadGen.generate(
        #     curr_hex, curr_hex.get_neighbor('N').get_neighbor('N')
        # )

        # Hexagon.find_path(curr_hex, curr_hex.get_neighbor('N').get_neighbor('N'))

        # from util import dist_between
        # print dist_between(road_hexagons[0], road_hexagons[0].get_neighbor('N'))
        # print 1 / dist_between(road_hexagons[0], road_hexagons[0].get_neighbor('S'))
        # print dist_between(road_hexagons[0], road_hexagons[0].get_neighbor('NW'))

        height_list = [hex.get_height() for hex in Hexagon.get_all_hexagons()]

        max_height = max(height_list)
        min_height = min(height_list)

        if max_height and min_height:
            for hex in Hexagon.get_all_hexagons():
                height = hex.get_height()

                if height > 0.0:
                    height_percent = (height / max_height)

                    if height_percent < 0.5:
                        curr_percent = height_percent * 2.0

                        red = curr_percent * 0.7
                        green = 0.5 + curr_percent * 0.2
                        blue = curr_percent * 0.7
                    else:
                        curr_percent = (height_percent - 0.5) * 2.0

                        red = 0.7 + curr_percent * 0.3
                        green = 0.7 + curr_percent * 0.3
                        blue = 0.7 + curr_percent * 0.3
                else:
                    height_percent = abs(height / min_height)

                    if height_percent < 0.5:
                        curr_percent = height_percent * 2.0

                        red = curr_percent * 0.3
                        green = 0.5 - curr_percent * 0.5
                        blue = 0
                    else:
                        curr_percent = (height_percent - 0.5) * 2.0

                        red = 0.3 + curr_percent * 0.7
                        green = 0
                        blue = 0

                hex.set_hex_color(red, green, blue)
        else:
            for hex in Hexagon.get_all_hexagons():
                hex.set_hex_color(0, 0.5, 0)

        img_list = [
            'media/test_a.png',
            'media/test_b.png',
        ]

        for i in range(1):
            while True:
                curr_hex = self.get_hexagon(
                    int(random() * GlobalConsts.BOARD_WIDTH),
                    int(random() * GlobalConsts.BOARD_HEIGHT))
                if curr_hex.is_pathable():
                    board_obj = BoardObject(curr_hex, img_list[i])
                    break

        # orig_hex = self.get_hexagon(int(random() * GlobalConsts.BOARD_WIDTH), int(random() * GlobalConsts.BOARD_HEIGHT))
        # for i in range(10):
        #     curr_hex = orig_hex
        #     for j in range(13):
        #         curr_hex.set_select_color(1, 0, 1)
        #         k = 0.0
        #         for neigh_hex in curr_hex.get_neighbors().values():
        #             k += 1.0 / 6.0
        #             neigh_hex.set_select_color(1, k, 0)
        #         curr_hex = curr_hex.get_neighbor("N").get_neighbor("N").get_neighbor("N")

        #     orig_hex = orig_hex.get_neighbor("NE").get_neighbor("SE").get_neighbor("NE").get_neighbor("SE")

        board_obj.set_selected(True)
예제 #28
0
 def get_base_hex(self):
     from hexagon import Hexagon
     hex_ptr = board_object_lib.BoardObject_get_base_hex(self._c_pointer)
     return Hexagon.get_hexagon(hex_ptr)
예제 #29
0
파일: test.py 프로젝트: yabb85/hexagone
def display_units(window, units):
    """
    Display all unit on the map
    :param window:window used to display
    :param units:list of all units
    """
    hexa = Hexagon((100, 100), SIZE, GRAY_127, BORDER)
    texture_mgr = TextureManager()
    for unit in units:
        hexa.set_texture(texture_mgr.get_unit_texture(unit))
        hexa.position = convert_coord_to_pixel(unit.get_position())
        window.draw(hexa)
        if unit.get_selected():
            hexa.set_texture(None)
            hexa.set_color(sf.Color(250, 50, 250, 50))
            window.draw(hexa)
            neighbors = unit.get_neighbors()
            for i in range(len(neighbors)):
                pos = unit.get_position()
                neighbor = (neighbors[i][0] + pos[0], neighbors[i][1] + pos[1])
                hexa.position = convert_coord_to_pixel(neighbor)
                hexa.set_color(sf.Color(0, 0, 250, 50))
                window.draw(hexa)
예제 #30
0
    def init_board(self):
        from player_input import PlayerInput
        self.player_input = PlayerInput()
        controller_lib.Controller_set_player_input(self.player_input._c_pointer)

        self.zoom = GlobalConsts.START_ZOOM
        self.rotation = GlobalConsts.START_ROTATION
        self.view_range = GlobalConsts.BOARD_WIDTH

        print 'Creating Board...'
        for j in range(GlobalConsts.BOARD_HEIGHT):
            for i in range(GlobalConsts.BOARD_WIDTH):
                x = i * 1.5
                y = j if not i%2 else j + 0.5

                curr_hex = Hexagon(x * GlobalConsts.COS_60, y * GlobalConsts.SIN_60)

                controller_lib.Controller_push_hexagon(curr_hex._c_pointer)

        print "Linking Segments..."
        self.link_segments()

        if GlobalConsts.GENERATE_HILLS:
            print 'Generating hills',
            for i in range(int(20 * (GlobalConsts.BOARD_WIDTH / 100.0))):
                print '.',
                x_start = int(random() * GlobalConsts.BOARD_WIDTH)
                y_start = int(random() * GlobalConsts.BOARD_WIDTH)
                RollingHillsGen.generate(self.get_hexagon(x_start, y_start), 750 * (GlobalConsts.BOARD_WIDTH / 100.0), height_range=(0,  0.015))
                RollingHillsGen.generate(self.get_hexagon(x_start, y_start), 750 * (GlobalConsts.BOARD_WIDTH / 100.0), height_range=(0, -0.0225))
            print

        if GlobalConsts.GENERATE_MOUNTAINS:
            print 'Generating mountains',
            for i in range(int(7 * (GlobalConsts.BOARD_WIDTH / 100.0))):
                print '.',
                x_start = int(random() * GlobalConsts.BOARD_WIDTH)
                y_start = int(random() * GlobalConsts.BOARD_WIDTH)
                MountainRangeGen.generate(
                    self.get_hexagon(x_start, y_start),
                    Hexagon.NEIGHBOR_DIRECTION[int(random() * len(Hexagon.NEIGHBOR_DIRECTION))],
                    60 * (GlobalConsts.BOARD_WIDTH / 100.0), 2, height_range=(0.25, 1.0)
                )
            print

        road_hexagons = []
        for i in range(3):
            while True:
                curr_hex = self.get_hexagon(int(random() * GlobalConsts.BOARD_WIDTH), int(random() * GlobalConsts.BOARD_HEIGHT))
                if curr_hex.is_pathable():
                    road_hexagons.append(curr_hex)
                    break

        RoadGen.generate(
            road_hexagons[0], road_hexagons[1]
        )
        RoadGen.generate(
            road_hexagons[1], road_hexagons[2]
        )
        RoadGen.generate(
            road_hexagons[2], road_hexagons[0]
        )


        from timeit import Timer
        from functools import partial

        def get_execution_time(function, *args, **kwargs):
            """Return the execution time of a function in seconds."""
            numberOfExecTime = kwargs.pop('numberOfExecTime', 20)
            return Timer(partial(function, *args, **kwargs)).timeit(numberOfExecTime)

        from util import a_star
        # return a_star(hex_a, hex_b)

        for i in range(3):
            print 'cpp:', get_execution_time(Hexagon.find_path, road_hexagons[i-1], road_hexagons[i])
            print 'pyc:', get_execution_time(a_star, road_hexagons[i-1], road_hexagons[i])
            print '---'

        # while True:
        #     curr_hex = self.get_hexagon(int(random() * GlobalConsts.BOARD_WIDTH), int(random() * GlobalConsts.BOARD_HEIGHT))
        #     if curr_hex.is_pathable():
        #         break

        # # print 'dist: ', dist_between(curr_hex, curr_hex.get_neighbor('N').get_neighbor('N')), 'should be 2'
        # # print 'dist: ', dist_between(curr_hex, curr_hex.get_neighbor('S').get_neighbor('S')), 'should be 2'
        # # print 'dist: ', dist_between(curr_hex, curr_hex.get_neighbor('S').get_neighbor('S').get_neighbor('SE').get_neighbor('SE')), 'should be 3ish'

        # RoadGen.generate(
        #     curr_hex, curr_hex.get_neighbor('N').get_neighbor('N')
        # )

        # Hexagon.find_path(curr_hex, curr_hex.get_neighbor('N').get_neighbor('N'))

        # from util import dist_between
        # print dist_between(road_hexagons[0], road_hexagons[0].get_neighbor('N'))
        # print 1 / dist_between(road_hexagons[0], road_hexagons[0].get_neighbor('S'))
        # print dist_between(road_hexagons[0], road_hexagons[0].get_neighbor('NW'))

        height_list = [hex.get_height() for hex in Hexagon.get_all_hexagons()]

        max_height = max(height_list)
        min_height = min(height_list)

        if max_height and min_height:
            for hex in Hexagon.get_all_hexagons():
                height = hex.get_height()

                if height > 0.0:
                    height_percent = (height / max_height)

                    if height_percent < 0.5:
                        curr_percent = height_percent * 2.0

                        red     = curr_percent * 0.7
                        green   = 0.5 + curr_percent * 0.2
                        blue    = curr_percent * 0.7
                    else:
                        curr_percent = (height_percent - 0.5) * 2.0

                        red     = 0.7 + curr_percent * 0.3
                        green   = 0.7 + curr_percent * 0.3
                        blue    = 0.7 + curr_percent * 0.3
                else:
                    height_percent = abs(height / min_height)

                    if height_percent < 0.5:
                        curr_percent = height_percent * 2.0

                        red     = curr_percent * 0.3
                        green   = 0.5 - curr_percent * 0.5
                        blue    = 0
                    else:
                        curr_percent = (height_percent - 0.5) * 2.0

                        red     = 0.3 + curr_percent * 0.7
                        green   = 0
                        blue    = 0

                hex.set_hex_color(red, green, blue)
        else:
            for hex in Hexagon.get_all_hexagons():
                hex.set_hex_color(0, 0.5, 0)

        img_list = [
            'media/test_a.png',
            'media/test_b.png',
        ]

        for i in range(1):
            while True:
                curr_hex = self.get_hexagon(int(random() * GlobalConsts.BOARD_WIDTH), int(random() * GlobalConsts.BOARD_HEIGHT))
                if curr_hex.is_pathable():
                    board_obj = BoardObject(curr_hex, img_list[i])
                    break

        # orig_hex = self.get_hexagon(int(random() * GlobalConsts.BOARD_WIDTH), int(random() * GlobalConsts.BOARD_HEIGHT))
        # for i in range(10):
        #     curr_hex = orig_hex
        #     for j in range(13):
        #         curr_hex.set_select_color(1, 0, 1)
        #         k = 0.0
        #         for neigh_hex in curr_hex.get_neighbors().values():
        #             k += 1.0 / 6.0
        #             neigh_hex.set_select_color(1, k, 0)
        #         curr_hex = curr_hex.get_neighbor("N").get_neighbor("N").get_neighbor("N")

        #     orig_hex = orig_hex.get_neighbor("NE").get_neighbor("SE").get_neighbor("NE").get_neighbor("SE")

        board_obj.set_selected(True)