def question_switch(request, id): """ Accept a proposed question """ question = get_object_or_404(Question, pk=id) # qproposal - endorse part proposed_cat = Category.objects.filter(name='proposed')[0] if question.category == proposed_cat: if not question.endorsed_by: player = question.proposed_by.get_profile() staff_user = request.user question.endorsed_by = staff_user question.save() amount = 0 for tag in question.tags.all(): if tag.name == 'qotd': amount = QOTD_GOLD elif tag.name == 'challenge': amount = CHALLENGE_GOLD elif tag.name == 'quest': amount = QUEST_GOLD scoring.score(player, None, 'bonus-gold', external_id=staff_user.id, gold=amount) # regular activation of question else: question.active = not question.active question.save() go_back = request.META.get('HTTP_REFERER', None) if not go_back: go_back = reverse('wouso.interface.cpanel.views.qpool_home') return HttpResponseRedirect(go_back)
def created(self): if self.challenge.WARRANTY: # take 3 points from user_from scoring.score(self.challenge.user_from.user, ChallengeGame, 'chall-warranty', external_id=self.challenge.id)
def question_switch(request, id): question = get_object_or_404(Question, pk=id) # qproposal - endorse part proposed_cat = Category.objects.filter(name='proposed')[0] if question.category == proposed_cat: if not question.endorsed_by: player = question.proposed_by.get_profile() staff_user = request.user question.endorsed_by = staff_user question.save() amount = 0 for tag in question.tags.all(): if tag.name == 'qotd': amount = QOTD_GOLD elif tag.name == 'challenge': amount = CHALLENGE_GOLD elif tag.name == 'quest': amount = QUEST_GOLD scoring.score(player, None, 'bonus-gold', external_id=staff_user.id, gold=amount) # regular activation of question else: question.active = not question.active question.save() go_back = request.META.get('HTTP_REFERER', None) if not go_back: go_back = reverse('wouso.interface.cpanel.views.qpool_home') return HttpResponseRedirect(go_back)
def give_level_bonus(self): final = QuestGame.get_final() if not final: return for level in xrange(len(self.levels) + 1): if level == 0: continue users = QuestUser.objects.filter(current_quest=final, current_level__gte=level, race__can_play=True) for user in users: scoring.score(user, QuestGame, self.get_formula('finalquest-ok'), level=level, level_users=users.count()) signal_msg = ugettext_noop( "received bonus for reaching level {level} in the final quest" ) signals.addActivity.send(sender=None, user_from=user, user_to=user, message=signal_msg, arguments=dict(level=level), game=QuestGame.get_instance())
def create(self, request): attrs = self.flatten_dict(request.POST) if 'spell' not in attrs.keys(): return {'success': False, 'error': 'Spell not provided'} try: spell = int(attrs['spell']) spell = Spell.objects.get(pk=spell) except (ValueError, Spell.DoesNotExist): return {'success': False, 'error': 'No such spell'} # TODO refactor player = request.user.get_profile() if spell.price > player.coins.get('gold', 0): return {'success': False, 'error': 'Insufficient gold'} else: player.magic.add_spell(spell) scoring.score(player, None, 'buy-spell', external_id=spell.id, price=spell.price) SpellHistory.bought(player, spell) return {'success': True}
def create(user_from, user_to, ignore_questions = False): """ Assigns questions, and returns the number of assigned q """ questions = [q for q in get_questions_with_category('challenge')] if (len(questions) < 5) and not ignore_questions: raise ChallengeException('Too few questions') shuffle(questions) uf, ut = Participant(user=user_from), Participant(user=user_to) uf.save(), ut.save() c = Challenge(user_from=uf, user_to=ut, date=datetime.now()) c.save() # TODO: better question selection #limit = 5 for q in questions[:Challenge.LIMIT]: c.questions.add(q) # set last_launched user_from.last_launched = datetime.now() user_from.save() # take 3 points from user_from scoring.score(user_from, ChallengeGame, 'chall-warranty', external_id=c.id) return c
def user_post_save(sender, instance, **kwargs): profile, new = Player.objects.get_or_create(user=instance) if new: # add in default group from wouso.core.config.models import ChoicesSetting try: default_group = PlayerGroup.objects.get(pk=int(ChoicesSetting.get('default_group').get_value())) except (PlayerGroup.DoesNotExist, ValueError): pass else: profile.groups.add(default_group) try: default_series = PlayerGroup.objects.get(pk=int(ChoicesSetting.get('default_series').get_value())) except (PlayerGroup.DoesNotExist, ValueError): pass else: profile.groups.add(default_series) # kick some activity signal_msg = ugettext_noop('has joined the game.') signals.addActivity.send(sender=None, user_from=profile, user_to=profile, message=signal_msg, game=None) # give 15 bonus points from wouso.core.scoring import score from wouso.settings import STARTING_POINTS try: score(profile, None, 'bonus-points', points=STARTING_POINTS) except: pass # This might fail when formulas are not set-up, i.e. superuser syncdb profile creation
def manage_player_set(request, player_id, task_id): player = get_object_or_404(SpecialQuestUser, id=player_id) task = get_object_or_404(SpecialQuestTask, id=task_id) if task not in player.done_tasks.all(): if player.group: members = player.group.members player.group.set_task_done(task) else: members = (player, ) for member in members: if task not in member.done_tasks.all(): member.done_tasks.add(task) scoring.score(member, SpecialQuestGame, 'specialquest-passed', external_id=task.id, value=task.value) signal_msg = ugettext_noop( 'completed special quest {task_name} and earned {value} gold' ) action_msg = 'specialq-ok-gold' signals.addActivity.send(sender=None, user_from=member, \ user_to=member, \ message=signal_msg, arguments=dict(task_name=task.name, value=task.value), \ game=SpecialQuestGame.get_instance(), action=action_msg) return HttpResponseRedirect( reverse('specialquest_manage', args=(player.id, )))
def karma_group_view(request, group): group_id = group group = get_object_or_404(PlayerGroup, pk=group) players = group.players.all() if request.method == 'POST': form = KarmaBonusForm(request.POST, players=players) if form.is_valid(): formula = Formula.get('bonus-karma') if formula is None: messages.error(request, 'No such formula, bonus-karma') else: for player, entry in zip(players, form.fields): # get amount of karma points for current player karma_points = form.cleaned_data[entry] # if karma points are zero then skip if karma_points == 0: continue # compute formula and calculate amount of bonus given amount = eval(formula.expression.format(**{'karma_points': karma_points}).split('=')[1]) # apply scoring scoring.score(player, None, formula, external_id=request.user.get_profile().id, **{'karma_points': karma_points}) # add activity (parse formula expression to get the coin from formula) add_activity(player, _( 'received {amount} {coin} bonus for {karma_points} Karma Points'), amount=amount, coin=formula.expression.split('=')[0], karma_points=karma_points, reason='Bonus for Karma') messages.info(request, 'Successfully given bonus') return redirect('karma_group', **{'group': group_id}) else: form = KarmaBonusForm(players=players) return render_to_response('cpanel/karma_group.html', {'form':form, 'group':group}, context_instance=RequestContext(request))
def infraction_recheck(request): """ Rerun an infraction check on the current challenge history The view should allow for other infraction additions. """ try: inf_list = History.objects.filter(coin__name='penalty', formula__name='chall-was-set-up-infraction').delete() except: pass all_participants = Participant.objects.filter(seconds_took__lt=15).exclude( seconds_took=None) formula = Formula.objects.get(name='chall-was-set-up-infraction') for p in all_participants: id = None if p.user_from.count(): if p.user_from.all()[0].status == 'P' and p.user_from.all()[ 0].winner.id != p.user.id: user = p.user.player_ptr id = p.user_from.all()[0].id if p.user_to.count(): if p.user_to.all()[0].status == 'P' and p.user_to.all()[ 0].winner.id != p.user.id: user = p.user.player_ptr id = p.user_to.all()[0].id if id: scoring.score(user=user, game=None, formula=formula, external_id=id) return HttpResponseRedirect(reverse('wouso.interface.cpanel.views.players'))
def bazaar_buy(request, spell): spell = get_object_or_404(Spell, pk=spell) player = request.user.get_profile() error, message = '','' if Bazaar.disabled(): error = _("Magic is disabled") elif spell.price > player.coins.get('gold', 0): error = _("Insufficient gold amount") elif spell.available == False: error = _("Spell is not available") elif spell.level_required > player.level_no: error = _("Level {level} is required to buy this spell").format(level=spell.level_required) else: player.magic.add_spell(spell) scoring.score(player, None, 'buy-spell', external_id=spell.id, price=spell.price) signal_msg = ugettext_noop('bought a spell') action_msg = 'spell-buy' signals.addActivity.send(sender=None, user_from=player, user_to=player, message=signal_msg, game=None, action=action_msg, public=False) SpellHistory.bought(player, spell) message = _("Successfully aquired") return bazaar(request, message=message, error=error)
def check_answer(self, user, answer): if user.current_quest != self: user.finish_quest() user.set_current(self) return False try: question = self.levels[user.current_level] except IndexError: logging.error("No such question") return False if not user.current_level == self.count and \ answer.lower() == question.answers.all()[0].text.lower(): # score current progress scoring.score(user, QuestGame, self.get_formula('quest-ok'), level=(user.current_level + 1)) user.current_level += 1 if user.current_level == self.count: user.finish_quest() # score finishing scoring.score(user, QuestGame, self.get_formula('quest-finish-ok')) user.save() return True return False
def check_answer(self, user, answer): if user.current_quest != self: user.finish_quest() user.set_current(self) return False try: question = self.levels[user.current_level] except IndexError: logging.error("No such question") user_hash = hashlib.sha1( '%s%s%s' % (user.last_name[::-1], question.answers.all()[0].text, user.first_name) ) if not user.current_level == self.count and \ answer.lower() == user_hash.hexdigest(): # score current progress scoring.score(user, QuestGame, self.get_formula('quest-ok'), level=(user.current_level + 1)) user.current_level += 1 if user.current_level == self.count: user.finish_quest() # score finishing scoring.score(user, QuestGame, self.get_formula('quest-finish-ok')) user.save() return True return False
def create(self, request, coin, tocoin): try: coin = Coin.objects.get(id=coin) tocoin = Coin.objects.get(id=tocoin) except Coin.DoesNotExist: return {'success': False, 'error': 'Invalid coin'} attrs = self.flatten_dict(request.POST) if 'amount' not in attrs.keys(): return {'success': False, 'error': 'Amount not provided'} player = request.user.get_profile() try: amount = int(attrs['amount']) assert amount > 0 except (ValueError, AssertionError): return {'success': False, 'error': 'Invalid Amount'} if player.coins[coin.id] < amount: return {'success': False, 'error': 'Insufficient amount'} # TODO: change me if coin.id == 'points': scoring.score(player, None, 'points-gold-rate', points=amount) elif coin.id == 'gold': scoring.score(player, None, 'gold-points-rate', gold=amount) return {'success': True, 'coins': player.coins}
def penalise(cls, player, formula, external_id=None): coins = Coin.get('penalty') if not coins is None: score(user=player, game=None, formula=formula, external_id=external_id)
def accept(self): if self.challenge.WARRANTY: # take warranty from user_to scoring.score(self.challenge.user_to.user, ChallengeGame, 'chall-warranty', external_id=self.challenge.id)
def manage_player(request, player_id): player = get_object_or_404(Player, pk=player_id) player = player.get_extension(SpecialQuestUser) tasks_not_done = SpecialQuestTask.objects.exclude(id__in=player.done_tasks.all().values('id')).all() # TODO: use smth like django-flash for this message, error = '', '' if request.method == "POST": # do bonuses try: amount = int(request.POST.get('gold', 0)) except ValueError: amount = 0 if amount > 0: scoring.score(player, None, 'bonus-gold', external_id=request.user.get_profile().id, gold=amount) message = 'Successfully given bonus' else: error = 'Invalid amount' bonuses = scoring.History.objects.filter(user=player, formula__id='bonus-gold') return render_to_response('specialquest/cpanel_manage.html', dict(mplayer=player, tasks_not_done=tasks_not_done, message=message, error=error, bonuses=bonuses), context_instance=RequestContext(request))
def manage_player_set(request, player_id, task_id): player = get_object_or_404(SpecialQuestUser, id=player_id) task = get_object_or_404(SpecialQuestTask, id=task_id) if task not in player.done_tasks.all(): if player.group: members = player.group.members player.group.set_task_done(task) else: members = (player,) for member in members: if task not in member.done_tasks.all(): member.done_tasks.add(task) scoring.score(member, SpecialQuestGame, 'specialquest-passed',external_id=task.id, value=task.value) signal_msg = ugettext_noop('completed special quest {task_name} and earned {value} gold') action_msg = 'specialq-ok-gold' signals.addActivity.send(sender=None, user_from=member, \ user_to=member, \ message=signal_msg, arguments=dict(task_name=task.name, value=task.value), \ game=SpecialQuestGame.get_instance(), action=action_msg) return HttpResponseRedirect(reverse('specialquest_manage', args=(player.id,)))
def bazaar_buy(request, spell): spell = get_object_or_404(Spell, pk=spell) player = request.user.get_profile() error, message = '','' if Bazaar.disabled(): error = _("Magic is disabled") elif spell.price > player.coins.get('gold', 0): error = _("Insufficient gold amount") elif spell.available == False: error = _("Spell is not available") elif spell.level_required > player.level_no: error = _("Level {level} is required to buy this spell").format(level=spell.level_required) else: player.magic.add_spell(spell) scoring.score(player, None, 'buy-spell', external_id=spell.id, price=spell.price) signal_msg = ugettext_noop('bought a spell') action_msg = 'spell-buy' signals.addActivity.send(sender=None, user_from=player, user_to=player, message=signal_msg, game=None, action=action_msg, public=False) SpellHistory.bought(player, spell) message = _("Successfully acquired") if error: messages.error(request, error) if message: messages.success(request, message) return redirect('bazaar_home')
def bonus(request, player_id): player = get_object_or_404(Player, pk=player_id) if request.method == 'POST': form = BonusForm(request.POST) if form.is_valid(): coin, amount = form.cleaned_data['coin'], form.cleaned_data['amount'] formula = Formula.get('bonus-%s' % coin.name) if formula is None: messages.error(request, 'No such formula, bonus-%s' % coin.name) else: scoring.score(player, None, formula, external_id=request.user.get_profile().id, **{coin.name: amount}) if form.cleaned_data['reason']: add_activity(player, _('received {amount} {coin} bonus for {reason}'), amount=amount, coin=coin, reason=form.cleaned_data['reason']) messages.info(request, 'Successfully given bonus') return redirect('player_profile', id=player.id) else: form = BonusForm() bonuses = scoring.History.objects.filter(user=player, formula__name__startswith='bonus-').order_by('-timestamp') penalties = scoring.History.objects.filter(user=player, formula__name__startswith='penalty-').order_by('-timestamp') return render_to_response('cpanel/bonus.html', {'target_player': player, 'form': form, 'bonuses': bonuses, 'penalties': penalties}, context_instance=RequestContext(request) )
def accept(self): self.status = 'A' self.save() # take warranty from user_to scoring.score(self.user_to.user, ChallengeGame, 'chall-warranty', external_id=self.id)
def give_bonus(self): for i, r in enumerate(self.top_results()): player = r.user.get_extension(Player) scoring.score(player, QuestGame, 'quest-finish-bonus', position=i + 1, external_id=self.id)
def quest_bonus(request, quest): quest = get_object_or_404(Quest, pk=quest) # TODO: move logic to models for i, r in enumerate(quest.top_results()): player = r.user.get_extension(Player) scoring.score(player, QuestGame, 'quest-finish-bonus', position=i + 1, external_id=quest.id) return redirect('quest_home')
def give_level_bonus(self): for level in xrange(len(self.levels)): users = QuestUser.objects.filter(current_level=level) for user in users: scoring.score(user, QuestGame, self.get_formula('finalquest-ok'), level=level, level_users=users.count())
def manage_player(request, player_id): player = get_object_or_404(Player, pk=player_id) player = player.get_extension(SpecialQuestUser) tasks_not_done = SpecialQuestTask.objects.exclude(id__in=player.done_tasks.all().values("id")).all() # TODO: use smth like django-flash for this message, error = "", "" if request.method == "POST": # do bonuses if request.POST.get("gold", False): try: amount = int(request.POST.get("gold", 0)) except ValueError: amount = 0 if amount > 0: scoring.score(player, None, "bonus-gold", external_id=request.user.get_profile().id, gold=amount) message = "Successfully given bonus" if request.POST.get("comment", None): signal_msg = ugettext_noop("received {gold} gold bonus for {comment}") signals.addActivity.send( sender=None, user_from=player, user_to=player, message=signal_msg, arguments=dict(gold=amount, comment=request.POST["comment"]), game=SpecialQuestGame.get_instance(), ) else: error = "Invalid amount" elif request.POST.get("points", False): try: amount = int(request.POST.get("points", 0)) # assert amount > 0 except (ValueError, AssertionError): error = "Invalid amount" else: scoring.score(player, None, "penalty-points", external_id=request.user.get_profile().id, points=amount) message = "Successfully punished" bonuses = scoring.History.objects.filter(user=player, formula__id="bonus-gold").order_by("-timestamp") penalties = scoring.History.objects.filter(user=player, formula__id="penalty-points").order_by("-timestamp") return render_to_response( "specialquest/cpanel_manage.html", dict( mplayer=player, tasks_not_done=tasks_not_done, message=message, error=error, bonuses=bonuses, penalties=penalties, ), context_instance=RequestContext(request), )
def karma_group_view(request, id): group = get_object_or_404(PlayerGroup, pk=id) players = group.players.all() if request.method == 'POST': form = KarmaBonusForm(request.POST, players=players) if form.is_valid(): formula = Formula.get('bonus-karma') if formula is None: messages.error(request, 'No such formula, bonus-karma') else: for player, entry in zip(players, form.fields): # Get amount of karma points for current player karma_points = form.cleaned_data[entry] # Skip if there are no karma points if karma_points == 0: continue # Compute formula and calculate amount of bonus given amount = eval( formula.expression.format(**{ 'karma_points': karma_points }).split('=')[1]) # Apply scoring scoring.score(player, None, formula, external_id=request.user.get_profile().id, **{'karma_points': karma_points}) # Add activity (parse formula expression to get the coin from formula) add_activity( player, _('received {amount} {coin} bonus for {karma_points} Karma Points' ), amount=amount, coin=formula.expression.split('=')[0], karma_points=karma_points, reason='Bonus for Karma') messages.info(request, 'Successfully given bonus') return redirect('karma_group', id=id) else: form = KarmaBonusForm(players=players) return render_to_response('cpanel/karma_group.html', { 'form': form, 'group': group }, context_instance=RequestContext(request))
def answered(user, question, choice): correct = False for i, a in enumerate(question.answers): if a.id == choice: if a.correct: correct = True break user.set_answered(choice, correct) # answer id if correct: scoring.score(user, QotdGame, 'qotd-ok')
def give_level_bonus(self): for level in xrange(len(self.levels)): users = QuestUser.objects.filter(current_level=level) for user in users: scoring.score( user, QuestGame, self.get_formula('finalquest-ok'), level=level, level_users=users.count() )
def manage_player(request, player_id): player = get_object_or_404(Player, pk=player_id) player = player.get_extension(SpecialQuestUser) tasks_not_done = SpecialQuestTask.objects.exclude( id__in=player.done_tasks.all().values('id')).all() # TODO: use smth like django-flash for this message, error = '', '' if request.method == "POST": # do bonuses if request.POST.get('gold', False): try: amount = int(request.POST.get('gold', 0)) except ValueError: amount = 0 if amount > 0: scoring.score(player, None, 'bonus-gold', external_id=request.user.get_profile().id, gold=amount) message = 'Successfully given bonus' else: error = 'Invalid amount' elif request.POST.get('points', False): try: amount = int(request.POST.get('points', 0)) #assert amount > 0 except (ValueError, AssertionError): error = 'Invalid amount' else: scoring.score(player, None, 'penalty-points', external_id=request.user.get_profile().id, points=amount) message = 'Successfully punished' bonuses = scoring.History.objects.filter( user=player, formula__id='bonus-gold').order_by('-timestamp') penalties = scoring.History.objects.filter( user=player, formula__id='penalty-points').order_by('-timestamp') return render_to_response('specialquest/cpanel_manage.html', dict(mplayer=player, tasks_not_done=tasks_not_done, message=message, error=error, bonuses=bonuses, penalties=penalties), context_instance=RequestContext(request))
def testScore(self): formula = Formula.objects.create(id="_test_formula_sc", formula="_test=13", owner=self.game) scoring.score(self.user.get_profile(), self.game, formula, external_id=3) hs = scoring.history_for(self.user, self.game, external_id=3) self.assertTrue(isinstance(hs, QuerySet)) history = list(hs)[0] # check if specific coin has been updated self.assertEqual(history.coin, self.coin) self.assertEqual(history.amount, 13)
def pass_level(self, quest): """ Pass current level. Increment current level and score. """ if self.current_quest != quest: return None scoring.score(self, QuestGame, quest.get_formula('quest-ok'), level=(self.current_level + 1), external_id=quest.id) self.current_level += 1 if self.current_level == quest.count: self.finish_quest() scoring.score(self, QuestGame, quest.get_formula('quest-finish-ok'), external_id=quest.id) self.save() return self.current_level
def steal_points(self, userto, amount): # TODO (re)move it from wouso.core import scoring scoring.score(self, None, 'steal-points', external_id=userto.id, points=-amount) scoring.score(userto, None, 'steal-points', external_id=self.id, points=amount)
def _give_bonus(self, points, gold): if self.best_attempt is not None: if points > self.best_attempt.points: points = points - self.best_attempt.points gold = gold - self.best_attempt.gold scoring.score(self.user, None, 'bonus-points', points=points) scoring.score(self.user, None, 'bonus-gold', gold=gold) add_activity(self.user, _('received {points} points and ' '{gold} gold bonus' ' for beating his/her ' 'highscore at quiz {quiz_name}'), points=points, gold=gold, quiz_name=self.quiz.name) else: scoring.score(self.user, None, 'bonus-points', points=points) scoring.score(self.user, None, 'bonus-gold', gold=gold) add_activity(self.user, _('received {points} points' ' and {gold} gold bonus' ' for submitting quiz {quiz_name}'), points=points, gold=gold, quiz_name=self.quiz.name)
def pass_level(self, quest): """ Pass current level. Increment current level and score. """ if self.current_quest.id != quest.id: return None scoring.score(self, QuestGame, quest.get_formula('quest-ok'), level=(self.current_level + 1), external_id=quest.id) self.current_level += 1 if self.current_level == quest.count: self.finish_quest() scoring.score(self, QuestGame, quest.get_formula('quest-finish-ok'), external_id=quest.id) self.save() self.user.get_profile().save() return self.current_level
def _give_bonus(self, points, gold): if self.best_attempt is not None: if points > self.best_attempt.points: points = points - self.best_attempt.points gold = gold - self.best_attempt.gold scoring.score(self.user, None, "bonus-points", points=points) scoring.score(self.user, None, "bonus-gold", gold=gold) add_activity( self.user, _( "received {points} points and " "{gold} gold bonus" " for beating his/her " "highscore at quiz {quiz_name}" ), points=points, gold=gold, quiz_name=self.quiz.name, ) else: scoring.score(self.user, None, "bonus-points", points=points) scoring.score(self.user, None, "bonus-gold", gold=gold) add_activity( self.user, _("received {points} points" " and {gold} gold bonus" " for submitting quiz {quiz_name}"), points=points, gold=gold, quiz_name=self.quiz.name, )
def bazaar_exchange(request): gold_rate = scoring.calculate('gold-points-rate', gold=1)['points'] points_rate = scoring.calculate('points-gold-rate', points=1)['gold'] player = request.user.get_profile() message, error = '', '' if BoolSetting.get('setting-bazaar-exchange').get_value() is False: error = _("Exchange is disabled") elif request.method == 'POST': try: points = float(request.POST.get('points', 0)) gold = round(float(request.POST.get('gold', 0))) except: error = _('Invalid amounts') else: if points != 0: gold = points_rate * points if gold > 0: if player.points < points: error = _('Insufficient points') else: points = round(gold) / points_rate scoring.score(player, None, 'points-gold-rate', points=points) message = _('Converted successfully') else: error = _('Insufficient points') # other way around elif gold != 0: points = gold_rate * gold if player.coins['gold'] < gold: error = _('Insufficient gold') else: scoring.score(player, None, 'gold-points-rate', gold=gold) message = _('Converted successfully') else: error = _('Unknown action') else: error = _('Expected post') if error: messages.error(request, error) if message: messages.success(request, message) return render_to_response('magic/bazaar_buy.html', {'tab': 'exchange'}, context_instance=RequestContext(request))
def manage_player_set(request, player_id, task_id): player = get_object_or_404(SpecialQuestUser, id=player_id) task = get_object_or_404(SpecialQuestTask, id=task_id) if task not in player.done_tasks.all(): if player.group: members = player.group.members.all() else: members = (player,) for member in members: if task not in member.done_tasks.all(): member.done_tasks.add(task) scoring.score(member, SpecialQuestGame, 'specialquest-passed',external_id=task.id, value=task.value) return HttpResponseRedirect(reverse('specialquest_manage', args=(player.id,)))
def testScore(self): formula = Formula.add('_test_formula_sc', definition='_test=13', owner=self.game) scoring.score(self.user.get_profile(), self.game, formula, external_id=3) hs = scoring.history_for(self.user, self.game, external_id=3) self.assertTrue(isinstance(hs, QuerySet)) history = list(hs)[0] # check if specific coin has been updated self.assertEqual(history.coin, self.coin) self.assertEqual(history.amount, 13)
def manage_player(request, player_id): player = get_object_or_404(Player, pk=player_id) player = player.get_extension(SpecialQuestUser) tasks_not_done = SpecialQuestTask.objects.exclude(id__in=player.done_tasks.all().values('id')).all() # TODO: use smth like django-flash for this message, error = '', '' if request.method == "POST": # do bonuses if request.POST.get('gold', False): try: amount = int(request.POST.get('gold', 0)) except ValueError: amount = 0 if amount > 0: scoring.score(player, None, 'bonus-gold', external_id=request.user.get_profile().id, gold=amount) message = 'Successfully given bonus' if request.POST.get('comment', None): signal_msg = ugettext_noop('received {gold} gold bonus for {comment}') signals.addActivity.send(sender=None, user_from=player, user_to=player, message=signal_msg, arguments=dict(gold=amount, comment=request.POST['comment']), game=SpecialQuestGame.get_instance() ) else: error = 'Invalid amount' elif request.POST.get('points', False): try: amount = int(request.POST.get('points', 0)) #assert amount > 0 except (ValueError, AssertionError): error = 'Invalid amount' else: scoring.score(player, None, 'penalty-points', external_id=request.user.get_profile().id, points=amount) message = 'Successfully punished' bonuses = scoring.History.objects.filter(user=player, formula__name='bonus-gold').order_by('-timestamp') penalties = scoring.History.objects.filter(user=player, formula__name='penalty-points').order_by('-timestamp') if error: messages.error(request, error) if messages: messages.success(request, message) return render_to_response('specialquest/cpanel_manage.html', dict(mplayer=player, tasks_not_done=tasks_not_done, bonuses=bonuses, penalties=penalties), context_instance=RequestContext(request))
def bazaar_exchange(request): gold_rate = scoring.calculate('gold-points-rate', gold=1)['points'] points_rate = scoring.calculate('points-gold-rate', points=1)['gold'] player = request.user.get_profile() message, error = '', '' if BoolSetting.get('disable-Bazaar-Exchange').get_value(): error = _("Exchange is disabled") elif request.method == 'POST': try: points = float(request.POST.get('points', 0)) gold = round(float(request.POST.get('gold', 0))) except: error = _('Invalid amounts') else: if points != 0: gold = points_rate * points if gold > 0: if player.points < points: error = _('Insufficient points') else: points = round(gold) / points_rate scoring.score(player, None, 'points-gold-rate', points=points) message = _('Converted successfully') else: error = _('Insufficient points') # other way around elif gold != 0: points = gold_rate * gold if player.coins['gold'] < gold: error = _('Insufficient gold') else: scoring.score(player, None, 'gold-points-rate', gold=gold) message = _('Converted successfully') else: error = _('Unknown action') else: error = _('Expected post') if error: messages.error(request, error) if message: messages.success(request, message) return render_to_response('magic/bazaar_buy.html', {'tab': 'exchange'}, context_instance=RequestContext(request))
def check_answer(self, user, answer): self.error = '' if user.current_quest.id != self.id: user.finish_quest() user.set_current(self) return False try: question = self.levels[user.current_level] except IndexError: logging.error("No such question") # Get the checker path path = os.path.join(settings.FINAL_QUEST_CHECKER_PATH, 'task-%02d' % (user.current_level + 1), 'check') if not os.path.exists(path): self.error = 'No checker for level %d' % user.current_level return False # Run checker path args = [path, user.user.username, answer] work_dir = os.path.join(settings.FINAL_QUEST_CHECKER_PATH, 'task-%02d' % (user.current_level + 1)) p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=work_dir) retval = p.wait() if retval > 1: self.error = 'Error running checker for %d' % user.current_level if not user.current_level == self.count and \ (retval == 0): scoring.score(user, QuestGame, self.get_formula('quest-ok'), level=(user.current_level + 1)) user.current_level += 1 user.save() if user.current_level == self.count: user.finish_quest() scoring.score(user, QuestGame, self.get_formula('quest-finish-ok')) return True return False
def played(self): """ Both players have played, save and score Notice the fact this is the only function where the scoring is affected """ """ Handle artifacts and spells """ for u in (self.user_to, self.user_from): # always lose, you mofo if u.user.has_modifier('challenge-always-lose'): u.score = -1 # affect bonuses if u.user.has_modifier('challenge-affect-scoring'): u.percents = u.user.modifier_percents('challenge-affect-scoring') else: u.percents = 100 if self.user_to.score > self.user_from.score: result = (self.user_to, self.user_from) elif self.user_from.score > self.user_to.score: result = (self.user_from, self.user_to) else: #draw game result = 'draw' if result == 'draw': self.status = 'D' scoring.score(self.user_to.user, ChallengeGame, 'chall-draw', percents=self.user_to.percents) scoring.score(self.user_from.user, ChallengeGame, 'chall-draw', percents=self.user_from.percents) # send activty signal signal_msg = ugettext_noop('draw result between {user_to} and {user_from}:\n{extra}') signals.addActivity.send(sender=None, user_from=self.user_to.user, \ user_to=self.user_from.user, \ message=signal_msg, \ arguments=dict(user_to=self.user_to, user_from=self.user_from, extra=self.extraInfo(self.user_from, self.user_to)),\ game=ChallengeGame.get_instance()) else: self.status = 'P' self.user_won, self.user_lost = result self.winner = self.user_won.user diff_race = self.user_won.user.series != self.user_lost.user.series diff_class = self.user_won.user.proximate_group != self.user_lost.user.proximate_group diff_race = 1 if diff_race else 0 diff_class = 1 if diff_class else 0 scoring.score(self.user_won.user, ChallengeGame, 'chall-won', external_id=self.id, percents=self.user_won.percents, points=self.user_won.score, points2=self.user_lost.score, different_race=diff_race, different_class=diff_class) scoring.score(self.user_lost.user, ChallengeGame, 'chall-lost', external_id=self.id, points=self.user_lost.score, points2=self.user_lost.score) # send activty signal signal_msg = ugettext_noop('won challenge with {user_lost}: {extra}') signals.addActivity.send(sender=None, user_from=self.user_won.user, \ user_to=self.user_lost.user, \ message=signal_msg, arguments=dict(user_lost=self.user_lost, extra=self.extraInfo(self.user_won, self.user_lost)), \ game=ChallengeGame.get_instance()) self.save()
def bazaar_buy(request, spell): spell = get_object_or_404(Spell, pk=spell) player = request.user.get_profile() error, message = '','' if spell.price > player.coins.get('gold', 0): error = _("Insufficient gold amount") else: player.add_spell(spell) scoring.score(player, None, 'buy-spell', external_id=spell.id, price=spell.price) SpellHistory.bought(player, spell) message = _("Successfully aquired") return bazaar(request, message=message, error=error) # TODO: use django-flash """
def answered(user, question, choice): correct = False for i, a in enumerate(question.answers): if a.id == choice: if a.correct: correct = True break user.set_answered(choice, correct) # answer id if correct: now = datetime.now() pr = randint(0, 99) scoring.score(user, QotdGame, 'qotd-ok', hour=now.hour) if pr < settings.QOTD_BONUS_PROB: scoring.score(user, QotdGame, 'qotd-ok-bonus', hour=now.hour)
def answered(user, question, choice): correct = False for i, a in enumerate(question.answers): if a.id == choice: if a.correct: correct = True break user.set_answered(choice, correct) # answer id if correct: now = datetime.now() pr = randint(0, 99) scoring.score(user, QotdGame, 'qotd-ok', hour=now.hour); if pr < settings.QOTD_BONUS_PROB: scoring.score(user, QotdGame, 'qotd-ok-bonus', hour=now.hour)
def bonus(request, player_id): player = get_object_or_404(Player, pk=player_id) if request.method == 'POST': form = BonusForm(request.POST) if form.is_valid(): coin, amount = form.cleaned_data['coin'], form.cleaned_data[ 'amount'] formula = Formula.get('bonus-%s' % coin.name) if formula is None: messages.error(request, 'No such formula, bonus-%s' % coin.name) else: scoring.score(player, None, formula, external_id=request.user.get_profile().id, **{coin.name: amount}) if form.cleaned_data['reason']: add_activity( player, _('received {amount} {coin} bonus for {reason}'), amount=amount, coin=coin, reason=form.cleaned_data['reason']) messages.info(request, 'Successfully given bonus') return redirect('details_player', pk=player.id) else: form = BonusForm() bonuses = scoring.History.objects.filter( user=player, formula__name__startswith='bonus-').order_by('-timestamp') penalties = scoring.History.objects.filter( user=player, formula__name__startswith='penalty-').order_by('-timestamp') return render_to_response('cpanel/bonus.html', { 'target_player': player, 'form': form, 'bonuses': bonuses, 'penalties': penalties }, context_instance=RequestContext(request))
def bazaar_buy(request, spell): spell = get_object_or_404(Spell, pk=spell) player = request.user.get_profile() error, message = '','' if spell.price > player.coins.get('gold', 0): error = _("Insufficient gold amount") elif spell.available == False: error = _("Spell is not available") elif spell.level_required > player.level_no: error = _("Level {level} is required to buy this spell").format(level=spell.level_required) else: player.add_spell(spell) scoring.score(player, None, 'buy-spell', external_id=spell.id, price=spell.price) SpellHistory.bought(player, spell) message = _("Successfully aquired") return bazaar(request, message=message, error=error)
def check_answer(self, user, answer): if user.current_quest != self: user.finish_quest() user.set_current(self) return False try: question = self.levels[user.current_level] except IndexError: logging.error("No such question") return False if not user.current_level == self.count and answer.lower() == question.answers.all()[0].text.lower(): # score current progress scoring.score(user, QuestGame, self.get_formula("quest-ok"), level=(user.current_level + 1)) user.current_level += 1 if user.current_level == self.count: user.finish_quest() # score finishing scoring.score(user, QuestGame, self.get_formula("quest-finish-ok")) user.save() return True return False
def create(self, request): attrs = self.flatten_dict(request.POST) if 'spell' not in attrs.keys(): return {'success': False, 'error': 'Spell not provided'} try: spell = int(attrs['spell']) spell = Spell.objects.get(pk=spell) except (ValueError, Spell.DoesNotExist): return {'success': False, 'error': 'No such spell'} # TODO refactor player = request.user.get_profile() if spell.price > player.coins.get('gold', 0): return {'success': False, 'error': 'Insufficient gold'} else: player.add_spell(spell) scoring.score(player, None, 'buy-spell', external_id=spell.id, price=spell.price) SpellHistory.bought(player, spell) return {'success': True}
def _give_bonus(self, points, gold): if self.best_attempt is not None: if points > self.best_attempt.points: points = points - self.best_attempt.points gold = gold - self.best_attempt.gold scoring.score(self.user, None, 'bonus-points', points=points) scoring.score(self.user, None, 'bonus-gold', gold=gold) add_activity(self.user, _('received {points} points and {gold} gold bonus' ' for beating his/her highscore at quiz {quiz_name}'), points=points, gold=gold, quiz_name=self.quiz.name) else: scoring.score(self.user, None, 'bonus-points', points=points) scoring.score(self.user, None, 'bonus-gold', gold=gold) add_activity(self.user, _('received {points} points and {gold} gold bonus' ' for submitting quiz {quiz_name}'), points=points, gold=gold, quiz_name=self.quiz.name)
def give_level_bonus(self): final = QuestGame.get_final() if not final: return for level in xrange(len(self.levels) + 1): if level == 0: continue users = QuestUser.objects.filter(current_quest=final, current_level__gte=level, race__can_play=True) for user in users: scoring.score( user, QuestGame, self.get_formula('finalquest-ok'), level=level, level_users=users.count() ) signal_msg = ugettext_noop("received bonus for reaching level {level} in the final quest") signals.addActivity.send(sender=None, user_from=user, user_to=user, message=signal_msg, arguments=dict(level=level), game=QuestGame.get_instance() )