def request(request): if request.method == "GET": rg = request.GET player = Player.objects.get(id=request.session['user_id']) if 'new_player_name' in rg: player.name = rg['new_player_name'] player.save() return HttpResponse(json.dumps({"result": "success", "player_name": rg['new_player_name']})) if 'new_max_score' in rg: game_name = rg['game_name'] score = None try: score = Score.objects.get(player=player, game__name=game_name) except: score = Score(player=player, game=Game.objects.get(name=game_name), score=0) score.score = rg['new_max_score'] score.save() return HttpResponse(json.dumps({"result": "success", "max_score": rg['new_max_score']})) if 'max_score_records' in rg: game_name = rg['game_name'] count = rg['count'] max_score_records = [] for record in Score.objects.filter(game__name=game_name).order_by('-score')[:10]: max_score_records.append({"score": record.score, "player_name": record.player.name}) return HttpResponse(json.dumps(max_score_records))
def init_db(): Base.metadata.create_all(bind=engine) player1 = Player(name="player1") db_session.add(player1) sc = Score(rule='ガチヤグラ', power=1900, weapon='スクリュースロッシャー', result='WIN', player=player1) db_session.add(sc) sc = Score(rule='ガチエリア', power=1920, weapon='スクリュースロッシャー', result='WIN', player=player1) db_session.add(sc) player2 = Player(name="player2") sc = Score(rule='ガチアサリ', power=2100, weapon='スプラシューター', result='WIN', player=player2) db_session.add(sc) sc = Score(rule='ガチエリア', power=2320, weapon='スプラシューターベッチュー', result='WIN', player=player2) db_session.add(sc) db_session.commit()
def _cache_winning_chance(user_name): """Populates memcache with the average moves remaining of Games""" ## the scores user earned when it is user in games user_chance = 0 oppo_chance = 0 user_scores = Score.query(Game.user.get().name == user_name).fetch() if user_scores: total = 2 * len(user_scores) wins = sum([score.user_score_to_int() for score in user_scores]) user_chance = wins / float(total) ## score the user earned when it is the opponent in games oppo_scores = Score.query( Game.user.get().name == GLOBAL_CURRENT_USER_NAME).fetch() if user_scores: total = 2 * len(oppo_scores) wins = sum([score.user_score_to_int() for score in oppo_scores]) oppo_chance = wins / float(total) if user_chance == 0 or oppo_chance == 0: chance = user_chance | oppo_chance else: change = (user_chance + oppo_chance) / 2 print "Winning chance of {} is {}".format(GLOBAL_CURRENT_USER_NAME, chance) memcache.set(MEMCACHE_WINNING_CHANCE, 'The winning chance is {:.2f}'.format(chance))
def new_game(self, request): """This function creates a new game. Input: Two Usernames; Only The first is required, if the second is not given, the first player will be playing with an Automate (Computer)""" player = utils.get_by_username(request.player) if not request.opponent: opponent = Player.query(Player.username == "computer").get() else: opponent = utils.get_by_username(request.opponent) newgame = Game(player=player.key, opponent=opponent.key) newgame.put() # initialize players position Position(game=newgame.key, player=player.key, position=0).put() Position(game=newgame.key, player=opponent.key, position=0).put() # update score Score(game=newgame.key, player=player.key, score=0).put() Score(game=newgame.key, player=opponent.key, score=0).put() return NewGameForm(player=player.username, opponent=opponent.username, urlsafekey=newgame.key.urlsafe())
def player_data(): if not request.json or 'player' not in request.json: print(request, request.json) abort(400) db = get_db() player_data = request.json['player'] friends = player_data['friends'] puzzle_data = player_data['puzzle_data'] del player_data['friends'] del player_data['puzzle_data'] player = Player.get_or_create(player_data) db.session.query(Player).filter( Player.social_id == player.social_id).update(player_data) for friend_social_id in friends: friend = Player.get_or_create({"social_id": friend_social_id}) player.add_friendship(friend) for index, puzzle_id in enumerate(puzzle_data['puzzles']): Score.maybe_update_score({ 'player_social_id': player.social_id, 'puzzle_id': puzzle_id, 'score': puzzle_data['scores'][index], 'stars': puzzle_data['stars'][index]}) db.session.commit() return jsonify( _assemble_response(player))
def play(): """Main function""" print('Hello in my AWESOME GAME!!!') name = input('Tell me yor NAME, my brave player: ') player = Player(name) enemy = Enemy() score = Score('scores.txt') while True: print('_' * 50) print('{}, make your choice!'.format(player.name)) print('For start the GAME type "START"') print('For help about GAME type "HELP"') print('For view the scores of game type "SCORE"') print('For exit from GAME type "EXIT"') choice = input('>>> ').lower() while choice not in ALLOWED_COMMANDS: choice = input('You are funny one))))\n' 'Try one more time: ') if choice == 'start': start(player, enemy) elif choice == 'help': _help() elif choice == 'score': score.print_score() else: raise KeyboardInterrupt
def _get_winning_percentage(player_name): """Populates ranking entity based on players winning %""" user = User.query(User.name == player_name).get() if user: total_win = float( len( Score.query(Score.user == user.key, Score.result == 'win').fetch())) total_lose = float( len( Score.query(Score.user == user.key, Score.result == 'lose').fetch())) total_tie = float( len( Score.query(Score.user == user.key, Score.result == 'tie').fetch())) # tie counts for 1/2 win and 1/2 lose winning_per = ((total_win + (total_tie / 2)) / (total_win + total_lose + total_tie)) # logging.info(total_win) # logging.info(total_lose) # logging.info(total_tie) # logging.info(winning_per) ranking = Ranking.query(Ranking.user == user.key).get() if ranking: ranking.winning_percent = winning_per ranking.put() else: ranking = Ranking(user=user.key, winning_percent=winning_per) ranking.put()
def get_high_scores(self,request): """Return all scores ordered by total points""" if request.number_of_results: scores = Score.query(Score.won == True).order(Score.attempts_allowed,Score.guesses).fetch(request.number_of_results) else: scores = Score.query(Score.won == True).order(Score.attempts_allowed,Score.guesses).fetch() return ScoreForms(items=[score.to_form() for score in scores])
def get_high_scores(self, request): """Gets the high scores for the game""" if request.number_of_results is not None: scores = Score.query().order(Score.score).fetch(request.number_of_results) else: scores = Score.query().order(Score.score) return ScoreForms(items=[score.to_form() for score in scores])
def create_score(payload, player_id): sub = payload.get('sub') check_user_id = Player.query.filter( Player.user_id == sub).one_or_none() # check if player_id is same as player_id come from JWT payload # if they are not same, abort. if check_user_id.id != player_id: print(' different user, no permission to create') abort(401) body = request.get_json() new_player_id = player_id new_course_id = body.get('course_id', None) new_score = body.get('score', None) new_date = body.get('date', None) try: score = Score(player_id=new_player_id, course_id=new_course_id, score=new_score, date=new_date) score.insert() return jsonify({'added_score': new_score}) except BaseException: abort(422)
def add_player(self, user_in, pass_in): """ Add a player to the database game return: True if everything is OK False if the user already exists """ exists = False for user in User.select(): if user_in.upper() == user.username.upper( ) and user.is_active == 1: exists = True response = False if not exists: user = User(username=user_in, password=pass_in, is_admin=0, is_active=1) user.save() try: score = Score(score=0, date=date.today(), id_user=user.id_user) score.save() response = True except AttributeError: response = False return response
def create_new_game_api(self, request): """ Create a new game. Requires an exiting user""" user = User.query(User.name == request.user_name).get() if not user: raise endpoints.NotFoundException( 'There is no user with that name!') try: history_record = [ HistoryRecord(play_sequence=1, action='Game created', user_entry=" ", result=" ", current_game="", game_over=False, game_won=False, game_cancelled=False) ] game = Game.create_new_game_models(user.key, request.answer, request.strikes, history_record) Score.create_new_score_models(user, game) except ValueError: raise endpoints.BadRequestException( 'You really need a positive number of strikes') input_validation = validate_input(game.answer) if input_validation[0] is True: return game.to_form('Have fun playing Hangman!') else: raise endpoints.BadRequestException(input_validation[1])
def _cache_winning_chance(user_name): """Populates memcache with the average moves remaining of Games""" ## the scores user earned when it is user in games user_chance = 0 oppo_chance = 0 user_scores = Score.query(Game.user.get().name == user_name).fetch() if user_scores: total = 2*len(user_scores) wins = sum([score.user_score_to_int() for score in user_scores]) user_chance = wins/float(total) ## score the user earned when it is the opponent in games oppo_scores = Score.query(Game.user.get().name == GLOBAL_CURRENT_USER_NAME).fetch() if user_scores: total = 2*len(oppo_scores) wins = sum([score.user_score_to_int() for score in oppo_scores]) oppo_chance = wins/float(total) if user_chance == 0 or oppo_chance == 0: chance = user_chance | oppo_chance else: change = (user_chance+oppo_chance)/2 print "Winning chance of {} is {}".format(GLOBAL_CURRENT_USER_NAME, chance) memcache.set(MEMCACHE_WINNING_CHANCE, 'The winning chance is {:.2f}'.format(chance))
def get_high_scores(self, request): """Return high scores.""" if request.number_of_results > 0: scores = Score.query().order(Score.guesses).fetch( request.number_of_results) else: scores = Score.query().order(Score.guesses) return ScoreForms(items=[score.to_form() for score in scores])
def get_high_scores(self, request): """ Get the user scores, Requires the user info's""" user = self._get_user(request) if request.number_of_results: scores = Score.query(Score.user == user.key).order(Score.score).fetch(limit=request.number_of_results) else: scores = Score.query(Score.user == user.key).order(Score.score) return ScoreForms(items=[score.to_form() for score in scores])
def get_user_rankings(self, request): """Returns user rankings""" users = User.query(User.name) scores = Score.query([Score.user == user.key]) wins = Score.query([Score.won == True for user in users]) games = Game.query(User.name) ranks = [(sum(wins)/sum(games) * 100) for user in users] return ranks
def test_float_serialization(self): """Tests that float values serialize and deserialize intact""" sc = Score(score=3.4) sc.save() serial_str = serializers.serialize(self.serializer_name, [sc]) deserial_objs = list(serializers.deserialize(self.serializer_name, serial_str)) self.assertEqual(deserial_objs[0].object.score, Approximate(3.4, places=1))
def get_high_scores(self, request): """Return high scores (scores ordered by the Score property)""" if not request.results_to_show: q = Score.query().order(-Score.score) else: q = Score.query().order(-Score.score).fetch( limit=request.results_to_show) return HighScoreForms(items=[score.to_form() for score in q])
def song_create_score(user_id, user_email, song_slug, score): score = Score( user_id=user_id, user_email=user_email, song_slug=song_slug, score=score, ) score.put()
def submit(user): try: score_ = submit_score(request.form.to_dict()) except MultipleInvalid as e: return show_errors(e) score = Score(value=score_['score'], user=user) score.save() return {"success": True}
def get_high_scores(self, request): """Return all scores ordered by total points""" if request.limit: scores = Score.query().order(-Score.num_of_wons).fetch(request.limit) else: scores = Score.query().order(-Score.num_of_wons).fetch() return ScoreForms(items=[score.to_form() for score in scores])
def create_score(): data = request.get_json() score = Score( criterion_id=data.get('criterion_id'), state=data.get('state'), meets_criterion=data.get('meets_criterion'), ).save() return jsonify(score.serialize()), 201
def post(self, request): score = request.POST.get('score') question_id = request.POST.get('question_id') question = Question.objects.get(pk=question_id) score = Score(question=question,user=request.user,score=int(score)) score.save() return HttpResponse(status=201)
def setUp(self): self.state = create_state() self.category = create_category() self.subcategory = create_subcategory(self.category.id) self.criterion = create_criterion(self.subcategory.id) self.score = Score( criterion_id=self.criterion.id, state=self.state.code, meets_criterion=True, ).save()
def get_high_scores(self, request): """Return all scores ordered by total points""" if request.limit: scores = Score.query().order(-Score.num_of_wons).fetch( request.limit) else: scores = Score.query().order(-Score.num_of_wons).fetch() return ScoreForms(items=[score.to_form() for score in scores])
def create_user(self, request): """Create a User. Requires a unique username""" if User.query(User.name == request.user_name).get(): raise endpoints.ConflictException( 'A User with that name already exists!') user = User(name=request.user_name, email=request.email) user.put() score = Score(parent=user.key, wins=0, losses=0, ties=0) score.put() return StringMessage( message='User {} created!'.format(request.user_name))
def get_high_scores(self, request): """Return high scores""" if request.number_of_results: return ScoreForms(items=[score.to_form() for score in Score.query().order(-Score.winner, -Score.user_steps).\ fetch(request.number_of_results)]) else: return ScoreForms(items=[ score.to_form() for score in Score.query().order( -Score.winner, -Score.user_steps) ])
def get_high_scores(self, request): """Return a specified number of high scores""" # Checks the value of number_of_results to determine if it is a number # to return a specific number of highscores if it is not then function # will only return 10 highscores if isinstance(request.number_of_results, int): _number_of_results = request.number_of_results scores = Score.query(Score.won==True).order(Score.total_attempts).fetch(limit=_number_of_results) return ScoreForms(items=[score.to_form() for score in scores]) else: scores = Score.query(Score.won==True).order(Score.total_attempts).fetch(limit=10) return ScoreForms(items=[score.to_form() for score in scores])
def end_Game(game, won): """ args: game - won - ends the user's game. """ game.endGame = True game.put() user = User.query(User.key == game.user).get() gameScore = get_Score(game, won) score = Score(player=user.name, score=gameScore, won=won) score.put()
def set_student_score(teacher_nid): '''设置学生分数''' print('set student') student_list = student_info(teacher_nid) choice = int(input('请选择学生:').strip()) number = float(input('请输入分数:').strip()) obj = Score(number) obj.save() student_list[choice].score_nid = obj.nid student_list[choice].save() print('------成绩设置成功------')
def get_user_rankings(self, request): """Get user rankings""" users = User.query() for user in users: games = Score.query(Score.user == user.key) win = Score.query().filter(Score.result == 'Win').fetch() draw = Score.query().filter(Score.result == 'Draw').fetch() lose = Score.query().filter(Score.result == "Lose").fetch() # The final score is base on both performance and participation. final_score = 5*len(win) + 3*len(win)+ 1*len(lose) user.rankingscore = final_score user.put() return UserForms(items=[user.to_form() for user in User.query().order(-User.rankingscore)])
def test(self, score_class_mock): save_mock = Mock(return_value=None) score_class_mock.return_value.save = save_mock storage = Storage() storage.populate() self.assertEqual(save_mock.call_count, 1) score = Score() score.score = 1234 score_class_mock.objects.all.return_value.order_by.return_value = QuerySetMock(score_class_mock, score) score = storage.get_score() self.assertEqual(score, 1234)
def determine_scores(game_round): wins_dict = defaultdict(int) for play in game_round.plays: wins_dict[play.winner] += 1 player_scores = Score(game_round.players) for p, bid in game_round.bids.items(): if bid == wins_dict[p]: player_scores.add_points(p, 10 + bid) return player_scores
def create_user(self, request): """Create a User. Requires a unique username""" if User.query(User.name == request.user_name).get(): raise endpoints.ConflictException( 'A User with that name already exists!') user = User(name=request.user_name, email=request.email) user.put() # Create an associated Score for this user score = Score(user=user.key) score.put() return StringMessage(message='User {} created!'.format( request.user_name))
def test(self, score_class_mock): save_mock = Mock(return_value=None) score_class_mock.return_value.save = save_mock storage = Storage() storage.populate() self.assertEqual(save_mock.call_count, 1) score = Score() score.score = 1234 score_class_mock.objects.all.return_value.order_by.return_value = QuerySetMock( score_class_mock, score) score = storage.get_score() self.assertEqual(score, 1234)
def create_score(registered_client): score = Score() score.registered_client = registered_client score.played_on = timezone.now() score.recieved_on = timezone.now() score.play_time = random.randint(2000, 30000) score.altitude = random.randint(0, 2000) score.score = random.randint(0, 130) score.save() return score
def get_high_scores(self, request): """Returns a list of scores sorted by final_score in descending order""" try: count_of_results = int(request.number_of_results) if count_of_results == 0: scores = Score.query(Score.game_status == 'Won').order( -Score.final_score).fetch() else: scores = Score.query(Score.game_status == 'Won').order( -Score.final_score).fetch(limit=count_of_results) print scores return ScoreForms(items=[score.to_form() for score in scores]) except: raise endpoints.BadRequestException('Numbers only please...')
def update_high_score(address, score): from models import Score score_obj = Score.query.filter(Score.address == address).first() if not score_obj: score_obj = Score(address, score) db.session.merge(score_obj) db.session.commit() return 'success' if score_obj and score_obj.score and score > score_obj.score: score_obj.score = score db.session.merge(score_obj) db.session.commit() return 'success'
def index(): den = Score.get_or_insert('den', name='Denver', amount=0) sea = Score.get_or_insert('sea', name='Seattle', amount=0) goal = 6500 * 100.0 if den.amount < goal and sea.amount < goal: den_factor = den.amount * 100.0 / goal sea_factor = sea.amount * 100.0 / goal else: den_factor = 100 sea_factor = 100 if den.amount > sea.amount: sea_factor = sea.amount * 100.0 / den.amount elif sea.amount > den.amount: den_factor = den.amount * 100.0 / sea.amount return render_template('index.html', den=den, sea=sea, den_factor=den_factor, sea_factor=sea_factor)
def get_user_rankings(self, request): """Get game history""" # user rankings userRanking = UserRankForms() # get all users users = User.query().fetch() # Get user scores and perform calculation for user in users: user_scores = Score.query(ancestor=user.key) user_scores.count() won = 0.0 lost = 0 gamecount = 0 if user_scores: for score in user_scores: gamecount += 1 if score.won is True: won += 1 else: lost += 1 # perform ranking calculation if gamecount > 0: performance = won/gamecount else: performance = -1.0 # -1 means user has not completed any games # userRankingList.append() userRanking.items.append(UserRankForm(user_name=user.name, performance_indicator=performance)) userRanking.items.sort(key=lambda x: x.performance_indicator, reverse=True) return userRanking
def get_user_scores(self, request): """Returns all of an individual User's scores""" user = User.query(User.name == request.user_name).get() if not user: raise endpoints.NotFoundException('A User with that name does not exist!') scores = Score.query(Score.user == user.key) return ScoreForms(items=[score.to_form() for score in scores])
def get_all_rankings(self, request): """returns rankings by winning percentage ranked descending""" scores = Score.query() users = User.query() user_keys = [] for score in scores: if score.winning_user not in user_keys: user_keys.append(score.winning_user) if score.losing_user not in user_keys: user_keys.append(score.losing_user) user_results = [] for user in user_keys: wins = 0 losses = 0 current_user_name = '' for ind_user in users: if user == ind_user.key: current_user_name = ind_user.name for score in scores: if score.winning_user == user: wins = wins + 1 if score.losing_user == user: losses = losses + 1 games = wins + losses winning_percentage = float(wins) / float(games) user_result = (current_user_name, wins, losses, games, winning_percentage) user_results.append(user_result) user_results.sort(key=lambda x: x[4], reverse=True) return UserRankingForms( items=([ranking_to_form(result) for result in user_results]))
def get_user_rankings(self, request): """ The ranking is defined by the ratio of sum(score)/(2*game) """ scores = Score.query() scores_list_dict = defaultdict(list) for score in scores: scores_list_dict[score.user.get().name].append( score.user_score_to_int()) scores_list_dict = dict(scores_list_dict) performances_dict = {} for k, v in scores_list_dict.iteritems(): performance = sum(v) / (2 * len(v)) performances_dict[k] = performance performances_list_sorted = sorted(performances_dict.items(), key=operator.itemgetter(1), reverse=True)[0:request.max_number] strs = json.dumps(performances_list_sorted) return StringMessage(message=strs)
def song_total_score(song_slug): score_query = Score.query(Score.song_slug == song_slug) scores = score_query.fetch() total_score = 0 for user_score in scores: total_score += user_score.score return total_score
def get_game_history(self, request): """Return Game History""" game = get_by_urlsafe(request.urlsafe_game_key, Game) return GameHistoryForm(history=game.history) for u in users: scores = Score.query(Score.user == u.key).fetch tot_guesses = sum([score.guesses for score in scores])
def get_user_ranking(self, request): """Returns the performance of the player as a Ranking.""" user = User.query(User.name == request.user_name).get() if not user: raise endpoints.NotFoundException( 'A User with that name does not exist!') scores = Score.query(Score.user == user.key).fetch() if not scores: raise endpoints.NotFoundException( 'No scores were found for that user!') wins = sum(s.won == True for s in scores) percent_won = (float(wins)/len(scores)) * 100 number_of_guesses = sum(score.total_incorrect for score in scores) avg_wrong = float(number_of_guesses)/len(scores) ranking = Ranking.query(Ranking.user == user.key).get() if ranking: ranking.wins = wins ranking.percent_won = percent_won ranking.avg_wrong = avg_wrong ranking.put() return ranking.to_form("Ranking has been updated for {}".format( user.name)) else: ranking = Ranking.new_ranking(user=user.key, wins=wins, percent_won=percent_won, avg_wrong=avg_wrong) return ranking.to_form("Ranking created for {}".format(user.name))
def get_user_rankings(self, request): """Return user rankings""" users = User.query() userRankInfoList = [] if users == None: raise endpoints.NotFoundException('No existing users now') for user in users: winTime = 0 totalTime = 0 winRate = 0.0 totalGuesses = 0 scores = Score.query(Score.user == user.key) if scores != None: for score in scores: totalTime = totalTime + 1 if score.won == True: winTime = winTime + 1 totalGuesses += score.guesses if totalTime != 0: winRate = winTime / float(totalTime) userRankInfo = UserRankInfo(user.name, winTime, winRate, totalGuesses) userRankInfoList.append(userRankInfo) userRankInfoList = sorted( userRankInfoList, key=lambda user: (user.winTime, user.winRate, -user.totalGuesses), reverse=True) return UserRankForms( items=[userRank.to_form() for userRank in userRankInfoList])
def rank_them(users, number_of_results): rankings = [] for user in users: scores = Score.query(ancestor=user.key) wins = losses = cats = moves = 0.0 for score in scores: # chore: might not want to include moves in losses in the # rankings algorithm moves += score.moves if score.won: wins += 1.0 elif score.cats: cats += 1.0 else: losses += 1.0 games = wins + cats + losses # don't rank users who haven't finished a game if games != 0: rating = Ranking(user=user.name, win_percent=wins / games, cats_percent=cats / games, avg_moves=moves / games) rankings.append(rating) # sorts are stable(order from initial sort retained unless changed # by a later sort) so execute the last sort criteria first rankings = sorted(rankings, key=attrgetter('avg_moves')) rankings = sorted(rankings, key=attrgetter('win_percent', 'cats_percent'), reverse=True) if number_of_results: rankings = rankings[:number_of_results] return rankings
def get_user_rankings(self, request): """Get the rankings of each player""" items = [] users = User.query() for user in users: wins = 0 guesses = 0 #Use .fetch() to turn query into an iterable list you can take the len() of scores = Score.query(Score.user == user.key).fetch() if scores: for score in scores: guesses += score.guesses if score.won: wins += 1 winning_percentage = 100 * wins/float(len(scores)) items.append(user.to_form(wins, guesses, winning_percentage)) #Lambda defines nameless inline function #items.sort(key=lambda u: u.winning_percentage, reverse = True) #http://stackoverflow.com/questions/12749398/using-a-comparator-function-to-sort\ def _compare_user_games(a, b): """Sort user rankings by winning_percentage, then # wins, then # guesses""" if a.winning_percentage != b.winning_percentage: return int(a.winning_percentage - b.winning_percentage) elif a.wins != b.wins: return int(a.wins - b.wins) else: return b.guesses - a.guesses items = sorted(items, cmp = _compare_user_games, reverse = True) return UserForms(items=items)
def home(): if 'email' not in session: return redirect(url_for('login')) user = User.query.filter_by(email=session['email']).first() form = ScoreForm() my_scores = [] #my_scores = Score.query.filter_by(uid=user.uid) my_scores = Score.query.all() print(my_scores) if request.method == 'POST': if form.validate() == False: return render_template('home.html', form=form) else: # submit the score into the db newscore = Score(user.uid, form.score.data) db.session.add(newscore) db.session.commit() # return those results return render_template('home.html', form=form, my_scores=my_scores) if request.method == 'GET': return render_template("home.html", form=form, my_scores=my_scores)
def get_high_scores(self, request): """ This returns the highest streak scores recorded in the game in decending order. Users can limit the number of scores returned with an optional value. """ scores = Score.query().order(-Score.streak).fetch(request.number_of_results) return HighScores(items=[score.high_scores() for score in scores])
def submitarticle(request): error_msg = u"No POST data sent." if request.method == "POST": post = request.POST.copy() if post.has_key('tags') and post.has_key('title') and post.has_key('url'): try: url = post['url'] art = Article() art.tags = post['tags'].strip().split(',') art.author = str(request.user) art.title = post['title'] art.votecount = 0 art.viewcount = 0 if not url.startswith('http://'): url = 'http://'+url art.url = url if art.url and art.title and art.author: try: person = getPerson(request) person.timesArticle = person.timesArticle + 1 person.lastActive = datetime.datetime.now() rating = Score.objects(type='submitarticle')[0].value person.currentRating = person.currentRating + rating person.save() incrementStat('articles',1) art.save() except Exception as inst: print inst return HttpResponseRedirect('/') except: return HttpResponseServerError('wowza! an error occurred, sorry!') else: error_msg = u"Insufficient POST data (need 'content' and 'title'!)" return HttpResponseServerError(error_msg)
def get_user_rankings(self, request): """ Returns all user rankings given a GameDifficulty level, Determined first by winning percentage then by number if total wins as the tie breaker. """ difficulty = validateGameDifficultyValue(request, True) users = User.query().fetch() items = [] total_games = 0 wins = 0 for user in users: scores = Score.query() # Filter by game difficulty and only wons that resulted in a win scores = scores.filter(Score.user == user.key, \ Score.difficulty == difficulty) scores.fetch() for score in scores: total_games += 1 if score.won: wins += 1 if total_games > 0: items.append( RankingForm(user_name=user.name, difficulty=getattr(GameDifficulty, difficulty), win_percentage=round(float(wins)/total_games*100, 2), wins=wins) ) total_games = 0 wins = 0 return RankingForms(items=items)
def promote(request): error_msg = u"No POST data sent." if request.method == "POST": post = request.POST.copy() print "promote ID: "+post['id'] if post.has_key('id') : try: iid = post['id'] ideas = Idea.objects(id=iid) print "len: "+str(len(ideas)) if(len(ideas) >0): idea = ideas[0] idea.ispromoted = True incrementStat('promotions',1) people = Person.objects(email=idea.email) if people and len(people)>0: person = people[0] person.timesPromoted = person.timesPromoted +1 rating = Score.objects(type='promotion')[0].value person.currentRating = person.currentRating + rating person.save() idea.save() try: t = ThreadClass("Idea Promoted", "Your idea '"+str(idea.title)+"' has been promoted and will now go forward for idea selection, it may or may not be chosen for implementation.",[idea.email]) t.start() except Exception as inst: print 'exception sending email '+str(inst) traceback.print_exc() return HttpResponseRedirect('/') except Exception as inst: return HttpResponseServerError('wowza! an error occurred, sorry!</br>'+str(inst)) else: error_msg = u"Insufficient POST data (need 'slug' and 'title'!)" return HttpResponseServerError(error_msg)
def get_high_scores(self, request): """ Returns the leader-board for hangman """ scores = Score.query(Score.won == True).order(Score.guesses).fetch( request.number_of_results) return ScoreForms(items=[score.to_form() for score in scores])
def submitidea(request): error_msg = u"No POST data sent." if request.method == "POST": post = request.POST.copy() if post.has_key('tags') and post.has_key('title') and post.has_key('content'): try: content = post['content'] idea = Idea() idea.tags = post['tags'].strip().split(',') idea.author = str(request.user) print "user: "******"Insufficient POST data (need 'content' and 'title'!)" return HttpResponseServerError(error_msg)