Exemplo n.º 1
0
def createPlayer(self):
    '''Creates a new Player Character and returns that character as a JSON
    Response.
    '''
    logging.info('###################### createPlayer() ####################')    
    # Build the basic data format for scores and fill base values ...
    abilities = buildScores(self, models.ABILITIES_KEY, models.ABILITY_KEYS)
    skills = buildScores(self, models.SKILLS_KEY, models.SKILL_KEYS)
    defenses = buildScores(self, models.DEFENSES_KEY, models.DEFENSE_KEYS)
    scores = {'abilities': abilities, 'skills': skills, 'defenses': defenses}
    logging.info('###################### score = '+str(scores)+'############')
    scores = buildDefenses(scores)
    # Update score data with Race and Cast bonuses ...
    race = models.Race.get_by_key_name(self.request.get('race'))
    cast = models.Cast.get_by_key_name(self.request.get('cast'))   
    logging.info('###################### score = '+str(scores)+'############')     
    scores = addMods(self, scores, race.mods, cast.mods)
    hp = buildHitPoints(cast, scores)
    player = models.PlayerCharacter(name = self.request.get('name'),
                                    level = 1,
                                    speed = utils.strToInt(self.request.get('speed')),
                                    size = self.request.get('size'),
                                    race = self.request.get('race'),
                                    cast = self.request.get('cast'),
                                    alignment = self.request.get('alignment'),
                                    hit_points = hp,
                                    height = utils.strToInt(self.request.get('height')),
                                    weight = utils.strToInt(self.request.get('weight')),
                                    scores = scores)
    db.put(player)
    return player
Exemplo n.º 2
0
def parseFBJSON(json):
    """Returns a dictionary of game data retrieved from Freebase.
    """
    logging.info(TRACE+'parseFBJSON('+str(json)+')')
    fb_data = {'name': json.name}
    if json.introduced is not None: 
        fb_data['year_published'] = strToInt(json.introduced)  
    else: fb_data['year_published'] = None      
    if json["/games/game/number_of_players"] is not None:
        fb_data['min_players'] = strToInt(json["/games/game/number_of_players"].high_value)
        fb_data['max_players'] = strToInt(json["/games/game/number_of_players"].low_value)
    else: 
        fb_data['min_players'] = None
        fb_data['max_players'] = None
    if json.playing_time_minutes is not None:
        fb_data['playing_time'] = strToInt(json.playing_time_minutes)
    else: fb_data['playing_time'] = None
    if json.minimum_age_years is not None:
        fb_data['age'] = strToInt(json.minimum_age_years)
    else: fb_data['age'] = None   
    if json.publisher is not None:
        fb_data['publishers'] = json.publisher
    else: fb_data['publishers'] = None
    if json.designer is not None:
        fb_data['designers'] = json.designer
    else: fb_data['designers'] = None
    if json.expansions is not None:
        fb_data['expansions'] = json.expansions  
    else: fb_data['expansions'] = None    
    
    return fb_data        
Exemplo n.º 3
0
 def get(self, method):
     logging.info(TRACE+'APICheckin:: get()')
     if method == "latest": 
         fb_id = self.request.get('fb_id')
         time_since = utils.strToInt(self.request.get('time_since'))
         limit = utils.strToInt(self.request.get('limit'))
         if time_since is None: time_since = 0 # Default to since 1970
         if limit is 0: limit = 10 # Default to a limit of 10
         if fb_id != '':
             logging.info(TRACE+'VALUE fb_id = ' +fb_id)                
             r = getLatestUserCheckins(limit, time_since, fb_id)
         else:    
             r = getLatestCheckins(limit, time_since)
     else: r = API404
     return self.response.out.write(simplejson.dumps(r)) 
Exemplo n.º 4
0
 def get(self, checkin_id):
     logging.info(TRACE+'GameLog:: get()')        
     checkin = models.Checkin.get_by_id(strToInt(checkin_id)) 
     if checkin is None:
         self.error(404)
         return
     game = checkin.game
     checkin_json = simplejson.loads(checkin.json)
     checkin_json['created'] = checkin.created
     checkin_json['id'] = str(checkin.key().id())
     logging.info(TRACE+'GameLog:: '+str(checkin_json))            
     user = self.current_user # this is the logged in User 
     if user is not None:
         result = facebook.GraphAPI(
             user.access_token).get_connections('me', 'friends')
         
         fb_data = result["data"]
         friends = []
         for f in fb_data:
             friends.append({'value':f['id'], 'label':f['name']})
         
         friends = simplejson.dumps(friends)
     else:
         user = None
         friends = None
         
     template_values = {
         'friends': friends,
         'checkin': checkin_json,
         'game': game,
         'current_user': user,
         'facebook_app_id': FACEBOOK_APP_ID
     }  
     self.generate('base_test.html', template_values)
Exemplo n.º 5
0
def buildHitPoints(cast, scores):
    logging.info('############## buildHitPoints() ##########################')    
    #{'hp': 10, 'surge': 2, 'recharge': 3}
    con = scores[models.ABILITIES_KEY]['CON']['score']
    hp = cast.hit_point_base + utils.strToInt(con)
    surge_recharge = cast.surge_recharge
    surge = hp//4
    hit_points = {'hp': hp, 'surge': surge, 'surge_recharge': surge_recharge}
    return hit_points
Exemplo n.º 6
0
def getGameLog(checkin_id):
    """Returns JSON formated GameLog Response.
    """
    logging.info(TRACE+'getGameLog('+checkin_id+')')
    q = models.Checkin.get_by_id(utils.strToInt(checkin_id)) 
    checkin = simplejson.loads(q.json)
    checkin['created'] = str(q.created)
    checkin['id'] = str(q.key().id())  
    data = {'checkin': checkin}
    r = API200
    r['result'] = data 
    logging.info(_trace+'result = '+r)
    return r 
Exemplo n.º 7
0
def parseBGGXML(bgg_id):
    """Returns a dictionary of game data retrieved from BGGs XML API.
    """
    logging.info(TRACE+'parseBGGXML('+bgg_id+')')
    bgg_game_url = BGG_XML_URI + bgg_id
    result = urllib2.urlopen(bgg_game_url).read()
    try:
        xml = ElementTree.fromstring(result)
    except Exception:
        logging.info(TRACE+'parseBGGXML() error parsing BGG')
        return None  
    decoded_result = result.decode("utf-8")
    xml_text = db.Text(decoded_result)
    bgg_data = {'name': findPrimaryName(xml),
                'description': xml.findtext(".//description"),
                'year_published': strToInt(xml.findtext(".//yearpublished")),
                'min_players': strToInt(xml.findtext(".//minplayers")),
                'max_players': strToInt(xml.findtext(".//maxplayers")),
                'playing_time': strToInt(xml.findtext(".//playingtime")),
                'age': strToInt(xml.findtext(".//age")),
                'publishers': 
                    buildDataList(xml.findall(".//boardgamepublisher")),
                'artists': buildDataList(xml.findall(".//boardgameartist")),
                'designers': 
                    buildDataList(xml.findall(".//boardgamedesigner")),  
                'expansions': 
                    buildDataList(xml.findall(".//boardgameexpansion")),
                'categories': 
                    buildDataList(xml.findall(".//boardgamecategory")),
                'mechanics': 
                    buildDataList(xml.findall(".//boardgamemechanic")),
                'subdomains': 
                    buildDataList(xml.findall(".//boardgamesubdomain")),
                'image_url': xml.findtext(".//image"),
                'thumbnail_url':xml.findtext(".//thumbnail"),
                'xml_text': xml_text}
    
    return bgg_data
Exemplo n.º 8
0
def createBadges():
    """Creates Badges and loads necessary images to the Blobstore.
    """
    _trace = TRACE + "createBadges():: "
    logging.info(_trace)
    base_url = "http://www.supermeeple.com/static/images/badges/"
    mime_type = "image/png"

    # Load Badges
    updated = []
    for b in awardbase.BADGES:
        badge = models.Badge.get_by_key_name(b["key"])
        if badge is None:
            logging.info(_trace + "creating Badge " + b["key"])

            # Get *image* file for this Badge
            image_name = b["key"] + ".png"
            logging.info(_trace + "image_name = " + image_name)
            image_blob_key = updateBlobStore(base_url, image_name, mime_type)

            # Get *banner* file for this Badge
            banner_name = b["key"] + "_BANNER.png"
            logging.info(_trace + "banner_name = " + banner_name)
            banner_blob_key = updateBlobStore(base_url, banner_name, mime_type)

            image_url = images.get_serving_url(str(image_blob_key))
            banner_url = images.get_serving_url(str(banner_blob_key))

            name = b["cat"] + " " + b["lvl"]
            badge = models.Badge(
                key_name=b["key"],
                name=name,
                description=b["description"],
                image=image_blob_key,
                image_url=image_url,
                banner=banner_blob_key,
                banner_url=banner_url,
                level=utils.strToInt(b["lvl"]),
                category=b["cat"],
            )

            updated.append(badge)

    db.put(updated)
    return None
Exemplo n.º 9
0
 def get(self, method):
     if method == "form":
         characters = models.PlayerCharacter.all().fetch(10)
         template_values = {
             'characters': characters
         }        
         generate(self, 'admin_character_form.html', template_values) 
     else:
         i = utils.strToInt(method)
         character = models.PlayerCharacter.get_by_id(i)    
         weapons = models.Weapon.all().fetch(100)
         powers = models.Power.all().fetch(100)                          
         template_values = {
             'character': character,
             'weapons': weapons,
             'powers': powers
         }        
         generate(self, 'admin_character.html', template_values)
Exemplo n.º 10
0
  def create_image(self):
    try:
      # Загружаем  SVG файл c границами регионов.
      file_name_regions = 'RF_Regions.svg'
      regions = open(file_name_regions, 'r').read()
    except:
      showerror("Ошибка", "Не найден файл '" + file_name_regions + "'.")
      return

    # Парсим SCV файл статистики.
    statistic = thematic_map_lib.parse_csv(self.entry_input_file_name.get())

    # Количество интервалов.
    current_band = utils.strToInt(self.current_band.get())

    # Значения интервалов.
    intervals = [[utils.strToFloat(self.interval_1_from.get()), utils.strToFloat(self.interval_1_to.get())],
                 [utils.strToFloat(self.interval_2_from.get()), utils.strToFloat(self.interval_2_to.get())],
                 [utils.strToFloat(self.interval_3_from.get()), utils.strToFloat(self.interval_3_to.get())],
                 [utils.strToFloat(self.interval_4_from.get()), utils.strToFloat(self.interval_4_to.get())],
                 [utils.strToFloat(self.interval_5_from.get()), utils.strToFloat(self.interval_5_to.get())],
                 [utils.strToFloat(self.interval_6_from.get()), utils.strToFloat(self.interval_6_to.get())]]

    # Проверяем и подготавливаем данные (интервалы значений для автоматического режима)
    if current_band == 0:
       current_band = 5
       (min_value, max_value) = utils.get_min_max_values( statistic.values() )
       step = (max_value - min_value)/5
       intervals = [[min_value, min_value+step],
                    [min_value+step, min_value+step*2],
                    [min_value+step*2, min_value+step*3],
                    [min_value+step*3, min_value+step*4],
                    [min_value+step*4, min_value+step*5,]]

    current_color = self.color_code[self.current_color.get()]

    # Редактируем SVG файл
    map_svg = thematic_map_lib.edit_svg(regions, statistic, current_band, intervals, current_color)

    # Конвертируем  и сохраняем SVG в PNG
    image_width = 1700
    image_height = 1050
    thematic_map_lib.save_svg_to_png(map_svg, self.entry_output_file_name.get(), image_width, image_height)
Exemplo n.º 11
0
def addToPlayer(model_type, object_name, player_id):
    '''Adds an Item or Power to a Player.
    '''
    args = '('+str(model_type)+', '+object_name+', '+player_id+')'
    logging.info('########## addToPlayer'+args)
    id_ = utils.strToInt(player_id)
    player = models.PlayerCharacter.get_by_id(id_)
    object_ = model_type.get_by_key_name(object_name)
    name = model_type.class_name() 
    logging.info('########## name = '+name+' ###############################')
    # Determine whether this is object is a subclass of Item or Power
    if name in (models.WPN, models.ARM, models.IMP, models.GEA): 
        player.items.append(object_.key())
    elif name in (models.ATT, models.UTL, models.HEL):
        player.powers.append(object_.key())
    else:
        logging.info('########## NO MATCH FOUND for '+object_name+' ########')
        return None    
    db.put(player)  
    return player
Exemplo n.º 12
0
def getScore(scores, cat_key, keyword):
    logging.info('######################## getScore() ######################')      
    score = scores[cat_key][keyword]['score']    
    return utils.strToInt(score)    
Exemplo n.º 13
0
def getMod(scores, cat_key, keyword):
    logging.info('######################## getMod() ########################')    
    mod = scores[cat_key][keyword]['mod']
    return utils.strToInt(mod)
Exemplo n.º 14
0
def createGameLog(self, checkin_id):
    '''Creates new GameLog and Returns JSON Response of Checkin, Scores,
    Badges and Game.
    '''
    _trace = TRACE+'createGameLog('+checkin_id+') '
    logging.info(_trace)
    game_log = models.GameLog.get_by_key_name(checkin_id)  
    if game_log: return # game_log already exists!
    checkin = models.Checkin.get_by_id(strToInt(checkin_id))
    user = models.User.get_by_key_name(self.request.get('fb_id1'))    
    # Read and organize data ...
    note = self.request.get('note')
    mid = self.request.get('mid')  
    logging.info(_trace+' note = '+note)
    logging.info(_trace+' mid = '+mid) 
    game_key = db.Key.from_path('Game', mid)         
    scores = [] 
    player_keys = []
    entities = []
    count = 1
    while (count < 9):
        player_name = self.request.get('name'+str(count))
        if player_name:
            player_id = self.request.get('fb_id'+str(count)) 
            points = self.request.get('score'+str(count))
            win = self.request.get('win'+str(count))
            if win == "True": win = True
            else: win = False
            score = {"name":player_name,
                     "fb_id":player_id,
                     "points":points,
                     "winner":win}
            logging.info(_trace+'  score '+str(count)+' '+str(score))
            scores.append(score)                    
            if player_id: # Only Facebook Players ...
                player_key = db.Key.from_path('User', player_id)
                player = models.User.get(player_key)
                # If the player has never logged on, create them
                if player is None:
                    player = main.createLiteUser(player_name, player_id)
                    entities.append(player)
                player_keys.append(player_key)
                # Create Score ...
                entity = models.Score(game=game_key,
                                      player=player_key,
                                      gamelog_id=strToInt(checkin_id),
                                      points=strToInt(points),
                                      win=win, 
                                      author=user)
                entities.append(entity)
        count += 1
        
    # Update Checkin with JSON string of Scores ...    
    game_log_json = {'scores':scores, 'note':note}    
    checkin_json_dict = simplejson.loads(checkin.json)
    checkin_json_dict['gamelog'] = game_log_json
    checkin_json_txt = simplejson.dumps(checkin_json_dict)
    checkin.json = db.Text(checkin_json_txt)
    entities.append(checkin)
    
    # Create a new GameLog ...
    game_log = models.GameLog(key_name=checkin_id,
                              game=game_key,
                              checkin=checkin,
                              note=note,
                              players=player_keys)
    entities.append(game_log)
    
    # Update User's score count ...
    user.score_count += 1
    entities.append(user)
            
    # Save all entities
    db.put(entities)
  
    # Share gamelog on Facebook if requested ...
    share = self.request.get('facebook')
    if share.upper() == 'TRUE':
        deferred.defer(shareGameLog, user, simplejson.loads(checkin.json))

    return game_log_json
Exemplo n.º 15
0
HOST = '127.0.0.1'
PORT = 65432

while True:
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind((HOST, PORT))
        s.listen()
        conn, addr = s.accept()
        resultado = ""

        with conn:                       
            conn.sendall("digite".encode())
            dados = conn.recv(1024)                           

            dados = utils.strToInt(dados)            

            while True:
                msg = 'menu'.encode()
                conn.sendall(msg)
                escolha = conn.recv(1024)
                escolha = escolha.decode()                            

                if(escolha == '1'):
                    media = calc.media(dados)
                    resultado = "O resultado da média é: "+str(media)
                    conn.sendall(resultado.encode())
                elif(escolha == '2'):
                    mediana = calc.mediana(dados)
                    resultado = "O resultado da mediana é: "+str(mediana)
                    conn.sendall(resultado.encode())