Exemplo n.º 1
0
 def initialize(self):
     rect = Rectangle()
     rect.bottomLeft = self.intersection(self.ray(0, 0))
     rect.topLeft = self.intersection(self.ray(0, self.image['height']))
     rect.topRight = self.intersection(
         self.ray(self.image['width'], self.image['height']))
     rect.bottomRight = self.intersection(self.ray(self.image['width'],
                                                   0.0))
     self.pyramid = Pyramid(self.position, rect)
     self.plane = Plane(rect, self.image)
Exemplo n.º 2
0
 def initialize(self):
     rect = Rectangle()
     rect.bottomLeft = self.intersection(self.ray(0, 0))
     rect.topLeft = self.intersection(self.ray(0, self.image['height']))
     rect.topRight = self.intersection(self.ray(self.image['width'], self.image['height']))
     rect.bottomRight = self.intersection(self.ray(self.image['width'], 0.0))
     self.pyramid = Pyramid(self.position, rect)
     self.plane = Plane(rect, self.image)
Exemplo n.º 3
0
    def __init__(self):
        self.deck = Deck()
        self.pyramid = Pyramid()
        for i in range(28):
            self.pyramid.deck_pyramid.append(self.deck.__next__())

        for card in self.pyramid.deck_pyramid:
            print(card)
        print("-----------")
Exemplo n.º 4
0
class World:
    tiles = defaultdict(lambda: None)
    orders = set()
    resources = set()
    base = Pyramid(9, 9)
    workers = []

    def load(self, filename, world):
        for y, line in enumerate(open(filename, 'r')):
            for x, column in enumerate(line):
                if column not in TileType.__dict__:
                    continue
                t = Tile(getattr(TileType, column), world, x=x, y=y)
                self.tiles[(x, y)] = t

    def neighbors_los(self, p):
        potential_points = [
            (p[0] + 1, p[1]),
            (p[0], p[1] + 1),
            (p[0] - 1, p[1]),
            (p[0], p[1] - 1),
            (p[0] + 1, p[1] + 1),
            (p[0] - 1, p[1] + 1),
            (p[0] - 1, p[1] - 1),
            (p[0] + 1, p[1] - 1),
        ]
        points = []
        for p in potential_points:
            tile = self.tiles[p]
            if not tile:
                continue
            points.append(p)
        return points

    def neighbors(self, p):
        potential_points = [
            (p[0] + 1, p[1]),
            (p[0], p[1] + 1),
            (p[0] - 1, p[1]),
            (p[0], p[1] - 1),
        ]
        points = []
        for p2 in potential_points:
            old_tile = self.tiles[p]
            if old_tile.type in DIGGABLE_TYPES:
                continue
            tile = self.tiles[p2]
            if not tile:
                continue
            if tile.type in WALKABLE_TYPES + DIGGABLE_TYPES:
                points.append(p2)
        return points

    def cost(self, p1, p2):
        t1, t2 = self.tiles[p1], self.tiles[p2]
        return (TILE_COSTS[t1.type] + TILE_COSTS[t2.type]) / 2
Exemplo n.º 5
0
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.card = False
        self._well = Deck(DeckStrategy.invisible, self)
        self._vwell = Deck(DeckStrategy.visible, self)
        self._pyramid = Pyramid(self._well, self)
        p = self.palette()
        p.setColor(self.backgroundRole(), QtGui.QColor(3, 89, 2))
        self.setPalette(p)
        self.__score = 0

        self.score_view = QtWidgets.QLabel("Score: 0", parent=self)
        self.score_view.setGeometry(20, Card.height + 20, 200, 40)
        ps = self.score_view.palette()
        ps.setColor(self.score_view.foregroundRole(),
                    QtGui.QColor(255, 255, 255))
        self.score_view.setPalette(ps)

        self.show()
    def __init__(
            self,
            detector,
            descriptor=None,
            num_features=2000,
            num_levels=4,
            scale_factor=1.2,
            sigma0=1.0,  # N.B.: SIFT use 1.6 for this value
            first_level=0,
            pyramid_type=PyramidType.RESIZE,
            use_block_adaptor=False,
            do_parallel=kPyramidAdaptorUseParallelComputations,
            do_sat_features_per_level=False):
        self.detector = detector
        self.descriptor = descriptor
        self.num_features = num_features
        self.is_detector_equal_to_descriptor = (
            self.detector == self.descriptor)
        self.num_levels = num_levels
        self.scale_factor = scale_factor
        self.inv_scale_factor = 1. / scale_factor
        self.sigma0 = sigma0
        self.first_level = first_level
        self.pyramid_type = pyramid_type
        self.use_block_adaptor = use_block_adaptor
        self.do_parallel = do_parallel  # do parallel computations
        self.do_sat_features_per_level = do_sat_features_per_level  # saturate number of features for each level

        self.pyramid = Pyramid(num_levels=num_levels,
                               scale_factor=scale_factor,
                               sigma0=sigma0,
                               first_level=first_level,
                               pyramid_type=pyramid_type)
        self.initSigmaLevels()

        self.block_adaptor = None
        if self.use_block_adaptor:
            self.block_adaptor = BlockAdaptor(self.detector,
                                              self.descriptor,
                                              row_divs=kAdaptorNumRowDivs,
                                              col_divs=kAdaptorNumColDivs,
                                              do_parallel=False)
Exemplo n.º 7
0
class GaltonBoard():

    __queue = []
    __levels = 0
    #__marbles = 0
    __pyramid = Pyramid

    def __init__(self, levels):
        self.__queue = []
        #   self.__levels = levels
        #   self.__marbles = 0
        self.__pyramid = Pyramid(levels)

    def fill(self, marbles):
        self.__queue = []
        for m in xrange(0, marbles):
            self.__queue.append(self.__pyramid.random_path())
        return self.__queue

    def get_queue(self):
        return self.__queue
Exemplo n.º 8
0
 def __init__(self, levels):
     self.__queue = []
     #   self.__levels = levels
     #   self.__marbles = 0
     self.__pyramid = Pyramid(levels)
Exemplo n.º 9
0
from parse_scene import SceneParser
from pyramid import Pyramid

csv_row = [
    273.805471207, 634.350474966, 5.47014316383, 396.71899049, 769.570813668,
    5.46746117302, 716.12735601, 637.839968735, 4.17549101131, 1602.9590356,
    1386.1706033, 4.93679909159, 132.91424965, 39.6180430965, 4.06897520457,
    1017.61180338, 1280.84238753, 5.30929246675, 519.734389661, 157.465496871,
    4.86189480527, 1052.81750419, 1114.7492892, 5.17453822111, 399.624083354,
    152.848283046, 5.5284601383, 1476.00762606, 168.542917377, 4.41782320434,
    620.176397096, 1378.2212009, 5.20734816895, 1722.59757491, 733.156401685,
    5.18754977088, 1367.73392843, 746.551383153, 4.52141636174
]

scene = SceneParser.parse_csv_row(csv_row).cut_high_magnitudes(5.3)
scene.cartesian_to_spherical()

hip_data = '../data/hip_main.dat'
full_scene = SceneParser.parse_hip_data(hip_data).cut_high_magnitudes(5.3)

p = Pyramid(scene, full_scene)
p.find_match()
class PyramidAdaptor(object):
    def __init__(
            self,
            detector,
            descriptor=None,
            num_features=2000,
            num_levels=4,
            scale_factor=1.2,
            sigma0=1.0,  # N.B.: SIFT use 1.6 for this value
            first_level=0,
            pyramid_type=PyramidType.RESIZE,
            use_block_adaptor=False,
            do_parallel=kPyramidAdaptorUseParallelComputations,
            do_sat_features_per_level=False):
        self.detector = detector
        self.descriptor = descriptor
        self.num_features = num_features
        self.is_detector_equal_to_descriptor = (
            self.detector == self.descriptor)
        self.num_levels = num_levels
        self.scale_factor = scale_factor
        self.inv_scale_factor = 1. / scale_factor
        self.sigma0 = sigma0
        self.first_level = first_level
        self.pyramid_type = pyramid_type
        self.use_block_adaptor = use_block_adaptor
        self.do_parallel = do_parallel  # do parallel computations
        self.do_sat_features_per_level = do_sat_features_per_level  # saturate number of features for each level

        self.pyramid = Pyramid(num_levels=num_levels,
                               scale_factor=scale_factor,
                               sigma0=sigma0,
                               first_level=first_level,
                               pyramid_type=pyramid_type)
        self.initSigmaLevels()

        self.block_adaptor = None
        if self.use_block_adaptor:
            self.block_adaptor = BlockAdaptor(self.detector,
                                              self.descriptor,
                                              row_divs=kAdaptorNumRowDivs,
                                              col_divs=kAdaptorNumColDivs,
                                              do_parallel=False)

    def initSigmaLevels(self):
        num_levels = max(kNumLevelsInitSigma, self.num_levels)
        self.scale_factors = np.zeros(num_levels)
        self.inv_scale_factors = np.zeros(num_levels)
        self.scale_factors[0] = 1.0

        # compute desired number of features per level (by using the scale factor)
        self.num_features_per_level = np.zeros(num_levels, dtype=np.int)
        num_desired_features_per_level = self.num_features * (
            1 - self.inv_scale_factor) / (
                1 - math.pow(self.inv_scale_factor, self.num_levels))
        sum_num_features = 0
        for level in range(self.num_levels - 1):
            self.num_features_per_level[level] = int(
                round(num_desired_features_per_level))
            sum_num_features += self.num_features_per_level[level]
            num_desired_features_per_level *= self.inv_scale_factor
        self.num_features_per_level[self.num_levels - 1] = max(
            self.num_features - sum_num_features, 0)
        #print('num_features_per_level:',self.num_features_per_level)

        if self.first_level == -1:
            self.scale_factors[0] = 1.0 / self.scale_factor
        self.inv_scale_factors[0] = 1.0 / self.scale_factors[0]
        for i in range(1, num_levels):
            self.scale_factors[i] = self.scale_factors[i -
                                                       1] * self.scale_factor
            self.inv_scale_factors[i] = 1.0 / self.scale_factors[i]
        #print('self.inv_scale_factors: ', self.inv_scale_factors)

    # detect on 'unfiltered' pyramid images ('unfiltered' meanining depends on the selected pyramid type)
    def detect(self, frame, mask=None):
        if self.num_levels == 1:
            return self.detector.detect(frame, mask)
        else:
            #TODO: manage mask
            if kVerbose:
                print('PyramidAdaptor #levels:', self.num_levels, '(from',
                      self.first_level, '), scale_factor:', self.scale_factor,
                      ', sigma0:', self.sigma0, ', type:',
                      self.pyramid_type.name)
            self.pyramid.compute(frame)
            kps_all = []  # list are thread-safe

            def detect_level(scale, pyr_cur, i):
                kps = []
                if self.block_adaptor is None:
                    kps = self.detector.detect(pyr_cur)
                else:
                    kps = self.block_adaptor.detect(pyr_cur)
                if kVerbose and False:
                    print("PyramidAdaptor - level", i, ", shape: ",
                          pyr_cur.shape)
                for kp in kps:
                    #print('kp.pt before: ', kp.pt)
                    kp.pt = (kp.pt[0] * scale, kp.pt[1] * scale)
                    kp.size = kp.size * scale
                    kp.octave = i
                    #print('kp: ', kp.pt, kp.octave)
                if self.do_sat_features_per_level:
                    kps, _ = sat_num_features(
                        kps, None,
                        self.num_features_per_level[i])  # experimental
                kps_all.extend(kps)

            if not self.do_parallel:
                #print('sequential computations')
                # process the blocks sequentially
                for i in range(0, self.num_levels):
                    scale = self.scale_factors[i]
                    pyr_cur = self.pyramid.imgs[i]
                    detect_level(scale, pyr_cur, i)
            else:
                #print('parallel computations')
                futures = []
                with ThreadPoolExecutor(max_workers=4) as executor:
                    for i in range(0, self.num_levels):
                        scale = self.scale_factors[i]
                        pyr_cur = self.pyramid.imgs[i]
                        futures.append(
                            executor.submit(detect_level, scale, pyr_cur, i))
                    wait(futures)  # wait all the task are completed

            return np.array(kps_all)

    # detect on 'unfiltered' pyramid images ('unfiltered' meanining depends on the selected pyramid type)
    # compute descriptors on 'filtered' pyramid images ('filtered' meanining depends on the selected pyramid type)
    def detectAndCompute(self, frame, mask=None):
        if self.num_levels == 1:
            return self.detector.detectAndCompute(frame, mask)
        else:
            if kVerbose:
                print('PyramidAdaptor [dc] #levels:', self.num_levels, '(from',
                      self.first_level, '), scale_factor:', self.scale_factor,
                      ', sigma0:', self.sigma0, ', type:',
                      self.pyramid_type.name)
            self.pyramid.compute(frame)
            kps_all = []
            des_all = []
            kps_des_map = {}  # i -> (kps,des)

            def detect_and_compute_level(scale, pyr_cur, pyr_cur_filtered, N,
                                         i):
                kps = []
                if self.block_adaptor is None:
                    #kps, des = self.detector.detectAndCompute(pyr_cur)
                    if self.is_detector_equal_to_descriptor:
                        kps, des = self.detector.detectAndCompute(pyr_cur)
                    else:
                        kps = self.detector.detect(pyr_cur)
                        #print('description of filtered')
                        kps, des = self.descriptor.compute(
                            pyr_cur_filtered, kps)
                else:
                    kps, des = self.block_adaptor.detectAndCompute(pyr_cur)
                if kVerbose and False:
                    print("PyramidAdaptor - level", i, ", shape: ",
                          pyr_cur.shape)
                for kp in kps:
                    #print('before: kp.pt:', kp.pt,', size:',kp.size,', octave:',kp.octave,', angle:',kp.angle)
                    kp.pt = (kp.pt[0] * scale, kp.pt[1] * scale)
                    kp.size = kp.size * scale
                    kp.octave = i
                    #print('after: kp.pt:', kp.pt,', size:',kp.size,', octave:',kp.octave,', angle:',kp.angle)
                if self.do_sat_features_per_level:
                    kps, des = sat_num_features(kps, des, N)  # experimental
                kps_des_map[i] = (kps, des)

            if not self.do_parallel:
                #print('sequential computations')
                # process the blocks sequentially
                for i in range(0, self.num_levels):
                    scale = self.scale_factors[i]
                    pyr_cur = self.pyramid.imgs[i]
                    pyr_cur_filtered = self.pyramid.imgs_filtered[i]
                    detect_and_compute_level(scale, pyr_cur, pyr_cur_filtered,
                                             self.num_features_per_level[i], i)
            else:
                #print('parallel computations')
                futures = []
                with ThreadPoolExecutor(max_workers=4) as executor:
                    for i in range(0, self.num_levels):
                        scale = self.scale_factors[i]
                        pyr_cur = self.pyramid.imgs[i]
                        pyr_cur_filtered = self.pyramid.imgs_filtered[i]
                        futures.append(
                            executor.submit(detect_and_compute_level, scale,
                                            pyr_cur, pyr_cur_filtered,
                                            self.num_features_per_level[i], i))
                    wait(futures)  # wait all the task are completed

            # now merge the computed results
            for i, (kps, des) in kps_des_map.items():
                kps_all.extend(kps)
                if des is not None and len(des) > 0:
                    if len(des_all) > 0:
                        des_all = np.vstack([des_all, des])
                    else:
                        des_all = des
            return np.array(kps_all), np.array(des_all)
Exemplo n.º 11
0
def application(e, start_response):
    db = DB()

    headers = [('Content-Type', 'text/html; charset=utf-8')]
    app_root = urllib.parse.urlunsplit((e['wsgi.url_scheme'], e['HTTP_HOST'], e['SCRIPT_NAME'], '', ''))
    params = urllib.parse.parse_qs(e['QUERY_STRING'])
    path_info = e['PATH_INFO']

    # ----- If user has valid session cookie set session = True --------------------

    session = False
    session_user = None
    cookies = http.cookies.SimpleCookie()
    if 'HTTP_COOKIE' in e:
        cookies.load(e['HTTP_COOKIE'])
        if 'session' in cookies:
            session_user, session_pass = cookies['session'].value.split(':')
            session = db.user_pass_valid(session_user, session_pass)

    # ----- The common start of every page ---------------------------

    page = '''<!DOCTYPE html>
<html><head><title>Game</title>
<style>
    table { border-collapse: collapse; }
    table, th, td { border: 1px solid silver; padding: 2px; }
</style>
</head>
<body>
<h1>Rock-Paper-Scissors</h1>'''

    # ----- For logging in and registering ---------------------------

    if path_info == '/login_register':
        param_do = params['do'][0] if 'do' in params else None
        param_user = params['username'][0] if 'username' in params else None
        param_pass = params['password'][0] if 'password' in params else None

        login_register_form = '''
<form>
    <input type="text" name="username"> Username<br>
    <input type="password" name="password"> Password<br>
    <input type="submit" name="do" value="Login"> or
    <input type="submit" name="do" value="Register">
</form>'''

        if param_do == 'Login' and param_user and param_pass:
            if db.user_pass_valid(param_user, param_pass):
                headers.append(('Set-Cookie', 'session={}:{}'.format(param_user, param_pass)))
                headers.append(('Location', app_root))
                start_response('303 See Other', headers)
                return []
            else:
                start_response('200 OK', headers)
                page += login_register_form
                return [(page + 'Wrong username or password</body></html>').encode()]

        elif param_do == 'Register' and param_user and param_pass:
            if db.add_username(param_user, param_pass):
                headers.append(('Set-Cookie', 'session={}:{}'.format(param_user, param_pass)))
                headers.append(('Location', app_root))
                start_response('303 See Other', headers)
                return []
            else:
                start_response('200 OK', headers)
                page += login_register_form
                return [(page + 'Username {} is taken.</body></html>'.format(param_user)).encode()]

        else:
            start_response('200 OK', headers)
            return [(page + login_register_form + '</body></html>').encode()]

    # ----- Logout --------------------------------------------

    elif path_info == '/logout':
        headers.append(('Set-Cookie', 'session=0; expires=Thu, 01 Jan 1970 00:00:00 GMT'))
        headers.append(('Location', app_root))
        start_response('303 See Other', headers)
        return []

    # ----- Root page -----------------------------------------

    elif path_info == '/' or not path_info:
        if not session:
            start_response('200 OK', headers)
            page += '<a href="{}/login_register">Log in or register</a> to play</body></html>'.format(app_root)
            return [page.encode()]

        page += '{} | <a href="{}/logout">Logout</a>'.format(session_user, app_root)
#       page += ' | <a href="{}">Refresh</a>'.format(app_root)
        page += '<h2>My games</h2>\n'
        page += '<table><tr><th>Game</th><th>Goal</th><th>Quit</th><th>State</th><th>Players</th></tr>\n'
        games = [
            Pyramid(i, p, g, st, ts, t, db.connection) for i, p, g, st, ts, t in db.get_games_by_user(session_user)
            ]
        for game in games:
            page += '<tr><td>{}</td><td>{}</td><td><a href="{}/quit?id={}">quit</a></td>'.format(
                game.id, game.goal, app_root, game.id
            )
            players_scores = ', '.join(
                [
                    '{}{}|{}{}'.format(
                        '' if p['playing'] else '<s>',  # Add open strikethrough tag if player left game
                        p['name'],
                        p['score'],
                        '' if p['playing'] else '</s>'  # Add close strikethrough tag
                    ) for p in game.players
                ]
            )
            if game.state == 0:  # Accepting players
                page += '<td>Awaiting {}</td>'.format(game.num_players - len(game.players))
                page += '<td>' + ', '.join([p['name'] for p in game.players]) + '</td>'
            elif game.state == 2:
                page += '<td><a href="{}/game?id={}">Game over</a></td>'.format(app_root, game.id)
                page += '<td>' + players_scores + '</td>'
            elif game.is_players_turn(session_user):  # Playing, player's turn
                page += '<td><a href="{}/game?id={}">My turn</a></td>'.format(app_root, game.id)
                page += '<td>' + players_scores + '</td>'
            else:  # Playing, not player's turn
                page += '<td><a href="{}/game?id={}">Awaiting Turn</a></td>'.format(app_root, game.id)
                page += '<td>' + players_scores + '</td>'
            page += '</tr>\n'
        page += '</table>'
        page += '<p><a href="{}/newgame">Start a New Game</a></p>'.format(app_root)
        ts1 = max(game.ts for game in games) if games else None

        page += '<h2>Games accepting players</h2>\n'
        page += '<table><tr><th>Game</th><th>Goal</th><th>Join</th><th>State</th><th>Players</th></tr>\n'
        games = [
            Pyramid(i, p, g, 0, ts, t, db.connection)
            for i, p, g, ts, t in db.get_registering_games_by_user(session_user)
            ]
        for game in games:
            page += '<tr><td>{}</td><td>{}</td><td><a href="{}/join?id={}">join</a></td>'.format(
                game.id, game.goal, app_root, game.id
            )
            page += '<td>{} of {} players</td>'.format(len(game.players), game.num_players, game.id)
            page += '<td>' + ', '.join([p['name'] for p in game.players]) + '</td>'
            page += '</tr>\n'
        page += '</table>'
        ts2 = max(game.ts for game in games) if games else None

        page += '''
<script>
    function callback(event) {{
        if (event.target.readyState == 4 && event.target.responseText != '{} {}') {{
            window.location = '{}'
        }}
    }}
    function timeFunc(event) {{
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.addEventListener("readystatechange", callback)
        xmlhttp.open("GET", "{}/updated_games", true)
        xmlhttp.setRequestHeader("Content-Type", "text/plain")
        xmlhttp.send()
    }}
    setInterval(timeFunc, 1000)
</script>'''.format(ts1, ts2, app_root, app_root)

        start_response('200 OK', headers)
        return [(page + '</body></html>').encode()]

    # ----- Check if game list changed -------------------------------------------

    elif path_info == '/updated_games':
        if not session:
            start_response('200 OK', headers)
            return ['No session'.encode()]

        ts1, ts2 = db.updated_games(session_user)

        start_response('200 OK', headers)
        return ['{} {}'.format(ts1, ts2).encode()]

    # ----- Register new game ---------------------------------------------------------------
    # ***** MODIFY THIS PART TO ASK FOR NUMBER OF PLAYERS AND RECEIVE NUMBER OF PLAYERS *****

    elif path_info == '/newgame':
        if not session:
            start_response('200 OK', headers)
            return ['No session'.encode()]

        if 'goal' in params:
            db.new_game(2, params['goal'][0], session_user)
            headers.append(('Location', app_root))
            start_response('303 See Other', headers)
            return []

        page += '''
<h2>Create New Game</h2>
<form>
    <h3>Play until score:</h3>
    <input type="radio" name="goal" value="1">1<br>
    <input type="radio" name="goal" value="3">3<br>
    <input type="radio" name="goal" value="5">5<br>
    <input type="radio" name="goal" value="10" checked>10<br>
    <input type="radio" name="goal" value="20">20<br>
    <input type="radio" name="goal" value="100">100<br>
    <input type="submit" value="Create">
</form>
</body></html>'''

        start_response('200 OK', headers)
        return [page.encode()]

    # ----- Join game -----------------------------------------

    elif path_info == '/join':
        if not session:
            start_response('200 OK', headers)
            return ['No session'.encode()]

        game_id = params['id'][0]
        db.join_game(game_id, session_user)

        headers.append(('Location', app_root))
        start_response('303 See Other', headers)
        return []

    # ----- Quit game -----------------------------------------

    elif path_info == '/quit':
        if not session:
            start_response('200 OK', headers)
            return ['No session'.encode()]

        game_id = params['id'][0]
        db.quit_game(game_id, session_user)

        headers.append(('Location', app_root))
        start_response('303 See Other', headers)
        return []

    # ----- Game ------------------------------------------------------------

    elif path_info == '/game':
        if not session:
            start_response('200 OK', headers)
            return ['No session'.encode()]

        game_id = params['id'][0]

        (players, goal, state, ts, turns) = db.get_game_by_id(game_id)
        game = Pyramid(game_id, players, goal, state, ts, turns, db.connection)
        if game.state == 0:  # Error: cannot view game, it is still registering players
            start_response('200 OK', headers)
            return [(page + 'Still registering players</body></html>').encode()]

        if 'move' in params:  # Player came here by making a move
            game.add_player_move(session_user, params['move'][0])

        page += '<a href="{}">Home</a>'.format(app_root)
#       page += ' | <a href="{}/game?id={}">Refresh</a>'.format(app_root, game_id)
        page += '<h3>Game {} -- Play to {}</h3>'.format(game.id, game.goal)

        if game.state == 2:
            page += '<p>Game over</p>'
        elif game.is_players_turn(session_user):
            page += '<p>Your move: '
            move_template = '<a href="{}/game?id={}&amp;move={}">{}</a>'
            move_links = [
                move_template.format(app_root, game.id, mval, mname) for mval, mname in game.valid_moves(session_user)
                ]
            page += ' | '.join(move_links)
        else:
            page += '<p>Wait for your turn</p>'

        page += '<table>\n<tr><th>&nbsp;</th>'
        for p in game.players:
            page += '<th>{}</th>'.format(p['name']) if p['playing'] else '<th><s>{}</s></th>'.format(p['name'])
        page += '</tr>\n<tr style="background-color: silver"><td>Round</td>'
        for p in game.players:
            page += '<td>{} p</td>'.format(p['score'])
        page += '</tr>\n'

        for index, turn in enumerate(reversed(game.decorated_moves(session_user))):
            page += '<tr><td>{}</td>'.format(len(game.turns) - index)
            for move, winner in turn:
                if winner:
                    page += '<td style="background-color:lightgreen">{}</td>'.format(move)
                else:
                    page += '<td>{}</td>'.format(move)
            page += '</tr>\n'

        page += '</table>'

        if game.state == 1:
            page += '''
<script>
    function callback(event) {{
        if (event.target.readyState == 4 && event.target.responseText != '{}') {{
            window.location = '{}/game?id={}'
        }}
    }}
    function timeFunc(event) {{
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.addEventListener("readystatechange", callback)
        xmlhttp.open("GET", "{}/updated_game?id={}", true)
        xmlhttp.setRequestHeader("Content-Type", "text/plain")
        xmlhttp.send()
    }}
    setInterval(timeFunc, 1000)
</script>'''.format(game.ts, app_root, game.id, app_root, game.id)

        start_response('200 OK', headers)
        return [(page + '</body></html>').encode()]

    # ----- Check if game changed --------------------------------------

    elif path_info == '/updated_game':
        if not session:
            start_response('200 OK', headers)
            return ['No session'.encode()]

        start_response('200 OK', headers)
        p, g, s, ts, t = db.get_game_by_id(params['id'][0])
        return ['{}'.format(ts).encode()]

    # ----- Dump tables ------------------------------------------------

    elif path_info == '/dump':
        users, games, players = db.dump()

        page += '<a href="{}">Home</a>'.format(app_root)
        page += ' | <a href="{}/clear_games">Clear games and players</a>'.format(app_root)
        page += ' | <a href="{}/clear_all">Clear all</a>'.format(app_root)

        page += '<h2>Table "user"</h2>\n'
        page += '<p>Contains all registered users and their passwords.</p>\n'
        page += '<table><tr><th>name</th><th>password</th></tr>\n'
        for name, password in users:
            page += '<tr><td>{}</td><td>{}</td></tr>\n'.format(name, password)
        page += '</table>\n'

        page += '<h2>Table "game"</h2>\n'
        page += '<p>One row for every game.</p>\n'
        page += '<table><tr><th>rowid</th><th>players</th><th>goal</th><th>state</th><th>ts</th><th>turns</th></tr>\n'
        for rowid, numplayers, goal, state, ts, turns in games:
            page += '<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>\n'.format(
                rowid, numplayers, goal, state, ts, turns
            )
        page += '</table>\n'

        page += '<h2>Table "player"</h2>\n'
        page += '<p>Connects players with games. One row for every player in a game.</p>\n'
        page += '<table><tr><th>rowid</th><th>game_id</th><th>user_name</th><th>score</th><th>playing</th></tr>\n'
        for rowid, game_id, user_name, score, playing in players:
            page += '<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>\n'.format(
                rowid, game_id, user_name, score, playing
            )
        page += '</table>\n'

        page += '</body></html>'

        start_response('200 OK', headers)
        return [page.encode()]

    # ----- Clear tables --------------------------------------

    elif path_info == '/clear_games':
        db.clear_tables(False)
        headers.append(('Location', '{}/dump'.format(app_root)))
        start_response('303 See Other', headers)
        return []

    elif path_info == '/clear_all':
        db.clear_tables(True)
        headers.append(('Location', '{}/dump'.format(app_root)))
        start_response('303 See Other', headers)
        return []

    # ----- Unknown web app ----------------------------------------------------------

    else:
        start_response('200 OK', headers)
        return [(page + 'Unknown Web app {}</body></html>'.format(path_info)).encode()]
Exemplo n.º 12
0
class SIFT:
    def __init__(self, debug=True):
        self.pyramid = Pyramid()
        self.debug = debug

    #########################
    # Interfaces
    #########################
    def match(self,
              im1,
              im2,
              draw_matches=True,
              match_filename="matches.jpg",
              use_cv2_keypoints=True,
              use_bilinear_interp=False,
              draw_keypoints=False,
              kp_filename1="kp1.jpg",
              kp_filename2="kp2.jpg",
              descriptors1=None,
              positions1=None,
              descriptors2=None,
              positions2=None):
        if descriptors1 is not None and positions1 is not None:
            dp1, pos1 = descriptors1, positions1
        elif im1 is None:
            raise ValueError, "Empty image 'im1' is given!"
        else:
            self._log("processing img1...")
            dp1, pos1 = self.process(im1,
                                     draw_keypoints=draw_keypoints,
                                     kp_filename=kp_filename1)

        if descriptors2 is not None and positions2 is not None:
            dp2, pos2 = descriptors2, positions2
        elif im2 is None:
            raise ValueError, "Empty image 'im2' is given!"
        else:
            self._log("\nprocessing img2...")
            dp2, pos2 = self.process(im2,
                                     draw_keypoints=draw_keypoints,
                                     kp_filename=kp_filename2)

        self._log("\nmatching...")
        dp_matcher = DescriptorMatcher()
        matches, cnt = dp_matcher(dp1, dp2)
        matches = sorted(matches, key=lambda x: x[2])

        self._log("During %d descriptors matching %d," %
                  (dp1.shape[0], dp2.shape[0]))
        self._log(
            "%d succeed\n%d failed with multiple peaks\n%d failed with too large the distance"
            % tuple(cnt))
        self._log("Matching done.")

        self._log("")
        if draw_matches:
            self.draw_matches(im1,
                              pos1,
                              im2,
                              pos2,
                              matches,
                              filename=match_filename)

        self._log("\nFinished.")

        return self.match_for_human(matches, pos1, pos2)

    def process(self,
                im,
                save_pyramid=False,
                draw_keypoints=False,
                kp_filename="keypoints.jpg",
                use_cv2_keypoints=True,
                use_bilinear_interp=False):

        if im is None:
            raise ValueError, "Empty image is given!"

        if len(im.shape) != 2:
            raise ValueError, "Only gray scale image is acceptable"

        if use_cv2_keypoints:
            kp_finder = CV2KeypointFinder()
        else:
            kp_finder = DoGKeypointFinder()

        dp_calculator = DescriptorCalculator()

        self.pyramid.construct(im)
        self.pyramid.compute_grad()

        # get raw keypoints

        self._log("detecting keypoints...")
        n1, n2 = self.pyramid.find_keypoints(
            kp_finder, n_max_per_layer=para.max_keypoints_per_layer)
        self._log("%d keypoints found, and %d accounting orientations." %
                  (n1, n2))

        self._log("computing descriptors...")
        descriptors, pos = dp_calculator(self.pyramid, use_bilinear_interp)

        self._log("%d x %d descriptors calculation done." % descriptors.shape)

        # save result if need
        if save_pyramid:
            for i, j, im in self.pyramid.enumerate():
                cv2.imwrite(
                    "pyramid/pyramid_octave_{}_img_{}.jpg".format(i, j), im)

        if draw_keypoints:
            kps = self.pyramid.flattened_keypoints
            self.draw_keypoints(im, kps, filename=kp_filename)

        return descriptors, pos

    ##########################
    # Result visualization
    ##########################
    def draw_keypoints(self, im, keypoints, filename="keypoints.jpg"):
        self._log("drawing keypoints into '%s'..." % filename)
        rows, cols = im.shape

        def to_cv2_kp(kp):
            # assert kp = [<row>, <col>, <ori>, <octave_ind>, <layer_ind>]
            ratio = get_size_ratio_by_octave(kp[3])
            scale = get_scale_by_ind(kp[3], kp[4])
            return cv2.KeyPoint(kp[1] / ratio, kp[0] / ratio, 10,
                                kp[2] / PI * 180)

        kp_for_draw = list(map(to_cv2_kp, keypoints))
        im_kp = cv2.drawKeypoints(
            im, kp_for_draw, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
        cv2.imwrite(filename, im_kp)

    def draw_matches(self,
                     im1,
                     pos1,
                     im2,
                     pos2,
                     matches,
                     filename="matches.jpg"):
        self._log("drawing matches into '%s'..." % filename)
        row1, col1 = im1.shape
        row2, col2 = im2.shape

        im_out = np.zeros((max(row1, row2), col1 + col2, 3), dtype=np.uint8)
        im_out[:row1, :col1] = np.dstack([im1] * 3)
        im_out[:row2, col1:] = np.dstack([im2] * 3)

        l = len(matches)

        for ind, (i, j, d) in list(enumerate(matches))[::-1]:
            d /= para.descr_match_threshold  # map to [0, 1]
            _pos1, _pos2 = pos1[i], pos2[j]
            color = hsv_to_rgb(int(d * 120 - 120), 1, 1 - d / 3)
            color = [int(c * 255) for c in color]
            cv2.line(im_out, (_pos1[1], _pos1[0]), (_pos2[1] + col1, _pos2[0]),
                     color, 1)

        cv2.imwrite(filename, im_out)

    ##########################
    # Utility
    ##########################
    @staticmethod
    def match_for_human(matches, pos1, pos2):
        return [(list(pos1[i]), list(pos2[j]), v) for i, j, v in matches]

    def _log(self, info):
        if self.debug:
            print(info)
Exemplo n.º 13
0
import numpy as np

from pyramid import Pyramid, PyramidType

from utils_img import combine_images_horizontally

img = cv2.imread('../data/kitti06-12.png', cv2.IMREAD_COLOR)

pyramid_params = dict(
    num_levels=8,
    scale_factor=1.2,
    sigma0=1.,
    first_level=-1,  # 0: start from image; -1: start from image*scale_factor  
    pyramid_type=PyramidType.RESIZE)

pyramid = Pyramid(**pyramid_params)
print('pyramid_type: ', pyramid.pyramid_type.name)
print('first_level: ', pyramid.first_level)

time_start = time.time()
pyramid.compute(img)
duration = time.time() - time_start
print('duration: ', duration)

for i in range(0, pyramid.num_levels):
    name = 'level ' + str(i) + ':  img  - img_filtered'
    img_pyr = combine_images_horizontally(pyramid.imgs[i],
                                          pyramid.imgs_filtered[i])
    cv2.imshow(name, img_pyr)
    print(name, ' size: ', pyramid.imgs[i].shape)
Exemplo n.º 14
0
            for col, x in enumerate([int(s) for s in line.split(" ")]):
                vals[row_idx][col] = x
            row_idx += 1

    return vals


def make_output(file_path, occur_dict):
    with open(file_path, "w") as fdw:
        for k, v in sorted(occur_dict.items()):
            output_line = "{} | {}\n".format(k, v["n"])
            if v["trails"] is not None:
                output_line += "  TRAILS: {}\n".format(v["trails"])
            fdw.write(output_line)


# for trails mode
# --trails -output res/output_trails.txt

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-input", nargs='?', default="res/input.txt")
    parser.add_argument("-output", nargs='?', default="res/output.txt")
    parser.add_argument("--trails", action='store_true')
    args = parser.parse_args()

    vals = vals_from_file(args.input)
    pyramid = Pyramid(vals)
    pyramid.calc_path_sums(include_trails=args.trails)
    make_output(args.output, pyramid._path_sums)
Exemplo n.º 15
0
def application(e, start_response):
    db = DB()

    headers = [('Content-Type', 'text/html; charset=utf-8')]
    app_root = urllib.parse.urlunsplit(
        (e['wsgi.url_scheme'], e['HTTP_HOST'], e['SCRIPT_NAME'], '', ''))
    params = urllib.parse.parse_qs(e['QUERY_STRING'])
    path_info = e['PATH_INFO']

    # ----- If user has valid session cookie set session = True --------------------

    session = False
    session_user = None
    cookies = http.cookies.SimpleCookie()
    if 'HTTP_COOKIE' in e:
        cookies.load(e['HTTP_COOKIE'])
        if 'session' in cookies:
            session_user, session_pass = cookies['session'].value.split(':')
            session = db.user_pass_valid(session_user, session_pass)

    # ----- The common start of every page ---------------------------

    page = '''<!DOCTYPE html>
<html><head><title>Game</title>
<style>
    table { border-collapse: collapse; }
    table, th, td { border: 1px solid silver; padding: 2px; }
</style>
</head>
<body>
<h1>Rock-Paper-Scissors</h1>'''

    # ----- For logging in and registering ---------------------------

    if path_info == '/login_register':
        param_do = params['do'][0] if 'do' in params else None
        param_user = params['username'][0] if 'username' in params else None
        param_pass = params['password'][0] if 'password' in params else None

        login_register_form = '''
<form>
    <input type="text" name="username"> Username<br>
    <input type="password" name="password"> Password<br>
    <input type="submit" name="do" value="Login"> or
    <input type="submit" name="do" value="Register">
</form>'''

        if param_do == 'Login' and param_user and param_pass:
            if db.user_pass_valid(param_user, param_pass):
                headers.append(('Set-Cookie',
                                'session={}:{}'.format(param_user,
                                                       param_pass)))
                headers.append(('Location', app_root))
                start_response('303 See Other', headers)
                return []
            else:
                start_response('200 OK', headers)
                page += login_register_form
                return [(page +
                         'Wrong username or password</body></html>').encode()]

        elif param_do == 'Register' and param_user and param_pass:
            if db.add_username(param_user, param_pass):
                headers.append(('Set-Cookie',
                                'session={}:{}'.format(param_user,
                                                       param_pass)))
                headers.append(('Location', app_root))
                start_response('303 See Other', headers)
                return []
            else:
                start_response('200 OK', headers)
                page += login_register_form
                return [
                    (page +
                     'Username {} is taken.</body></html>'.format(param_user)
                     ).encode()
                ]

        else:
            start_response('200 OK', headers)
            return [(page + login_register_form + '</body></html>').encode()]

    # ----- Logout --------------------------------------------

    elif path_info == '/logout':
        headers.append(
            ('Set-Cookie', 'session=0; expires=Thu, 01 Jan 1970 00:00:00 GMT'))
        headers.append(('Location', app_root))
        start_response('303 See Other', headers)
        return []

    # ----- Root page -----------------------------------------

    elif path_info == '/' or not path_info:
        if not session:
            start_response('200 OK', headers)
            page += '<a href="{}/login_register">Log in or register</a> to play</body></html>'.format(
                app_root)
            return [page.encode()]

        page += '{} | <a href="{}/logout">Logout</a>'.format(
            session_user, app_root)
        #       page += ' | <a href="{}">Refresh</a>'.format(app_root)
        page += '<h2>My games</h2>\n'
        page += '<table><tr><th>Game</th><th>Goal</th><th>Quit</th><th>State</th><th>Players</th></tr>\n'
        games = [
            Pyramid(i, p, g, st, ts, t, db.connection)
            for i, p, g, st, ts, t in db.get_games_by_user(session_user)
        ]
        for game in games:
            page += '<tr><td>{}</td><td>{}</td><td><a href="{}/quit?id={}">quit</a></td>'.format(
                game.id, game.goal, app_root, game.id)
            players_scores = ', '.join([
                '{}{}|{}{}'.format(
                    '' if p['playing'] else
                    '<s>',  # Add open strikethrough tag if player left game
                    p['name'],
                    p['score'],
                    ''
                    if p['playing'] else '</s>'  # Add close strikethrough tag
                ) for p in game.players
            ])
            if game.state == 0:  # Accepting players
                page += '<td>Awaiting {}</td>'.format(game.num_players -
                                                      len(game.players))
                page += '<td>' + ', '.join([p['name']
                                            for p in game.players]) + '</td>'
            elif game.state == 2:
                page += '<td><a href="{}/game?id={}">Game over</a></td>'.format(
                    app_root, game.id)
                page += '<td>' + players_scores + '</td>'
            elif game.is_players_turn(session_user):  # Playing, player's turn
                page += '<td><a href="{}/game?id={}">My turn</a></td>'.format(
                    app_root, game.id)
                page += '<td>' + players_scores + '</td>'
            else:  # Playing, not player's turn
                page += '<td><a href="{}/game?id={}">Awaiting Turn</a></td>'.format(
                    app_root, game.id)
                page += '<td>' + players_scores + '</td>'
            page += '</tr>\n'
        page += '</table>'
        page += '<p><a href="{}/newgame">Start a New Game</a></p>'.format(
            app_root)
        ts1 = max(game.ts for game in games) if games else None

        page += '<h2>Games accepting players</h2>\n'
        page += '<table><tr><th>Game</th><th>Goal</th><th>Join</th><th>State</th><th>Players</th></tr>\n'
        games = [
            Pyramid(i, p, g, 0, ts, t, db.connection) for i, p, g, ts, t in
            db.get_registering_games_by_user(session_user)
        ]
        for game in games:
            page += '<tr><td>{}</td><td>{}</td><td><a href="{}/join?id={}">join</a></td>'.format(
                game.id, game.goal, app_root, game.id)
            page += '<td>{} of {} players</td>'.format(len(game.players),
                                                       game.num_players,
                                                       game.id)
            page += '<td>' + ', '.join([p['name']
                                        for p in game.players]) + '</td>'
            page += '</tr>\n'
        page += '</table>'
        ts2 = max(game.ts for game in games) if games else None

        page += '''
<script>
    function callback(event) {{
        if (event.target.readyState == 4 && event.target.responseText != '{} {}') {{
            window.location = '{}'
        }}
    }}
    function timeFunc(event) {{
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.addEventListener("readystatechange", callback)
        xmlhttp.open("GET", "{}/updated_games", true)
        xmlhttp.setRequestHeader("Content-Type", "text/plain")
        xmlhttp.send()
    }}
    setInterval(timeFunc, 1000)
</script>'''.format(ts1, ts2, app_root, app_root)

        start_response('200 OK', headers)
        return [(page + '</body></html>').encode()]

    # ----- Check if game list changed -------------------------------------------

    elif path_info == '/updated_games':
        if not session:
            start_response('200 OK', headers)
            return ['No session'.encode()]

        ts1, ts2 = db.updated_games(session_user)

        start_response('200 OK', headers)
        return ['{} {}'.format(ts1, ts2).encode()]

    # ----- Register new game ---------------------------------------------------------------
    # ***** MODIFY THIS PART TO ASK FOR NUMBER OF PLAYERS AND RECEIVE NUMBER OF PLAYERS *****

    elif path_info == '/newgame':
        if not session:
            start_response('200 OK', headers)
            return ['No session'.encode()]

        if 'goal' in params:
            db.new_game(2, params['goal'][0], session_user)
            headers.append(('Location', app_root))
            start_response('303 See Other', headers)
            return []

        page += '''
<h2>Create New Game</h2>
<form>
    <h3>Play until score:</h3>
    <input type="radio" name="goal" value="1">1<br>
    <input type="radio" name="goal" value="3">3<br>
    <input type="radio" name="goal" value="5">5<br>
    <input type="radio" name="goal" value="10" checked>10<br>
    <input type="radio" name="goal" value="20">20<br>
    <input type="radio" name="goal" value="100">100<br>
    <input type="submit" value="Create">
</form>
</body></html>'''

        start_response('200 OK', headers)
        return [page.encode()]

    # ----- Join game -----------------------------------------

    elif path_info == '/join':
        if not session:
            start_response('200 OK', headers)
            return ['No session'.encode()]

        game_id = params['id'][0]
        db.join_game(game_id, session_user)

        headers.append(('Location', app_root))
        start_response('303 See Other', headers)
        return []

    # ----- Quit game -----------------------------------------

    elif path_info == '/quit':
        if not session:
            start_response('200 OK', headers)
            return ['No session'.encode()]

        game_id = params['id'][0]
        db.quit_game(game_id, session_user)

        headers.append(('Location', app_root))
        start_response('303 See Other', headers)
        return []

    # ----- Game ------------------------------------------------------------

    elif path_info == '/game':
        if not session:
            start_response('200 OK', headers)
            return ['No session'.encode()]

        game_id = params['id'][0]

        (players, goal, state, ts, turns) = db.get_game_by_id(game_id)
        game = Pyramid(game_id, players, goal, state, ts, turns, db.connection)
        if game.state == 0:  # Error: cannot view game, it is still registering players
            start_response('200 OK', headers)
            return [
                (page + 'Still registering players</body></html>').encode()
            ]

        if 'move' in params:  # Player came here by making a move
            game.add_player_move(session_user, params['move'][0])

        page += '<a href="{}">Home</a>'.format(app_root)
        #       page += ' | <a href="{}/game?id={}">Refresh</a>'.format(app_root, game_id)
        page += '<h3>Game {} -- Play to {}</h3>'.format(game.id, game.goal)

        if game.state == 2:
            page += '<p>Game over</p>'
        elif game.is_players_turn(session_user):
            page += '<p>Your move: '
            move_template = '<a href="{}/game?id={}&amp;move={}">{}</a>'
            move_links = [
                move_template.format(app_root, game.id, mval, mname)
                for mval, mname in game.valid_moves(session_user)
            ]
            page += ' | '.join(move_links)
        else:
            page += '<p>Wait for your turn</p>'

        page += '<table>\n<tr><th>&nbsp;</th>'
        for p in game.players:
            page += '<th>{}</th>'.format(
                p['name']) if p['playing'] else '<th><s>{}</s></th>'.format(
                    p['name'])
        page += '</tr>\n<tr style="background-color: silver"><td>Round</td>'
        for p in game.players:
            page += '<td>{} p</td>'.format(p['score'])
        page += '</tr>\n'

        for index, turn in enumerate(
                reversed(game.decorated_moves(session_user))):
            page += '<tr><td>{}</td>'.format(len(game.turns) - index)
            for move, winner in turn:
                if winner:
                    page += '<td style="background-color:lightgreen">{}</td>'.format(
                        move)
                else:
                    page += '<td>{}</td>'.format(move)
            page += '</tr>\n'

        page += '</table>'

        if game.state == 1:
            page += '''
<script>
    function callback(event) {{
        if (event.target.readyState == 4 && event.target.responseText != '{}') {{
            window.location = '{}/game?id={}'
        }}
    }}
    function timeFunc(event) {{
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.addEventListener("readystatechange", callback)
        xmlhttp.open("GET", "{}/updated_game?id={}", true)
        xmlhttp.setRequestHeader("Content-Type", "text/plain")
        xmlhttp.send()
    }}
    setInterval(timeFunc, 1000)
</script>'''.format(game.ts, app_root, game.id, app_root, game.id)

        start_response('200 OK', headers)
        return [(page + '</body></html>').encode()]

    # ----- Check if game changed --------------------------------------

    elif path_info == '/updated_game':
        if not session:
            start_response('200 OK', headers)
            return ['No session'.encode()]

        start_response('200 OK', headers)
        p, g, s, ts, t = db.get_game_by_id(params['id'][0])
        return ['{}'.format(ts).encode()]

    # ----- Dump tables ------------------------------------------------

    elif path_info == '/dump':
        users, games, players = db.dump()

        page += '<a href="{}">Home</a>'.format(app_root)
        page += ' | <a href="{}/clear_games">Clear games and players</a>'.format(
            app_root)
        page += ' | <a href="{}/clear_all">Clear all</a>'.format(app_root)

        page += '<h2>Table "user"</h2>\n'
        page += '<p>Contains all registered users and their passwords.</p>\n'
        page += '<table><tr><th>name</th><th>password</th></tr>\n'
        for name, password in users:
            page += '<tr><td>{}</td><td>{}</td></tr>\n'.format(name, password)
        page += '</table>\n'

        page += '<h2>Table "game"</h2>\n'
        page += '<p>One row for every game.</p>\n'
        page += '<table><tr><th>rowid</th><th>players</th><th>goal</th><th>state</th><th>ts</th><th>turns</th></tr>\n'
        for rowid, numplayers, goal, state, ts, turns in games:
            page += '<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>\n'.format(
                rowid, numplayers, goal, state, ts, turns)
        page += '</table>\n'

        page += '<h2>Table "player"</h2>\n'
        page += '<p>Connects players with games. One row for every player in a game.</p>\n'
        page += '<table><tr><th>rowid</th><th>game_id</th><th>user_name</th><th>score</th><th>playing</th></tr>\n'
        for rowid, game_id, user_name, score, playing in players:
            page += '<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>\n'.format(
                rowid, game_id, user_name, score, playing)
        page += '</table>\n'

        page += '</body></html>'

        start_response('200 OK', headers)
        return [page.encode()]

    # ----- Clear tables --------------------------------------

    elif path_info == '/clear_games':
        db.clear_tables(False)
        headers.append(('Location', '{}/dump'.format(app_root)))
        start_response('303 See Other', headers)
        return []

    elif path_info == '/clear_all':
        db.clear_tables(True)
        headers.append(('Location', '{}/dump'.format(app_root)))
        start_response('303 See Other', headers)
        return []

    # ----- Unknown web app ----------------------------------------------------------

    else:
        start_response('200 OK', headers)
        return [
            (page +
             'Unknown Web app {}</body></html>'.format(path_info)).encode()
        ]
Exemplo n.º 16
0
 def __init__(self, debug=True):
     self.pyramid = Pyramid()
     self.debug = debug
Exemplo n.º 17
0
def keyPressed(*args):
    global camera
    global lineVision
    global objVision
    
    key=glutGetModifiers()
    
    #print(args[0])
    
    # If escape is pressed, kill everything.
    if args[0]==ESCAPE:
        sys.exit()
    elif args[0] == b'z':
        scene.objects[0].rotate_point_z(10,scene.objects[0].center)
    elif args[0] == b"x":
        scene.objects[0].rotate_point_x(10,scene.objects[0].center)
    elif args[0] == b"c":
        scene.objects[0].rotate_point_y(10,scene.objects[0].center)
        
    elif args[0] == b"b":
        scene.objects[0].increase_subdivisions()
    elif args[0] == b"n":
        scene.objects[0].decrease_subdivisions()

 
        
    elif args[0] == b"w":
        camera.move_forward(.1)
    elif args[0] == b"s":
        camera.move_backward(.1)
        
    elif args[0] == b"1":
        scene.cleanScene()
        scene.addObject(Sphere(18,12,1))
        scene.addObject(grid)
    elif args[0] == b"2":
        scene.cleanScene()
        scene.addObject(Torus(11,11,.3,1))
        scene.addObject(grid)
    elif args[0] == b"3":
        scene.cleanScene()
        scene.addObject(Cylinder(2,11,0.08))
        scene.addObject(grid)
    elif args[0] == b"4":
        scene.cleanScene()
        scene.addObject(Box(1,1,1))
        scene.addObject(grid)
    elif args[0] == b"5":
        scene.cleanScene()
        scene.addObject(Pyramid(.4))
        scene.addObject(grid)
    elif args[0] == b"6":
        scene.cleanScene()
        scene.addObject(Icosahedron())
        scene.addObject(grid)
    elif args[0] == b"7":
        scene.cleanScene()
        scene.addObject(Octahedron(1,3))
        scene.addObject(grid)
        
    elif args[0] == b"l":
        lineVision=True
        objVision=False
    elif args[0] == b"o":
        lineVision=False
        objVision=True
    elif args[0] == b"p":
        lineVision=True
        objVision=True
        
    elif args[0] == b"f":
        camera=Camera(Vec3d(0,0,5),Vec3d(0,0,-1))
Exemplo n.º 18
0
def main():
    pygame.init()
    size = 600
    display = (size, size)
    pygame.display.set_mode(display, DOUBLEBUF | OPENGL)
    player = Player()

    clock = pygame.time.Clock()
    exit = True
    wall = True
    sens = 0.25
    vel = 18
    thetax = 0
    thetay = 0
    jump = False

    bcheck = True

    randpyramid = random.choice([i for i in range(2, 7)])
    pyramid_list = []
    for i in range(randpyramid):
        x = Pyramid()
        pyramid_list.append(x)
    c = 0

    bullet_list = []

    while exit:

        clock.tick(90)

        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        # Define mouse position and camera orientation

        m = glGetDoublev(GL_MODELVIEW_MATRIX).flatten()
        pos = player.getposition()
        mouse_dx, mouse_dy = pygame.mouse.get_rel()
        mousepos = pygame.mouse.get_pos()

        # Define keys and getting direction of movement

        keys = pygame.key.get_pressed()
        fwd = -vel * (keys[K_w] - keys[K_s])
        strafe = vel * (keys[K_a] - keys[K_d])

        if abs(fwd) or abs(strafe):
            try:
                wallcollide(player, fwd, strafe)
            except IndexError:
                pass

        if keys[pygame.K_ESCAPE]:
            exit = False

        if pygame.mouse.get_pressed() == (0, 0, 0):
            bcheck = True

        if bcheck:
            if pygame.mouse.get_pressed() == (1, 0, 0):
                b = Bullet()
                b.brotate(thetax, thetay)
                b.bmove(pos[0], pos[1], pos[2])
                bullet_list.append(b)
                bcheck = False

        if not jump:
            if keys[pygame.K_SPACE]:
                jump = True

        if jump:
            array = np.linspace(-1, 1)
            player.gravity(array[c])
            c += 1
            if c == len(array):
                c = 0
                jump = False

        if wall:
            player.rotateworld(mouse_dx * sens, mouse_dy * sens)
            thetax = deg(atan2(m[8], m[0]))
            thetay = deg(
                atan2(-m[6],
                      -m[8] * sin(rad(thetax)) + m[10] * cos(rad(thetax))))

        if keys[pygame.K_UP]:
            player.rotateworld(0, -0.4)
            player.updatecross(0, -0.4)
        if keys[pygame.K_RIGHT]:
            player.rotateworld(0.4, 0)
            player.updatecross(0.4, 0)
        if keys[pygame.K_DOWN]:
            player.rotateworld(0, 0.4)
            player.updatecross(0, 0.4)
        if keys[pygame.K_LEFT]:
            player.rotateworld(-0.4, 0)
            player.updatecross(-0.4, 0)

        wall = True
        if mousepos[0] <= 1:
            pygame.mouse.set_pos(size, mousepos[1])
            wall = False
        if mousepos[0] >= size - 1:
            pygame.mouse.set_pos(0, mousepos[1])
            wall = False
        if mousepos[1] <= 1:
            pygame.mouse.set_pos(mousepos[0], size)
            wall = False
        if mousepos[1] >= size - 1:
            pygame.mouse.set_pos(mousepos[0], 0)
            wall = False

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        player.drawroom()
        player.draw()
        for i in pyramid_list:
            i.drawpyramid()
            i.checkpyramid(player)

        for i in bullet_list:
            i.bmove(i.bvel * sin(rad(i.thetax)), -i.bvel * sin(rad(i.thetay)),
                    -i.bvel * cos(rad(i.thetax)))
            i.drawbullet()
            try:
                if abs(i.pos[0]) > i.mulx:
                    bullet_list.remove(i)
                if abs(i.pos[2]) > i.mulz:
                    bullet_list.remove(i)
                if abs(i.pos[1]) > i.muly or i.pos[1] < 0:
                    bullet_list.remove(i)
            except ValueError:
                pass

        player.updatecross(thetax, -thetay)
        player.crosshair()

        if keys[K_KP_ENTER]:
            pygame.event.set_grab(True)
            pygame.mouse.set_cursor((8, 8), (0, 0), (0, 0, 0, 0, 0, 0, 0, 0),
                                    (0, 0, 0, 0, 0, 0, 0, 0))
            pygame.mouse.set_pos(size / 2, size / 2)
            player.rotateworld(-thetax, -thetay)
            thetax, thetay = 0, 0
            player.crosshair()

        pygame.display.flip()
        print(player.getposition())
Exemplo n.º 19
0
class Camera:
    def __init__(self, filmSize, focalLength, imagePath):
        # intrinsic parameters
        self.fieldOfView = {"x": 0.0, "y": 0.0}
        self.fieldOfView['x'] = 2.0 * atan(filmSize['width'] /
                                           (2.0 * focalLength))
        self.fieldOfView['y'] = 2.0 * atan(filmSize['height'] /
                                           (2.0 * focalLength))
        self.zPlane = {"near": 0.1, "far": 1000.0}
        self.image = {"width": 0.0, "height": 0.0, "data": None}
        self.loadImage(imagePath)
        self.canvas = {"width": 0.0, "height": 0.0}
        self.canvas['width'] = 2.0 * tan(
            self.fieldOfView['x'] / 2.0) * self.zPlane['near']
        self.canvas['height'] = 2.0 * tan(
            self.fieldOfView['y'] / 2.0) * self.zPlane['near']
        # coordinate system
        self.coordSystem = {
            "x": np.array([1.0, 0.0, 0.0], np.float32),
            "y": np.array([0.0, 1.0, 0.0], np.float32),
            "z": np.array([0.0, 0.0, 1.0], np.float32)
        }

    def loadImage(self, imagePath):
        img = image.read(imagePath)
        self.image['width'] = img[0]
        self.image['height'] = img[1]
        self.image['data'] = img[2]

    def adjustRotation(self, yaw, pitch, roll):
        rotation = mat.rotation(yaw, pitch, roll)
        self.coordSystem['x'] = mat.vec3(
            np.dot(rotation, mat.vec4(self.coordSystem['x'])))
        self.coordSystem['y'] = mat.vec3(
            np.dot(rotation, mat.vec4(self.coordSystem['y'])))
        self.coordSystem['z'] = mat.vec3(
            np.dot(rotation, mat.vec4(self.coordSystem['z'])))

    def setPosition(self, x, y, z):
        self.position = np.array([x, y, z], np.float32)

    def ray(self, x, y):
        u = self.canvas['width'] * ((x / self.image['width']) - 0.5)
        v = self.canvas['height'] * ((y / self.image['height']) - 0.5)
        w = -self.zPlane['near']
        a = np.array(self.coordSystem['x'] * u)
        b = np.array(self.coordSystem['y'] * v)
        c = np.array(self.coordSystem['z'] * w)
        d = mat.normalize((a + b) + c)
        return d

    def intersection(self, ray):
        v0 = np.array([0.0, 0.0, 0.0], np.float32)
        normal = np.array([0.0, 0.0, 0.1], np.float32)
        num = np.dot(normal, v0 - self.position)
        den = np.dot(normal, ray)
        t = num / den
        return self.position + t * ray

    def initialize(self):
        rect = Rectangle()
        rect.bottomLeft = self.intersection(self.ray(0, 0))
        rect.topLeft = self.intersection(self.ray(0, self.image['height']))
        rect.topRight = self.intersection(
            self.ray(self.image['width'], self.image['height']))
        rect.bottomRight = self.intersection(self.ray(self.image['width'],
                                                      0.0))
        self.pyramid = Pyramid(self.position, rect)
        self.plane = Plane(rect, self.image)

    def display(self, width, height, z, current=False, frustrum=False):
        self.plane.draw(width, height, z)
        if frustrum:
            self.pyramid.draw(width, height, z, current)
Exemplo n.º 20
0
class Game(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.card = False
        self._well = Deck(DeckStrategy.invisible, self)
        self._vwell = Deck(DeckStrategy.visible, self)
        self._pyramid = Pyramid(self._well, self)
        p = self.palette()
        p.setColor(self.backgroundRole(), QtGui.QColor(3, 89, 2))
        self.setPalette(p)
        self.__score = 0

        self.score_view = QtWidgets.QLabel("Score: 0", parent=self)
        self.score_view.setGeometry(20, Card.height + 20, 200, 40)
        ps = self.score_view.palette()
        ps.setColor(self.score_view.foregroundRole(),
                    QtGui.QColor(255, 255, 255))
        self.score_view.setPalette(ps)

        self.show()

    def cardClick(self, element: int, row: int):
        card = self._pyramid._cards[element]

        if card.leaf > 0:
            return

        if self.card == False:
            if card._rank.value == 13:
                self.score += 50
                for link in self._pyramid.getLinks(element, row):
                    link.leaf = link.leaf - 1
                card.setParent(None)
                return
            card.toggleActive()
            self.card = [card, element, row]
        else:
            if self.card[0] is card:
                card.toggleActive()
                self.card = False
                return

            if self.card[0]._rank.value + card._rank.value == 13:
                self.score += 50

                if len(self.card) == 3:
                    for link in self._pyramid.getLinks(self.card[1],
                                                       self.card[2]):
                        link.leaf = link.leaf - 1

                for link in self._pyramid.getLinks(element, row):
                    link.leaf = link.leaf - 1

                self.card[0].setParent(None)
                card.setParent(None)
            else:
                self.card[0].toggleActive()
            self.card = False

    @property
    def score(self):
        return self.__score

    @score.setter
    def score(self, value: int):
        self.__score = value
        self.score_view.setText("Score: " + str(value))
Exemplo n.º 21
0
class Camera:
    def __init__(self, filmSize, focalLength, imagePath):
        # intrinsic parameters
        self.fieldOfView = { "x": 0.0, "y": 0.0 }
        self.fieldOfView['x'] = 2.0 * atan(filmSize['width'] / (2.0 * focalLength))
        self.fieldOfView['y'] = 2.0 * atan(filmSize['height'] / (2.0 * focalLength))
        self.zPlane = { "near": 0.1, "far": 1000.0 }
        self.image = { "width": 0.0, "height": 0.0, "data": None }
        self.loadImage(imagePath)
        self.canvas = { "width": 0.0, "height": 0.0 }
        self.canvas['width'] = 2.0 * tan(self.fieldOfView['x'] / 2.0) * self.zPlane['near']
        self.canvas['height'] = 2.0 * tan(self.fieldOfView['y'] / 2.0) * self.zPlane['near']
        # coordinate system
        self.coordSystem = { "x": np.array([1.0, 0.0, 0.0], np.float32),
                             "y": np.array([0.0, 1.0, 0.0], np.float32),
                             "z": np.array([0.0, 0.0, 1.0], np.float32) }


    def loadImage(self, imagePath):
        img = image.read(imagePath)
        self.image['width'] = img[0]
        self.image['height'] = img[1]
        self.image['data'] = img[2]


    def adjustRotation(self, yaw, pitch, roll):
        rotation = mat.rotation(yaw, pitch, roll)
        self.coordSystem['x'] = mat.vec3(np.dot(rotation, mat.vec4(self.coordSystem['x'])))
        self.coordSystem['y'] = mat.vec3(np.dot(rotation, mat.vec4(self.coordSystem['y'])))
        self.coordSystem['z'] = mat.vec3(np.dot(rotation, mat.vec4(self.coordSystem['z'])))


    def setPosition(self, x, y, z):
        self.position = np.array([x, y, z], np.float32)


    def ray(self, x, y):
        u = self.canvas['width'] * ((x / self.image['width']) - 0.5)
        v = self.canvas['height'] * ((y / self.image['height']) - 0.5)
        w = -self.zPlane['near']
        a = np.array(self.coordSystem['x'] * u)
        b = np.array(self.coordSystem['y'] * v)
        c = np.array(self.coordSystem['z'] * w)
        d = mat.normalize((a + b) + c)
        return d


    def intersection(self, ray):
        v0 = np.array([0.0, 0.0, 0.0], np.float32)
        normal = np.array([0.0, 0.0, 0.1], np.float32)
        num = np.dot(normal, v0 - self.position)
        den = np.dot(normal, ray)
        t = num / den
        return self.position + t * ray


    def initialize(self):
        rect = Rectangle()
        rect.bottomLeft = self.intersection(self.ray(0, 0))
        rect.topLeft = self.intersection(self.ray(0, self.image['height']))
        rect.topRight = self.intersection(self.ray(self.image['width'], self.image['height']))
        rect.bottomRight = self.intersection(self.ray(self.image['width'], 0.0))
        self.pyramid = Pyramid(self.position, rect)
        self.plane = Plane(rect, self.image)


    def display(self, width, height, z, current=False, frustrum=False):
        self.plane.draw(width, height, z)
        if frustrum:
            self.pyramid.draw(width, height, z, current)
Exemplo n.º 22
0
from deck import Deck
from pyramid import Pyramid


class Game(object):
    def __init__(self):
        self.deck = Deck()
        self.pyramid = Pyramid()
        for i in range(28):
            self.pyramid.deck_pyramid.append(self.deck.__next__())

        for card in self.pyramid.deck_pyramid:
            print(card)
        print("-----------")


g = Game()
p = Pyramid()
p.call(8)
Exemplo n.º 23
0
"""Test file check all Pyramid module funcation """
from pyramid import Pyramid

if __name__ == "__main__":
    import os  #remove if dont have linux
    myPyramid = Pyramid()
    while 1:

        print("""---Pyramid DataStructure---
                \n |1| Insert Pyramid Layer
                \n |2| View Pyramid Graph
                \n |3| Vertical List 
                \n |4| Reverse Vertical List 
                \n |5| Horizontal List 
                \n |6| Reverse Horizontal List 
                \n |7| POP Pyramid Layer
                \n |8| DeQueue Pyramid Layer
                \n |9| Root to Right List
                \n |10| Root to Left List
                \n |11| Root to Up List
                \n |12| Root to Down List
            """)

        ch = input("Enter : ")
        if ch == "1":
            myPyramid.insert_pyramid_layer(input("Enter Down Data :"),
                                           input("Enter Right Data :"),
                                           input("Enter Top Data :"),
                                           input("Enter Left Data :"))
        elif ch == "2":
            myPyramid.graph_view()
Exemplo n.º 24
0
                r = int((x / self.width) * 255) if x / self.width < 1 else 1
                g = int((y / self.height) * 255) if y / self.height < 1 else 1
                b = 0
                self.pixels[y][x] = Color(r, g, b)
    


r = Raytracer(400, 400)
#r.envMap = Envmap('fondo.bmp')
r.light = Light(
    position = V3(0, 20, 20),
    intensity = 1.5
)
r.ambientLight = AmbientLight(strength = 0.1)
r.scene = [
    Pyramid([V3(-1, 0, -10), V3(-3, 2, -10), V3(-5, 0, -10), V3(-1, 0, -10)], blue3),
    Pyramid([V3(1, 0, -10), V3(3, 2, -10), V3(5, 0, -10), V3(1, 0, -10)], blue3),
    Pyramid([V3(-2, 0, -10), V3(-4, 2, -10), V3(-6, 0, -10), V3(-2, 0, -10)], blue2),
    Pyramid([V3(2, 0, -10), V3(4, 2, -10), V3(6, 0, -10), V3(2, 0, -10)], blue2),
    Pyramid([V3(0, 0, -10), V3(-2, 2, -10), V3(-4, 0, -10), V3(0, 0, -10)], blue4),
    Pyramid([V3(0, 0, -10), V3(2, 2, -10), V3(4, 0, -10), V3(0, 0, -10)], blue4),
    Pyramid([V3(2, 0, -10), V3(0, 3, -10), V3(-2, 0, -10), V3(2, 0, -10)], blue1),
    Cube(V3(0, -2, -2), 2, beige),
    Pyramid([V3(-1, 0, -10), V3(3, 0, -10), V3(-1, 0, -5), V3(-1, -1, -10)], brown),
    Cube(V3(0.75, -0.75, -2.5), 0.5, blue5),
    Sphere(V3(0.75, -0.40, -2.5), 0.20, white),
    Sphere(V3(0.75, -0.16, -2.5), 0.05, white),
    Plane(V3(2, -10, -15), V3(0,1,0), mirror),
    
    
    Sphere(V3(5, 0.1, -10), 0.10, green),