def get(self):
        Utils.reset(self)  # reset/clean standard variables
        name = self.request.get('name')
        if name == '':
            name = 'Guest?'

        name2 = self.request.get('name2')
        if name2 == '':
            name2 = 'Guest??'

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')
        track = Utils.required(self, 'track')
        toid = Utils.required(self, 'toid')
        image = self.request.get('image')
        image2 = self.request.get('image2')

        friend = False
        if self.request.get('friend'):
            friend = bool(self.request.get('friend'))

        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()  # start count

        Utils.LogRequest(self)

        # logic variables
        player = None

        # if error, skip this
        if self.error == '':
            player = Player.getplayer(self, uuid)

        if self.error == '' and player is not None and guid != '':
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        if self.error == '' and player is not None:
            logging.warn('creating new challenge with' + player.uuid)
            challenge = Challenge.Create(self, track, player.uuid, toid, name,
                                         name2, image, image2, friend)
            if challenge is not None:
                self.respn = '{'
                Challenge.ComposeActualChallenge(self, challenge)
                self.respn = self.respn.rstrip(',') + '}'
            # update timestamp for player
            player.state_obj['updated'] = start_time
            Player.setplayer(self, player)

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
    def get(self):
        Utils.reset(self)  # reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')
        chid = self.request.get('chid')

        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()  # start count

        # logic variables
        player = None

        # if error, skip this
        if self.error == '':
            player = Player.getplayer(self, uuid)

        if self.error == '' and player is not None and guid != '':
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        result = None
        if self.error == '' and player is not None:
            if chid:
                if Challenge.DeleteById(self, chid):
                    result = '"result":"deleted successfully"'
                else:
                    result = '"result":"Challenge Id=' + chid + ' could not be found, nothing was deleted"}'
            else:
                if Challenge.DeleteByUserId(self, player.uuid):
                    result = '"result":"deleted successfully"'
                elif Challenge.DeleteByUserId(self, player.fbid):
                    result = '"result":"deleted successfully"'
                else:
                    result = '"result":"nothing was deleted"'

        if self.error == '' and player is not None:
            self.respn = '{'
            Challenge.ComposeChallenges(self, player)
            self.respn += ',' + result
            self.respn = self.respn.rstrip(',') + '}'

            # update timestamp for player
            player.state_obj['updated'] = start_time
            Player.setplayer(self, player)

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
Exemple #3
0
    def get(self):
        Utils.reset(self)														# reset/clean standard variables
        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')

        if self.error == '' and passwd != config.testing['passwd']:                	# if password is incorrect
            self.error = 'passwd is incorrect.'                                    	# inform user via error message

        start_time = time.time()                                                # start count

        player = None
        recentplayerlist = None

        # if error, skip this
        if self.error == '':
            player = Player.getplayer(self, uuid)								# get player state from Player helper class, specified by uuid

        if self.error == '' and player is not None and guid != '':
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        if self.error == '' and player is not None:												# if have some data returned
            recentplayerlist = Data.GetRecentPlayerList(self)

        if self.error == '' and recentplayerlist is not None:
            _range = config.recentplayer['maxlist']
            if _range > len(recentplayerlist.obj):
                _range = len(recentplayerlist.obj)

            self.respn = '['
            if _range > 0:
                _size = config.recentplayer['numlist'];
                if _range < _size:
                    _size = _range
                random = Utils.GetRandomOfNumberInArray(self, _size, _range)
                for i in random:
                    recentplayer = recentplayerlist.obj[i]
                    if recentplayer['uuid'] != player.uuid:
                        self.respn += '{"fbid":"'+recentplayer['fbid']+'",'
                        self.respn += '"uuid":"'+recentplayer['uuid']+'",'
                        self.respn += '"name":"'+recentplayer['name']+'",'
                        self.respn += '"image":"'+recentplayer['image']+'",'
                        self.respn += '"total_wins":'+str(recentplayer['total_wins'])+','
                        self.respn += '"updated":'+str(recentplayer['updated'])+'},'
            self.respn = self.respn.rstrip(',') + ']'

        # calculate time taken and return result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
    def get(self):
        Utils.reset(self)
        uuid = Utils.required(self, 'uuid')
        version = config.data_version['building']
        if self.request.get('version'):
            version = self.request.get('version')
        lang = config.server["defaultLanguage"]
        if self.request.get('lang'):
            lang = self.request.get('lang')
        track = 'track.1'
        if self.request.get('track'):
            lang = self.request.get('track')
        score = 0
        if self.request.get('score'):
            lang = self.request.get('score')

        uuid = self.request.get('uuid')

        start_time = time.time()
        # find the right track in buildings and add the score total to it for collection

        player = Player.getplayer(self, uuid)

        # get all buildings types
        buildings = Data.getbuildings(self, lang, version)

        # get player buildings
        mybuildings = Building.getmybuildings(self, uuid)

        #find the building with the track id and give it cash
        if buildings is not None and mybuildings is not None:
            self.respn += '"building":['
            for mybuilding in mybuildings:
                _upd = False
                # for example:  "itid": "track.1",
                if mybuilding.itid == track:
                    mybuilding.amount += score
                    Building.setmybuilding(self, mybuilding)
                self.respn = Building.compose_mybuilding(
                    self.respn, mybuilding)
            self.respn = self.respn.rstrip(',') + '],'

        if self.error == '':
            self.respn = '{"state":' + player.state + ', "building":['
            self.respn = Building.compose_mybuilding(self.respn, mybuilding)
            self.respn = self.respn.rstrip(',') + ']'
            self.respn += '}'

        # calculate time taken and return the result
        time_taken = time.time() - start_time

        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
    def get(self):
        Utils.reset(self)  # reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')
        version = config.data_version['building']
        if self.request.get('version'):
            version = self.request.get('version')
        lang = config.server["defaultLanguage"]
        if self.request.get('lang'):
            lang = self.request.get('lang')
        checklist = self.request.get('checklist')

        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()  # start count

        # logic variables
        player = None

        # if error, skip this
        if self.error == '':
            player = Player.getplayer(self, uuid)

        if self.error == '' and player is not None and guid != '':
            logging.info(guid + '==' + player.state_obj['guid'])
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        if self.error == '' and player is not None:
            if checklist:
                player.state_obj['advice_checklist'] = checklist

            # update timestamp for player
            player.state_obj['updated'] = start_time
            Player.setplayer(self, player)

            self.respn = '{"advice_checklist_saved":"true"}'

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
Exemple #6
0
    def get(self):
        Utils.reset(self)														# reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')
        chid = Utils.required(self, 'chid')

        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()												# start count

        Utils.LogRequest(self)
        # logic variables
        player = None

        # if error, skip this
        if self.error == '':
            player = Player.getplayer(self, uuid)

        if self.error == '' and player is not None and guid != '':
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        if self.error == '' and player is not None:
            challenge = Challenge.GetChallenge(self, chid)
            if challenge is not None:
                if player.fbid == challenge.uid1 or player.fbid == challenge.uid2 or player.uuid == challenge.uid1 or player.uuid == challenge.uid2:
                    self.respn = '{'
                    Challenge.ComposeActualChallenge(self, challenge)
                    self.respn = self.respn.rstrip(',') + '}'
                else:
                    self.error = 'You don\'t have permission to access data of this challenge.'

            # update timestamp for player
            player.state_obj['updated'] = start_time
            Player.setplayer(self, player)

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken,False))
Exemple #7
0
    def get(self):
        Utils.reset(self)  # reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, GCVars.passwd)
        guid = self.request.get('guid')
        uuid = Utils.required(self, 'uuid')
        key = Utils.required(self, 'key')
        val = Utils.required(self, 'val')

        Utils.LogRequest(self)
        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()  # start count

        # if error, skip this
        if self.error != '' or self.error is None:
            player = Player.getplayer(self, uuid)

            if player is not None and guid != '':
                if guid != player.state_obj['guid']:
                    player = None
                    self.error = config.error_message['dup_login']

        if player is not None:
            data = {}
            if player.state_obj.has_key('data'):
                data = json.loads(player.state_obj['data'])

            data.setdefault(key, val)

            player.state_obj.setdefault('data', json.dumps(data))

            Player.setplayer(self, player)
            self.respn = '{"state":' + player.state + '}'

        else:
            self.error = 'Cant find a player for ' + uuid

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
    def get(self):
        Utils.reset(self)														# reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        version = config.data_version['building']
        if self.request.get('version'):
            version = self.request.get('version')
        lang = config.server["defaultLanguage"]
        if self.request.get('lang'):
            lang = self.request.get('lang')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')

        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()												# start count

        # logical variables
        player = None
        mycars = None

        # if error, skip this
        if self.error == '':
            player = Player.getplayer(self, uuid)

        if self.error == '' and player is not None and guid != '':
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        if self.error == '' and player is not None:
            mycars = Car.list(self, uuid)
            self.respn = '['
            for _car in mycars:
                self.respn += Car.compose_mycar('', _car) + ','
            self.respn = self.respn.rstrip(',') + ']'

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
Exemple #9
0
    def get(self):
        Utils.reset(self)  # reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')

        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()  # start count

        # logic variables
        player = None

        # if error, skip this
        if self.error == '':
            player = Player.getplayer(self, uuid)

        if self.error == '' and player is not None and guid != '':
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        if self.error == '' and player is not None:
            self.respn = '{'
            Challenge.ComposeChallenges(self, player)
            self.respn = self.respn.rstrip(',') + '}'

            # update timestamp for player
            player.state_obj['updated'] = start_time
            Player.setplayer(self, player)

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
Exemple #10
0
    def get(self):
        Utils.reset(self)  # reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')
        token = Utils.required(self, 'token')

        # required password to process this action
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()  # start count

        # if any error, skip this
        if self.error == '':
            player = Player.getplayer(self, uuid)  # get player as object

        if self.error == '' and player is not None and guid != '':
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        # if any error on player is none
        if self.error == '' and player is not None:
            player.info_obj['token'] = token
            # update timestamp for player
            player.state_obj['updated'] = start_time
            if Player.setplayer(self, player):
                Player.compose_player_info(self, player)
            else:
                self.error = 'unable to update player data (token).'

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
Exemple #11
0
    def get(self):
        Utils.reset(self)                                                        # reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        version = config.data_version['building']
        if self.request.get('version'):
            version = self.request.get('version')
        lang = config.server["defaultLanguage"]
        if self.request.get('lang'):
            lang = self.request.get('lang')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')
        inid = Utils.required(self, 'inid')
        amount = Utils.required(self, 'amount')

        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        Utils.LogRequest(self)

        start_time = time.time()                                                # start count

        # logic variables
        player = None
        buildings = None
        mybuilding = None
        res_produced = 0

        # if error, skip this
        if self.error == '':
            player = Player.getplayer(self, uuid)
        """
        if self.error == '' and player is not None and guid != '':
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']
        """
        if self.error == '' and player is not None:
            buildings = Data.getbuildings(self, lang, version)

        if self.error == '' and buildings is not None:
            mybuilding = Building.getmybuilding(self, uuid, inid)

        if self.error == '' and mybuilding is not None:
            _upd = False
            if mybuilding.status == Building.BuildingStatus.PENDING:
                if mybuilding.timestamp + (
                        buildings.as_obj[mybuilding.itid][mybuilding.level - 1]['build_time'] * 60) <= start_time:
                    mybuilding.timestamp = int(start_time)
                    mybuilding.status = Building.BuildingStatus.DELIVERED
                    _upd = True
            elif mybuilding.status == Building.BuildingStatus.DELIVERED:
                mybuilding.status = Building.BuildingStatus.OWNED
                _upd = True

            if mybuilding.status == Building.BuildingStatus.DELIVERED or mybuilding.status == Building.BuildingStatus.OWNED:
                time_delta = (start_time - mybuilding.timestamp) / 60
                if time_delta > buildings.as_obj[mybuilding.itid][mybuilding.level - 1]['resource_interval'] > 0:
                    #mybuilding.status = Building.BuildingStatus.PRODUCED_PARTIAL
                    #_upd = True
                    res_produced = int(
                        time_delta / buildings.as_obj[mybuilding.itid][mybuilding.level - 1]['resource_interval']) * buildings.as_obj[mybuilding.itid][mybuilding.level - 1]['resource_produced']
                    if res_produced >= buildings.as_obj[mybuilding.itid][mybuilding.level - 1]['resource_capacity']:
                        res_produced = buildings.as_obj[mybuilding.itid][mybuilding.level - 1]['resource_capacity']
                        ##mybuilding.status = Building.BuildingStatus.PRODUCED
                        #_upd = True
            elif mybuilding.status == Building.BuildingStatus.PRODUCED_PARTIAL or mybuilding.status == Building.BuildingStatus.PRODUCED:
                if mybuilding.amount is None:
                    mybuilding.amount = 0;
                res_produced = mybuilding.amount
                mybuilding.amount = 0
                mybuilding.status = Building.BuildingStatus.OWNED
                _upd = True

            if res_produced > 0:
                if res_produced > amount:
                    res_produced = amount
                try:
                    # eg player['cash'] += 1
                    resource_type = buildings.as_obj[mybuilding.itid][mybuilding.level - 1]['resource']
                    _upd = True
                    new_amount = int(res_produced) + int(mybuilding.amount)
                    logging.debug('resource to collect = ' + str(res_produced) + " " + str(resource_type) + " = " + str(new_amount))
                    logging.debug('building contains = ' + str(res_produced))

                    player.state_obj[
                        buildings.as_obj[mybuilding.itid][mybuilding.level - 1]['resource']] += new_amount
                    # update timestamp for player
                    player.state_obj['updated'] = start_time
                    if Player.setplayer(self, player):
                        #mybuilding.status = Building.BuildingStatus.OWNED
                        mybuilding.timestamp = int(start_time)
                        _upd = True
                except KeyError:
                    self.error = 'resource=' + buildings.as_obj[mybuilding.itid][mybuilding.level - 1][
                        'resource'] + ' doesn\'t exist in player properties!'

            if _upd is True:
                Building.setmybuilding(self, mybuilding)

            if self.error == '':
                self.respn = '{"state":' + player.state + ', "building":['
                self.respn = Building.compose_mybuilding(self.respn, mybuilding)
                self.respn = self.respn.rstrip(',') + ']'
                self.respn += '}'

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
Exemple #12
0
    def get(self):
        Utils.reset(self)														# reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        version = config.data_version['building']
        if self.request.get('version'):
            version = self.request.get('version')
        lang = config.server["defaultLanguage"]
        if self.request.get('lang'):
            lang = self.request.get('lang')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')
        inid = Utils.required(self, 'inid')

        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()												# start count

        # logical variables
        player = None
        buildings = None
        building = None
        mybuilding = None

        # if error, skip this
        if self.error == '':
            player = Player.getplayer(self, uuid)

        if self.error == '' and player is not None and guid != '':
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        if self.error == '' and player is not None:
            buildings = Data.getbuildings(self, lang, float(version))

        if self.error == '' and buildings is not None:
            mybuilding = Building.getmybuilding(self, uuid, inid)

        if self.error == '' and mybuilding is not None:
            if mybuilding.status != Building.BuildingStatus.PENDING:
                try:
                    if len(buildings.as_obj[mybuilding.itid]) > mybuilding.level:
                        building = buildings.as_obj[mybuilding.itid][mybuilding.level]
                    else:
                        self.error = 'Level '+str(mybuilding.level+1)+' of building='+mybuilding.itid+' does not exist!'
                except KeyError:
                    self.error = 'Building='+mybuilding.itid+' does not exist!'
            else:
                self.respn = '{"warning":"Building='+inid+' still under construction, cannot upgrade at the moment!"}'

        if self.error == '' and self.respn == '' and building is not None:
            self.respn = str(building['cost'])
            if player.state_obj['cash'] >= building['cost']:
                player.state_obj['cash'] -= building['cost']
                # update timestamp for player
                player.state_obj['updated'] = start_time
                if Player.setplayer(self, player):
                    mybuilding.itid = building['id']
                    mybuilding.status = Building.BuildingStatus.PENDING
                    mybuilding.level = building['level']
                    mybuilding.timestamp = int(start_time)
                    Building.setmybuilding(self, mybuilding)
                    self.respn = '{"state":'+player.state+','
                    self.respn += '"building":['
                    self.respn = Building.compose_mybuilding(self.respn, mybuilding)
                    self.respn = self.respn.rstrip(',') + ']'
                    self.respn += '}'
            else:
                self.respn = '{"warning":"not enough cash!"}'



        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
Exemple #13
0
    def get(self):
        Utils.reset(self)  # reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        version = config.data_version['building']
        if self.request.get('version'):
            version = self.request.get('version')
        lang = config.server["defaultLanguage"]
        if self.request.get('lang'):
            lang = self.request.get('lang')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')

        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()  # start count

        # logical variables
        player = None
        buildings = None
        mybuildings = None

        # if error, skip this
        if self.error == '':
            player = Player.getplayer(self, uuid)

        if self.error == '' and player is not None and guid != '':
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        if self.error == '' and player is not None:
            buildings = Data.getbuildings(self, lang, version)

        if self.error == '' and buildings is not None:
            mybuildings = Building.getmybuildings(self, uuid)

        if self.error == '' and mybuildings is not None:
            self.respn = '['
            for mybuilding in mybuildings:
                # update building status, determine production
                _upd = False
                if mybuilding.status == Building.BuildingStatus.PENDING:
                    if mybuilding.timestamp + (
                            buildings.as_obj[mybuilding.itid][
                                mybuilding.level - 1]['build_time'] *
                            60) <= start_time:
                        mybuilding.timestamp = int(start_time)
                        mybuilding.status = Building.BuildingStatus.DELIVERED
                        _upd = True
                elif mybuilding.status == Building.BuildingStatus.DELIVERED:
                    mybuilding.status = Building.BuildingStatus.OWNED
                    _upd = True
                if _upd is True:
                    Building.setmybuilding(self, mybuilding)
                self.respn = Building.compose_mybuilding(
                    self.respn, mybuilding)
            self.respn = self.respn.rstrip(',') + ']'

            # update timestamp for player
            player.state_obj['updated'] = start_time
            Player.setplayer(self, player)

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
Exemple #14
0
    def get(self):

        Utils.reset(self)  # reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')

        uuid = self.request.get('uuid')
        guid = self.request.get('guid')
        fbid = self.request.get('fbid')
        self.game = self.request.get('game') or ''

        version = config.data_version['building']

        token = self.request.get('token') or ''
        lang = self.request.get('lang') or config.server["defaultLanguage"]

        name = self.request.get('name') or ''

        image = 'Textures/profile-pic.png'
        if fbid != '':
            image = 'https://graph.facebook.com/' + fbid + '/picture?width=200&height=200'

        # TODO : Get defaults from Data
        gold = 10
        cash = 50000
        total_wins = 0
        total_races = 0
        advice_checklist = ''

        player = None
        # defaultitems = None

        if self.error == '' and passwd != config.testing[
                'passwd']:  # if password is incorrect
            self.error = 'passwd is incorrect.'  # inform user via error message

        start_time = time.time()  # start count

        Utils.LogRequest(self)

        # if error, skip this
        if self.error == '':
            if fbid != '':
                player = Player.getplayerByFbid(self, fbid)

            if player is None and uuid != '':
                player = Player.getplayer(self,
                                          uuid)  # get player from Player model
                # class helper, specified by uuid

            # TODO : Only get defaultItems if needed, ie a new player
            defaultitems = Data.getDataAsObj(
                self, 'defaultitems', config.data_version['defaultitems'])
            if defaultitems is not None:

                if player is None:  # if no player data
                    # returned or doesn't exist
                    ################################################################################################
                    ## Create new player data
                    player = Player(parent=db.Key.from_path(
                        'Player', config.db['playerdb_name'])
                                    )  # create a new player state data
                    uuid = Utils.genanyid(self, 'u')
                    #if fbid == '':
                    #    fbid = uuid
                    player.uuid = uuid  # assign uuid
                    player.fbid = fbid
                    # and assign all player info and state
                    player.info_obj = {
                        'uuid': player.uuid,
                        'fbid': player.fbid,
                        'token': token,
                        'name': 'Guest ' + str(random.randint(1000, 9999)),
                        'image': image,
                        'lang': lang
                    }
                    player.state_obj = {
                        'guid': guid,
                        'cash': cash,
                        'gold': gold,
                        'current_car': 'xxx',
                        'total_wins': total_wins,
                        'total_races': total_races,
                        'advice_checklist': advice_checklist,
                        'updated': start_time
                    }

                    logging.debug("New Player Created")

                    #################################################################################################
                    ## Init default item for new player
                    buildings = Data.getbuildings(self, lang, float(version))
                    cars = Data.getcars(self, lang, float(version))
                    upgrades = Data.getupgrades(self, lang, float(version))

                    if buildings is not None and cars is not None and upgrades is not None:
                        logging.debug("building default stuff")
                        for item in defaultitems.obj:
                            if item['type'] == 'state':
                                player.state_obj[item['id']] = item['value']
                            elif item['type'] == 'building':
                                try:
                                    building = buildings.as_obj[item['id']][0]
                                    if building is not None:
                                        new_building = Building.newbuilding(
                                            self)
                                        new_building.uuid = player.uuid
                                        new_building.itid = item['id']
                                        new_building.inid = Utils.genanyid(
                                            self, 'b')
                                        new_building.level = building['level']
                                        new_building.status = Building.BuildingStatus.DELIVERED
                                        new_building.location = item['value']
                                        new_building.amount = 0
                                        new_building.timestamp = int(
                                            start_time)
                                        Building.setmybuilding(
                                            self, new_building)
                                except KeyError:
                                    logging.warning('KeyError, key not found!')

                            elif item['type'] == 'car' and cars is not None:
                                type = ''
                                car = None
                                for _car in cars.as_obj:
                                    if _car['id'] == item['id']:
                                        car = _car
                                        break
                                mycar = Car.create(self, player.uuid)
                                mycar.data_obj['info'] = {'crid': car['id']}
                                mycar.data_obj['upgrades'] = []
                                mycar.data_obj['equip'] = {}
                                player.state_obj['current_car'] = mycar.cuid
                                default_upgrades = car[
                                    'default_upgrades'].replace(' ',
                                                                '').split(',')
                                for default_upgrade in default_upgrades:
                                    mycar.data_obj['upgrades'].append(
                                        default_upgrade)

                                    for _type in upgrades.as_obj:
                                        try:
                                            mycar.data_obj['equip'][type]
                                        except KeyError:
                                            for upgrade in upgrades.as_obj[
                                                    _type]:
                                                if upgrade[
                                                        'id'] == default_upgrade:
                                                    mycar.data_obj['equip'][
                                                        _type] = default_upgrade
                                                    break
                                                    break
                                Car.update(self, mycar)

                        else:
                            logging.warning("cant build default stuff")

                else:  # but if player does exist
                    #####################################################################################################################
                    ## Found existing user
                    uuid = player.uuid
                    if token:  # if token is provided from
                        # apple
                        player.state_obj[
                            'token'] = token  # assign token to player state
                    if fbid != '':
                        player.fbid = fbid
                        player.info_obj['fbid'] = fbid
                        player.info_obj['image'] = image  # assign image url
                    if name != '':
                        player.info_obj['name'] = name  # assign name
                    try:
                        updated = player.state_obj['updated']
                    except KeyError:
                        player.state_obj['updated'] = start_time

                    if self.request.get('lang'):
                        player.info_obj['lang'] = lang

                    # Additional things that have been added and neeed checking for old players
                    # TODO : Remove try catch, or see performance impact in Python
                    try:
                        if guid:
                            player.state_obj['guid'] = guid
                    except KeyError:
                        player.state_obj['guid'] = ''

                    # try .. cash and assign new property
                    try:
                        cash = player.state_obj['cash']
                    except KeyError:
                        player.state_obj['cash'] = cash

                    try:
                        total_wins = player.state_obj['total_wins']
                    except KeyError:
                        player.state_obj['total_wins'] = total_wins
                    try:
                        advice_checklist = player.state_obj['advice_checklist']
                    except KeyError:
                        player.state_obj['advice_checklist'] = advice_checklist

                if Player.setplayer(self, player):
                    # then obviously, no error
                    # compose JSON for frontend response
                    type = ''
                    for item in config.playerdata:
                        type += item + ','
                    type = type.rstrip(',')
                    self.respn = '{"uuid":"' + uuid + '",'
                    types = type.split(',')
                    for item in types:
                        if item == 'info':
                            self.respn += '"info":' + player.info + ','
                        elif item == 'state':
                            self.respn += '"state":' + player.state + ','
                        elif item == 'building':
                            buildings = Data.getbuildings(self, lang, version)
                            mybuildings = Building.getmybuildings(self, uuid)
                            if buildings is not None and mybuildings is not None:
                                self.respn += '"building":['
                                # loop through my buildings to find out which need their pending status updating
                                for new_building in mybuildings:
                                    # update building status, determine production
                                    _upd = False
                                    if new_building.status == Building.BuildingStatus.PENDING:
                                        if new_building.timestamp + (
                                                buildings.as_obj[
                                                    new_building.itid][
                                                        new_building.level - 1]
                                            ['build_time'] * 60) <= start_time:
                                            new_building.timestamp = int(
                                                start_time)
                                            new_building.status = Building.BuildingStatus.DELIVERED
                                            _upd = True
                                    elif new_building.status == Building.BuildingStatus.DELIVERED:
                                        new_building.status = Building.BuildingStatus.OWNED
                                        _upd = True
                                    if _upd is True:
                                        Building.setmybuilding(
                                            self, new_building)
                                    self.respn = Building.compose_mybuilding(
                                        self.respn, new_building)
                                self.respn = self.respn.rstrip(',') + '],'
                        elif item == 'car':
                            mycars = Car.list(self, player.uuid)
                            self.respn += '"car":['
                            for _car in mycars:
                                self.respn += Car.compose_mycar('', _car) + ','
                            self.respn = self.respn.rstrip(',') + '],'
                        elif item == 'challenge':
                            Challenge.ComposeChallenges(self, player)

                    self.respn = self.respn.rstrip(',') + '}'

                    ###################################################################################################
                    ## Add to recent player list
                    recentplayerlist = Data.GetRecentPlayerList(self)
                    _add = True

                    # check if this user hasn't reached the maximum set challengers
                    # we don't add players to the recent list if they are stacked
                    num = 0
                    challengers = Challenge.GetChallengers(
                        self, player.info_obj['uuid'])
                    if challengers is None:
                        Challenge.GetChallengers(self, player.info_obj['fbid'])
                    if challengers is not None:
                        for challenger in challengers:
                            obj = json.loads(challenger.data)
                            if obj['friend'] is False:
                                num += 1
                                if num > config.recentplayer['maxchallengers']:
                                    logging.warn(
                                        'Recent player list exceeded for ' +
                                        uuid)
                                    _add = False
                                    break

                    # find if it already exists?
                    num = 0
                    _deletelist = []
                    for recentplayer in recentplayerlist.obj:

                        if recentplayer['uuid'] == player.info_obj['uuid']:
                            if _add is False:  # this player reach the maximum of challengers
                                _deletelist.append(
                                    num
                                )  # we should delete him from the list, so nobody can challenge him
                            else:
                                _add = False

                        # if the list is longer than maxlist, delete the rest
                        if num >= config.recentplayer['maxlist']:
                            _deletelist.append(num)

                        # remove if player does not exist any more
                        else:
                            someplayer = Player.getplayer(
                                self, recentplayer['uuid'])
                            if someplayer is None:
                                self.error = ''
                                _deletelist.append(num)
                        num += 1

                    num = len(_deletelist)
                    for i in range(0, num):
                        del recentplayerlist.obj[num - 1 - i]

                    if _add is True:
                        recentplayerlist.obj.append({
                            'fbid':
                            player.info_obj['fbid'],
                            'name':
                            player.info_obj['name'],
                            'uuid':
                            player.info_obj['uuid'],
                            'image':
                            player.info_obj['image'],
                            'total_wins':
                            player.state_obj['total_wins'],
                            'updated':
                            player.state_obj['updated']
                        })

                    Data.SetRecentPlayerList(self, recentplayerlist)

                else:  # but if write down to database was failed
                    self.error = 'unable to insert/update player data.'  # inform user bia error message
                    logging.warn('unable to insert/update player data.')

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
    def get(self):
        Utils.reset(self)  # reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        version = config.data_version['building']
        if self.request.get('version'):
            version = self.request.get('version')
        lang = config.server["defaultLanguage"]
        if self.request.get('lang'):
            lang = self.request.get('lang')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')
        cuid = Utils.required(self, 'cuid')
        upid = Utils.required(self, 'upid')

        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()  # start count

        # logical variables
        player = None
        upgrades = None
        upgrade = None
        mycar = None
        qualify = False

        # if error, skip this
        if self.error == '':
            player = Player.getplayer(self, uuid)

        if self.error == '' and player is not None and guid != '':
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        if self.error == '' and player is not None:
            mycar = Car.get(self, cuid)

        if self.error == '' and mycar is not None:
            upgrades = Data.getupgrades(self, lang, version)

        if self.error == '' and upgrades is not None:
            found = False
            for _type in upgrades.as_obj:
                for _upgrade in upgrades.as_obj[_type]:
                    if _upgrade['id'] == upid:
                        upgrade = _upgrade
                        found = True
                        break
            if found is False:
                self.error = 'Upgrade id=' + upid + ' was not found.'

        if self.error == '' and upgrade is not None:

            # validate existing upgrade
            already_have = False
            for _upgrade in mycar.data_obj['upgrades']:
                if _upgrade == upid:
                    already_have = True

            # validate building
            buildings = Building.list(self, player.uuid)
            for building in buildings:
                if building.itid == upgrade[
                        'shop'] and building.level >= upgrade['shop_level']:
                    qualify = True
                    break
            if qualify is False:
                self.respn = '{"warning":' + GCWarnings.building_not_owned + '}'

        if self.error == '' and qualify is True:
            # validate cash
            if already_have is False:  # then you need to buy it, dude!
                if player.state_obj['cash'] >= upgrade['cost']:
                    player.state_obj['cash'] -= upgrade['cost']
                    player.state_obj['updated'] = start_time
                    if Player.setplayer(self, player):
                        mycar.data_obj['upgrades'].append(upgrade['id'])
                else:
                    self.respn = '{"warning":"not enough cash!"}'
                    qualify = False

        if self.error == '' and qualify is True:
            mycar.data_obj['equip'][upgrade['type']] = upgrade['id']
            if Car.update(self, mycar):
                self.respn = '{"state":' + player.state + ','
                self.respn += '"car":['
                self.respn += Car.compose_mycar('', mycar) + ','
                self.respn = self.respn.rstrip(',') + ']'
                self.respn += '}'

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
Exemple #16
0
    def get(self):
        Utils.reset(self)  # reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        version = config.data_version['building']
        if self.request.get('version'):
            version = self.request.get('version')
        lang = config.server["defaultLanguage"]
        if self.request.get('lang'):
            lang = self.request.get('lang')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')
        crid = Utils.required(self, 'crid')

        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()  # start count

        # logical variables
        player = None
        cars = None
        upgrades = None
        car = None
        #mycars = None

        Utils.LogRequest(self)

        # if error, skip this
        if self.error == '':
            player = Player.getplayer(self, uuid)

        if self.error == '' and player is not None and guid != '':
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        if self.error == '' and player is not None:
            cars = Data.getcars(self, lang, float(version))

        if self.error == '' and cars is not None:
            found = False
            for _car in cars.as_obj:
                if _car['id'] == crid:
                    car = _car
                    found = True
                    break
            if found is False:
                self.error = crid + " was not found!"

        if self.error == '' and car is not None:

            mycars = Car.list(self, uuid)
            for _car in mycars:
                data_obj = json.loads(_car.data)
                try:
                    if data_obj['info']['crid'] == crid:
                        # already own this car type, and you can only 1 of each type
                        #self.respn = '{"warning":"You have already purchased this car."}'
                        player.state_obj['current_car'] = _car.cuid
                        player.state_obj['updated'] = start_time
                        if Player.setplayer(self, player):
                            self.respn = '{"state":' + player.state + ','
                            self.respn += '"car":['
                            self.respn = Car.compose_mycar(self.respn, _car)
                            self.respn = self.respn.rstrip(',') + ']'
                            self.respn += '}'
                            car = None
                        break
                except KeyError:
                    self.error = 'Cannot find crid (KeyError issue), please report admin!'

        if self.error == '' and car is not None:
            upgrades = Data.getupgrades(self, lang, float(version))

        if self.error == '' and upgrades is not None:
            # good to go as we have a car
            if player.state_obj['cash'] >= car['cost']:
                player.state_obj['cash'] -= car['cost']
                player.state_obj[
                    'updated'] = start_time  # update timestamp for player

                mycar = Car.create(self, player.uuid)
                mycar.data_obj['info'] = {'crid': car['id']}
                mycar.data_obj['upgrades'] = []
                mycar.data_obj['equip'] = {}
                player.state_obj['current_car'] = mycar.cuid
                default_upgrades = car['default_upgrades'].replace(
                    ' ', '').split(',')

                for default_upgrade in default_upgrades:
                    mycar.data_obj['upgrades'].append(default_upgrade)
                    for _type in upgrades.as_obj:
                        try:
                            mycar.data_obj['equip'][type]
                        except KeyError:
                            for upgrade in upgrades.as_obj[_type]:
                                if upgrade['id'] == default_upgrade:
                                    mycar.data_obj['equip'][
                                        _type] = default_upgrade
                                    break
                                    break

                player.state = json.dumps(player.state_obj)
                if Player.setplayer(self, player):
                    if Car.update(self, mycar):
                        self.respn = '{"state":' + player.state + ','
                        self.respn += '"car":['
                        self.respn = Car.compose_mycar(self.respn, mycar)
                        self.respn = self.respn.rstrip(',') + ']'
                        self.respn += '}'

            else:
                self.respn = '{"warning":"not enough cash!"}'
                logging.warn("not enough cash")
        else:
            logging.warn("Error with car upgrades")
        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
Exemple #17
0
    def Update(self, chid, type, uid, laptime, replay, events, cardata, name,
               image, lang, version):
        """ Parameters:
            chid - Challenge Id
            type - type of update, 'CHALLENGE' or 'ACCEPT'
            uid - user id, could be fbid or uuid
            replay - racing data
            score - button replay
        """
        my_building = None
        logging.debug("Challenge Update with replay length " +
                      str(len(replay)))
        challenge = memcache.get(config.db['challengedb_name'] + '.' + chid)

        if challenge is None:
            logging.debug("Challenge not found in memcache")
            challenges = Challenge.all().filter('id =', chid) \
                .filter('state !=', CHALLENGE_TYPE.BOTH_PLAYERS_FINISH) \
                .filter('state !=', CHALLENGE_TYPE.GAME_OVER) \
                .ancestor(db.Key.from_path('Challenge',config.db['challengedb_name'])) \
                .fetch(1)

            if len(challenges) > 0:
                challenge = challenges[0]
                logging.debug("Challenge found in data")
                if not memcache.add(config.db['challengedb_name'] + '.' + chid,
                                    challenge, config.memcache['holdtime']):
                    logging.warning(
                        'Challenge - Set memcache for challenge by Id failed (Update)!'
                    )

        if challenge is not None:
            logging.debug("Challenge is not none")
            #logging.debug("challenge update :" + challenge.data)
            #TODO: remove the replay data from the .data to prevent it being serialzed and back
            game = json.loads(challenge.data)
            _upd = False
            if challenge.state != CHALLENGE_TYPE.BOTH_PLAYERS_FINISH and challenge.state != CHALLENGE_TYPE.GAME_OVER:
                logging.info("challenge not over. state = " + challenge.state +
                             " type = " + type)

                start_time = time.time()
                # flag to prevent Player saving outside this function and loosing the changes
                challenge.manual_update = False

                #CHALLENGE_TYPE
                _player = 'player1'
                if type != CHALLENGE_MODE.CHALLENGE:
                    _player = 'player2'

                logging.info("updating _player " + _player)

                # find the key in the challenge data for the correct player and update the new state
                game[_player] = {
                    'player': {
                        'id': uid
                    },
                    'laptime': float(laptime),
                    'replay': replay,
                    'events': events,
                    'created': start_time,
                    'cardata': cardata,
                    'name': name,
                    'image': image
                }

                # update challenge state by looking at participants
                if not 'replay' in game['player1'] and not 'replay' in game[
                        'player2']:
                    challenge.state = CHALLENGE_TYPE.OPEN_GAME
                elif 'replay' in game['player1']:
                    challenge.state = CHALLENGE_TYPE.PLAYER1_FINISH
                elif 'replay' in game['player2']:
                    challenge.state = CHALLENGE_TYPE.PLAYER2_FINISH

                logging.info("challenge updating. state = " + challenge.state +
                             " type = " + type)

                # see if we can finish the challenge
                if game['player1'] is not None and game['player2'] is not None:
                    if 'replay' in game['player1'] and 'replay' in game[
                            'player2']:
                        challenge.state = CHALLENGE_TYPE.BOTH_PLAYERS_FINISH

                        # Update players with earnings
                        player1 = None
                        player2 = None
                        opponents = None
                        racewinnings = None
                        winner = 'draw'

                        player1 = Player.getplayerByFbid(self, challenge.uid1)
                        if player1 is None:
                            player1 = Player.getplayer(self, challenge.uid1)

                        if player1 is not None:
                            player2 = Player.getplayerByFbid(
                                self, challenge.uid2)
                            if player2 is None:
                                player2 = Player.getplayer(
                                    self, challenge.uid2)

                        if player2 is not None:
                            racewinnings = Data.getDataAsObj(
                                self, 'racewinnings',
                                config.data_version['racewinnings'])

                        if racewinnings is not None:
                            opponents = Data.getDataAsObj(
                                self, 'opponent_en',
                                config.data_version['opponent'])

                        # everything is good - we have 2 player models and the winnings data
                        if opponents is not None:
                            prize1 = 0
                            prize2 = 0

                            # only use the first one for multiplayer challenges
                            win_prize = opponents.obj[
                                challenge.track][0]['win_prize']
                            lose_prize = opponents.obj[
                                challenge.track][0]['lose_prize']

                            if game['player1']['laptime'] < game['player2'][
                                    'laptime']:  # player1 wins
                                winner = player1.uuid
                                prize1 = win_prize
                                prize2 = lose_prize
                                player1.state_obj['total_wins'] += 1
                            elif game['player1']['laptime'] > game['player2'][
                                    'laptime']:
                                winner = player2.uuid
                                prize1 = lose_prize
                                prize2 = win_prize
                                player2.state_obj['total_wins'] += 1
                            else:
                                winner = 'draw'
                                prize1 = lose_prize
                                prize2 = lose_prize
                            """
                            player2.state_obj['cash'] += prize1
                            player2.state_obj['cash'] += prize2
                            """

                            player1_building = Building.save_resource_to_building(
                                self, lang, version, player1.uuid,
                                challenge.track, prize1)
                            player2_building = Building.save_resource_to_building(
                                self, lang, version, player2.uuid,
                                challenge.track, prize2)

                            if uid == challenge.uid1:
                                my_building = player1_building
                            else:
                                player2.info_obj['updated'] = start_time
                                my_building = player2_building

                            if Player.setplayer(self, player2):
                                logging.info('player2 saved')

                            player1.state_obj['total_races'] += 1
                            player2.state_obj['total_races'] += 1

                            game['result'] = {
                                'winner': winner,
                                'player1': challenge.uid1,
                                'player2': challenge.uid2,
                                'player1_prize': prize1,
                                'player2_prize': prize2,
                                'player1_seen': uid == challenge.uid1,
                                'player2_seen': uid == challenge.uid2,
                                'player1_laptime': game['player1']['laptime'],
                                'player2_laptime': game['player2']['laptime']
                            }

                _upd = True

            # this can't be used - the player cannot do a challengeUpdate unless they finish a race?
            elif game['result']['player1_seen'] is False or game['result'][
                    'player2_seen'] is False:
                if uid == challenge.uid1:
                    game['result']['player1_seen'] = True
                    _upd = True
                if uid == challenge.uid2:
                    game['result']['player2_seen'] = True
                    _upd = True

                challenge.manual_update = True

            if game['result']['player1_seen'] and game['result'][
                    'player2_seen']:
                challenge.state = CHALLENGE_TYPE.GAME_OVER

            logging.debug("Update finished with state " + challenge.state +
                          " type = " + type)
            if _upd is True:
                challenge.data = json.dumps(game)
                if challenge.put():
                    # TODO : memcache replace
                    memcache.delete(config.db['challengedb_name'] + '.' +
                                    challenge.id)
                    if not memcache.add(
                            config.db['challengedb_name'] + '.' + challenge.id,
                            challenge):
                        logging.warning(
                            'Challenge - Set memcache for challenge by Id failed!'
                        )
                        self.error += 'Challenge saving failed :('
                else:
                    self.error += 'Challengeupdate failed :('

        else:
            self.error = 'Challenge ID=' + chid + ' could not be found.'
            logging.debug(self.error)

        return challenge, my_building
Exemple #18
0
    def get(self):
        # reset/clean standard variables
        Utils.reset(self)

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        version = config.data_version['building']
        if self.request.get('version'):
            version = self.request.get('version')
        lang = config.server["defaultLanguage"]
        if self.request.get('lang'):
            lang = self.request.get('lang')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')
        inid = Utils.required(self, 'inid')

        # start count
        start_time = time.time()

        # set default parameters
        player = None
        buildings = None
        mybuilding = None
        economy = None

        # if error, skip this
        if self.error == '':
            player = Player.getplayer(self, uuid)

        if self.error == '' and player is not None and guid != '':
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        # if error or player is not, then skip to the end
        if self.error == '' and player is not None:
            buildings = Data.getbuildings(self, lang, version)

        if self.error == '' and buildings is not None:
            mybuilding = Building.getmybuilding(self, uuid, inid)

        # if any error or mybuilding is none, then skip to the end
        if self.error == '' and mybuilding is not None:
            if mybuilding.status != Building.BuildingStatus.PENDING:
                self.respn = '{"warning":"building=' + inid + ' has been finished."}'
            else:
                economy = Data.getDataAsObj(self, 'economy',
                                            config.data_version['economy'])

        if self.error == '' and self.respn == '' and economy is not None:
            _upd = False
            time_left = buildings.as_obj[mybuilding.itid][
                mybuilding.level - 1]['build_time'] - int(
                    (start_time - mybuilding.timestamp) / 60)
            if mybuilding.status == Building.BuildingStatus.PENDING:
                if time_left > 0:
                    sele = economy.obj[0]
                    for list in economy.obj:
                        if time_left >= list['time_in_minutes']:
                            sele = list
                        else:
                            break

                    if player.state_obj['gold'] >= sele['gold_value']:
                        player.state_obj['gold'] -= sele['gold_value']
                        mybuilding.status = Building.BuildingStatus.DELIVERED
                        _upd = True

                        player.state_obj['updated'] = start_time
                        Player.setplayer(self, player)
                    else:
                        self.respn = '{"warning":"not enough gold!"}'
                else:
                    mybuilding.status = Building.BuildingStatus.DELIVERED
                    _upd = True

            if _upd is True:
                Building.setmybuilding(self, mybuilding)

            if self.error == '' and self.respn == '':
                self.respn = '{"state":' + player.state + ', "buildings":['
                self.respn = Building.compose_mybuilding(
                    self.respn, mybuilding)
                self.respn = self.respn.rstrip(',') + ']'
                self.respn += '}'

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
    def get(self):
        Utils.reset(self)  # reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, GCVars.passwd)
        guid = self.request.get('guid')
        uuid = Utils.required(self, 'uuid')
        uuid2 = Utils.required(self, 'uid2')
        events = Utils.required(self, 'events')
        events2 = Utils.required(self, 'events2')
        laptime = Utils.required(self, 'laptime')
        laptime2 = Utils.required(self, 'laptime2')
        track = Utils.required(self, 'track')

        version = config.data_version['building']
        if self.request.get('version'):
            version = self.request.get('version')
        lang = config.server["defaultLanguage"]
        if self.request.get('lang'):
            lang = self.request.get('lang')

        Utils.LogRequest(self)
        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()  # start count

        # if error, skip this
        #if self.error != '' or self.error is None:
        player = Player.getplayer(self, uuid)
        player2 = Player.getplayer(self, uuid2)
        ai = None
        my_building = None

        win_prize = None
        lose_prize = None

        data = Data.getDataAsObj(self, 'opponent_en', 1.0)
        if data is None:
            opponents = {'obj': json.loads(Score.GetDefaultOpponents())}
        else:
            opponents = data.obj

        for _track in opponents:
            for opponent in opponents[_track]:
                if not win_prize:
                    win_prize = opponent['win_prize']
                if not lose_prize:
                    lose_prize = opponent['lose_prize']
                if player2 is None:
                    if opponent['id'] == uuid2:
                        ai = opponent
                        self.error = ''

        if player is not None and guid != '':
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        if player is not None:
            scores = Score.calculate(self, events, events2, laptime, laptime2,
                                     win_prize, lose_prize)

            if scores is not None:
                score = scores[0]['total']
                #player.state_obj['cash'] += score
                player.state_obj['updated'] = start_time

                if player2 is not None:
                    player.state_obj[GCVars.total_races] += 1
                    if laptime < laptime2:
                        player.state_obj[GCVars.total_wins] += 1

                if ai is not None:
                    # save the resource to a building, ready for collection
                    my_building = Building.save_resource_to_building(
                        self, lang, version, player.uuid, track, score)
                    if player.state_obj.has_key(GCVars.total_ai_races):
                        player.state_obj[GCVars.total_ai_races] += 1
                    else:
                        player.state_obj.setdefault(GCVars.total_ai_races, 1)

                    if laptime < laptime2:
                        if player.state_obj.has_key(GCVars.total_ai_wins):
                            player.state_obj[GCVars.total_ai_wins] += 1
                        else:
                            player.state_obj.setdefault(
                                GCVars.total_ai_wins, 1)

                        #find star rating
                        difference = float(laptime2) - float(laptime)
                        data = {}
                        star_value = 0
                        new_star_value = 0
                        if player.state_obj.has_key('data'):
                            data = json.loads(player.state_obj['data'])
                        if data.has_key(uuid2):
                            star_value = int(data[uuid2])

                        #0,2,4 = 1 start time, 2 start time, 3 star time
                        if difference > float(ai['1_star_time']):
                            new_star_value = 1
                        if difference > float(ai['2_star_time']):
                            new_star_value = 2
                        if difference > float(ai['3_star_time']):
                            new_star_value = 3

                        if new_star_value > star_value:
                            data[uuid2] = new_star_value

                        logging.debug(
                            str(new_star_value) + ' > star_value:' +
                            str(star_value) + ', laptime 1:' + str(laptime) +
                            ', laptime2: ' + str(laptime2))
                        logging.debug('setting player data to ' +
                                      json.dumps(data))

                        player.state_obj['data'] = json.dumps(data)
                        player.state = json.dumps(player.state_obj)

                Player.setplayer(self, player)
                if 'xxx' in player.state:
                    self.error += '[KNOWN ISSUE] Player car lost. Please visit showroom and buy X1 again.'

                player_score = scores[0]
                scores_to_return = {
                    'score_prize': player_score['prize'],
                    'score_drift': player_score['prizes']['drift_bonus'],
                    'score_shift': player_score['prizes']['shift_bonus'],
                    'score_start': player_score['prizes']['start_bonus']
                }

                logging.debug('finishrace player state:' + player.state)
                self.respn = '{"state":' + player.state
                self.respn += ',"scores":' + json.dumps(scores_to_return)
                if my_building is not None:
                    self.respn += ',"building":['
                    self.respn = Building.compose_mybuilding(
                        self.respn, my_building)
                    self.respn = self.respn.rstrip(',') + ']'
                self.respn += '}'

                if player2 is not None:
                    score = scores[1]['total']
                    #player2.state_obj[GCVars.cash] += score
                    Building.save_resource_to_building(self, lang, version,
                                                       player2.uuid, track,
                                                       score)
                    player2.state_obj[GCVars.updated] = start_time
                    player2.state_obj[GCVars.total_races] += 1
                    if laptime2 < laptime:
                        player2.state_obj[GCVars.total_wins] += 1
                    Player.setplayer(self, player2)
        else:
            self.error = 'Cant find a player for ' + uuid
            #else:
        #    logging.warn('final error ' + self.error)

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
    def get(self):
        Utils.reset(self)                                                        # reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')
        chid = Utils.required(self, 'chid')
        type = Utils.required(self, 'type')
        laptime = Utils.required(self, 'laptime')
        replay = Utils.required(self, 'replay')
        events = Utils.required(self, 'events')
        cardata = Utils.required(self, 'cardata')
        name = Utils.required(self, 'name')
        image = Utils.required(self, 'image')

        version = config.data_version['building']
        if self.request.get('version'):
            version = self.request.get('version')
        lang = config.server["defaultLanguage"]
        if self.request.get('lang'):
            lang = self.request.get('lang')

        #logging.info("events " + events);
        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()                                                # start count

        # logic variables
        player = None

        # if error, skip this
        if self.error == '':
            player = Player.getplayer(self, uuid)

        if self.error == '' and player is not None and guid != '':
            logging.warn("trying to create challenge with" + player.uuid)
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        if self.error == '' and player is not None:
            logging.warn("trying to create challenge with" + player.uuid)

            challenge, my_building = Challenge.Update(self, chid, type, uuid, laptime, replay, events, cardata, name,
                                         image, lang, version)
            if challenge is not None:
                self.respn = '{'
                Challenge.ComposeChallenges(self, player)
                if my_building is not None:
                    self.respn += ',"building":['
                    self.respn = Building.compose_mybuilding(self.respn, my_building)
                    self.respn = self.respn.rstrip(',') + ']'
                self.respn = self.respn.rstrip(',') + '}'

            # update timestamp for player - this is to update if needed
            if challenge.manual_update is True:
                player.state_obj['updated'] = start_time
                Player.setplayer(self, player)

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
    def get(self):
        Utils.reset(self)  # reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        version = config.data_version['building']
        if self.request.get('version'):
            version = self.request.get('version')
        lang = config.server["defaultLanguage"]
        if self.request.get('lang'):
            lang = self.request.get('lang')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')
        itid = Utils.required(self, 'itid')
        level = Utils.required(self, 'level')
        location = Utils.required(self, 'location')

        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()  # start count

        # logical variables
        player = None
        buildings = None
        building = None

        # if error, skip this
        if self.error == '':
            player = Player.getplayer(self, uuid)

        if self.error == '' and player is not None and guid != '':
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        if self.error == '' and player is not None:
            buildings = Data.getbuildings(self, lang, float(version))

        if self.error == '' and buildings is not None:
            try:
                building = buildings.as_obj[itid][int(level) - 1]
            except KeyError:
                self.error = itid + " was not found!"

        if self.error == '' and building is not None:
            if player.state_obj['cash'] >= building['cost']:
                player.state_obj['cash'] -= building['cost']
                player.state_obj[
                    'updated'] = start_time  # update timestamp for player
                if Player.setplayer(self, player):
                    mybuilding = Building.newbuilding(self)
                    mybuilding.uuid = uuid
                    mybuilding.itid = itid
                    mybuilding.inid = Utils.genanyid(self, 'b')
                    mybuilding.level = building['level']
                    mybuilding.status = Building.BuildingStatus.PENDING
                    mybuilding.location = location
                    mybuilding.amount = 0
                    mybuilding.timestamp = int(start_time)
                    Building.setmybuilding(self, mybuilding)
                    self.respn = '{"state":' + player.state + ','
                    self.respn += '"building":['
                    self.respn = Building.compose_mybuilding(
                        self.respn, mybuilding)
                    self.respn = self.respn.rstrip(',') + ']'
                    self.respn += '}'
            else:
                self.respn = '{"warning":"not enough cash!"}'

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
Exemple #22
0
    def get(self):
        Utils.reset(self)  # reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')
        type = Utils.required(self, 'type')
        version = config.data_version['building']
        if self.request.get('version'):
            version = self.request.get('version')
        lang = config.server["defaultLanguage"]
        if self.request.get('lang'):
            lang = self.request.get('lang')

        if self.error == '' and passwd != config.testing[
                'passwd']:  # if password is incorrect
            self.error = 'passwd is incorrect.'  # inform user via error message
        Utils.LogRequest(self)
        start_time = time.time()  # start count

        # if error, skip this
        if self.error == '':
            player = Player.getplayer(
                self, uuid
            )  # get player state from Player helper class, specified by uuid

        if self.error == '' and player is not None and guid != '':
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        if self.error == '' and player is not None:  # if have some data returned
            self.respn = '{'
            if type == 'all':
                type = ''
                for item in config.playerdata:
                    type += item + ','
                type = type.rstrip(',')
            types = type.split(',')
            for item in types:
                if item == 'info':
                    self.respn += '"info":' + player.info + ','
                elif item == 'state':
                    self.respn += '"state":' + player.state + ','
                elif item == 'building':
                    buildings = Data.getbuildings(self, lang, version)
                    mybuildings = Building.getmybuildings(self, uuid)
                    if buildings is not None and mybuildings is not None:
                        self.respn += '"building":['
                        for mybuilding in mybuildings:
                            # update building status, determine production
                            _upd = False
                            if mybuilding.status == Building.BuildingStatus.PENDING:
                                if mybuilding.timestamp + (
                                        buildings.as_obj[mybuilding.itid]
                                    [mybuilding.level - 1]['build_time'] *
                                        60) <= start_time:
                                    mybuilding.timestamp = int(start_time)
                                    mybuilding.status = Building.BuildingStatus.DELIVERED
                                    _upd = True
                            elif mybuilding.status == Building.BuildingStatus.DELIVERED:
                                mybuilding.status = Building.BuildingStatus.OWNED
                                _upd = True
                            if _upd is True:
                                Building.setmybuilding(self, mybuilding)
                            self.respn = Building.compose_mybuilding(
                                self.respn, mybuilding)
                        self.respn = self.respn.rstrip(',') + '],'
                elif item == 'car':
                    mycars = Car.list(self, uuid)
                    if mycars is not None:
                        self.respn += '"car":['
                        for _car in mycars:
                            self.respn += Car.compose_mycar('', _car) + ','
                        self.respn = self.respn.rstrip(',') + '],'
                elif item == 'challenge':
                    Challenge.ComposeChallenges(self, player)

            self.respn = self.respn.rstrip(',') + '}'

        # calculate time taken and return result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))