示例#1
0
def ask_firm_init(player_id):

    # -------  Get needed objects  ----------------------------------------------------------------- #

    p = Players.objects.get(player_id=player_id)
    rd = Round.objects.get(round_id=p.round_id)

    # -------  Log stuff -------------------------------------------------------------------------- #

    utils.log("Player {} for room {} and round {} ask init: t is {}.".format(
        player_id, p.room_id, rd.round_id, rd.t),
        f=utils.fname(), path=__path__)

    # -------  Maybe client has to wait the other player ------------------------------------------ #

    if player.dialog.client_has_to_wait_over_player(player_id=player_id, called_from=__path__ + ':' + utils.fname()):

        if not room.dialog.is_trial(player_id, utils.fname()):

            opp_progression = player.dialog.get_opponent_progression(
                player_id=player_id,
                called_from=__path__ + ':' + utils.fname()
            )
            return parameters.error["wait"], opp_progression  # Tuple is necessary!! '-1' hold for wait

    # Get information necessary for firm initialization
    d = data.get_init_info(player_id=player_id)

    return rd.t, d["firm_state"], d["player"]["position"], d["player"]["price"], d["player"]["profits"], \
        d["opp"]["position"], d["opp"]["price"], d["opp"]["profits"], rd.ending_t
示例#2
0
def registered_as_player(request):

    username = request.POST["username"].lower()
    rsp = room.client.registered_as_player(username)

    if rsp:
        return ("reply", utils.fname(), 1) + rsp

    else:
        return "reply", utils.fname(), 0
示例#3
0
def room_available(request):

    username = request.POST["username"].lower()
    utils.log("{} asks for a room available.".format(username),
              f=utils.fname(),
              path=__path__)

    # 1 if a room is available, else 0
    rsp = room.client.room_available()

    return "reply", utils.fname(), rsp
示例#4
0
def include_players_into_round_compositions(room_id, player_id, called_from):

    utils.log("Called by '{}'".format(called_from),
              f=utils.fname(),
              path=__path__)
    return composition.include_players_into_round_compositions(
        room_id, player_id)
示例#5
0
def connect(request):

    username = request.POST["username"].lower()
    password = request.POST["password"]

    went_well = room.client.connect(username=username, password=password)
    return "reply", utils.fname(), int(went_well)
示例#6
0
def get_opponent_progression(player_id):
    """
    :return: The percentage of opponent progression
     in the previous round
    """

    p = Players.objects.get(player_id=player_id)
    opp = Players.objects.filter(room_id=p.room_id).exclude(player_id=player_id).first()

    if p.state == room.state.pve:
        progression = tutorial.dialog.get_tutorial_progression(
                player_id=opp.player_id,
                called_from=__path__ + ':' + utils.fname()
            )
    else:
        comp = RoundComposition.objects.filter(player_id=opp.player_id)
        rd = None

        for c in comp:
            rd = Round.objects.get(round_id=c.round_id)
            if rd.state == room.state.pve:
                break

        progression = (rd.t / rd.ending_t) * 100

    return str(rnd(progression))
示例#7
0
    def post(self, request, *args, **kwargs):

        """
        Room creation process
        :param request: using POST request
        :return: html room form template (success or fail)
        """

        if request.POST["form_function"] == "room_organisation":

            form = RoomForm(request.POST)

            if form.is_valid():

                with transaction.atomic():
                    try:
                        # Create room
                        room.dashboard.create(form.get_data())
                    except IntegrityError:
                        utils.log("Room already exists!", f=utils.fname(), path=__path__, level=2)

                return redirect("/room_management")

            else:
                context = {"subtitle": "Set parameters and create a room", "form": form}
                return render(request, self.template_name, context)

        else:
            raise Exception("Error validating the form.")
示例#8
0
def register_as_user(user, user_mail, nationality, gender, age, mechanical_id):

    user = Users.objects.filter(username=user_mail).first()

    if user is None:

        password = _generate_password()

        if mail.send(user_mail=user_mail, password=password):

            entry = Users(username=user_mail,
                          email=user_mail,
                          password=password,
                          nationality=nationality,
                          gender=gender,
                          age=age,
                          mechanical_id=mechanical_id,
                          time_last_request=timezone.now(),
                          last_request=utils.fname())
            entry.save()

            return True

        else:
            return False
    else:
        return False
示例#9
0
def send_password_again(user_mail, nationality, gender, age, mechanical_id):

    entry = Users.objects.filter(username=user_mail).first()

    if entry is not None:
        password = entry.password
        new = False

    else:
        password = _generate_password()
        new = True

    if mail.send(user_mail=user_mail, password=password):
        if new:
            entry = Users(username=user_mail,
                          email=user_mail,
                          password=password,
                          nationality=nationality,
                          gender=gender,
                          age=age,
                          mechanical_id=mechanical_id,
                          time_last_request=timezone.now(),
                          last_request=utils.fname())
            entry.save()

        return True

    else:
        return False
示例#10
0
def _register_as_player(username):

    utils.log("I registered {}".format(username),
              f=utils.fname(),
              path=__path__)

    rm = Room.objects.exclude(missing_players=0).exclude(
        opened=0).order_by("missing_players").first()

    if Players.objects.filter(player_id=rm.player_0).first():
        player_id = rm.player_1
    else:
        player_id = rm.player_0

    # Decrease missing_players
    rm.missing_players -= 1

    # If round pve does not welcome additional players
    if rm.missing_players == 0:
        rm.opened = 0

    rm.save()

    # assign player_id to user
    user = Users.objects.get(username=username)
    user.player_id = player_id
    user.save()

    round_id = round.dialog.include_players_into_round_compositions(
        room_id=rm.room_id,
        player_id=player_id,
        called_from=__path__ + ":" + utils.fname())

    # When we create player entry, we associate him to a pve round id
    # because he needs to pass it in order to do pvp
    pp = Players(
        player_id=player_id,
        room_id=rm.room_id,
        round_id=round_id,
        state=state.tutorial,
        registration_time=timezone.now(),
    )

    pp.save()

    return pp
示例#11
0
def close(room_id):

    entry = Room.objects.get(room_id=room_id)
    entry.opened = 0
    entry.save()
    utils.log("The room {} is now closed.".format(room_id),
              f=utils.fname(),
              path=__path__)
示例#12
0
def submit_tutorial_progression(request):

    player_id = request.POST["player_id"]
    tutorial_progression = float(request.POST["tutorial_progression"].replace(
        ",", "."))
    tutorial.client.record_tutorial_progression(
        player_id=player_id, tutorial_progression=tutorial_progression)
    return "reply", utils.fname()
示例#13
0
def ask_firm_passive_opponent_choice(player_id, t):

    # -------  Get needed objects  ----------------------------------------------------------------- #

    p = Players.objects.get(player_id=player_id)
    rd = Round.objects.get(round_id=p.round_id)

    # -------  Get needed variables --------------------------------------------------------------- #

    agent_id = RoundComposition.objects.get(round_id=rd.round_id, player_id=player_id).agent_id
    opponent_id = (agent_id + 1) % parameters.n_firms

    # -------  Log stuff -------------------------------------------------------------------------- #
    utils.log("Firm passive {} of room {} and round {} asks for opponent strategy.".format(
        player_id, p.room_id, rd.round_id
    ),
        f=utils.fname(), path=__path__)

    utils.log(
        "Client's time is {}, server's time is {}.".format(t, rd.t),
        f=utils.fname(), path=__path__
    )

    # ---------- Record call ------------------------------------------------------------------ #

    if t <= rd.t:

        # Make bot firm play if applicable
        if state.check_if_bot_firm_has_to_play(rd.round_id, t):
            state.check_if_consumers_have_to_play(round_id=rd.round_id, t=t)

        # Get the state (possibly new)
        rs = RoundState.objects.get(round_id=rd.round_id, t=t)

        if rs.firm_active_played:
            positions, prices = data.get_positions_and_prices(round_id=rd.round_id, t=t)
            return t, positions[opponent_id], prices[opponent_id]

        else:
            utils.log("Have to wait: Active firm needs to play", f=utils.fname(), path=__path__)
            return parameters.error["wait"],  # Tuple is necessary!!

    else:
        utils.log("Error: Time is superior!!!!", f=utils.fname(), path=__path__, level=3)
        return parameters.error["time_is_superior"],  # Time is superior!
示例#14
0
def proceed_to_registration_as_player(request):

    username = request.POST["username"].lower()

    with transaction.atomic():
        try:
            rsp = room.client.proceed_to_registration_as_player(
                username=username)

        except IntegrityError:
            transaction.rollback()
            return "reply", "error", "player_id_is_unique"

    if rsp:
        return ("reply", utils.fname(), 1) + rsp

    else:
        return "reply", utils.fname(), 0
示例#15
0
def _pvp_is_done(player_id):

    p = Players.objects.get(player_id=player_id)

    # Modify sate of player
    p.state = room.state.end
    p.save()

    rm = Room.objects.get(room_id=p.room_id)

    if rm.trial or _opponent_has_done_pvp(player_id=player_id):

        # Close round
        round.dialog.close_round(round_id=p.round_id, called_from=__path__ + ':' + utils.fname())

        # Close room and set state
        room.dialog.close(room_id=p.room_id, called_from=__path__ + ":" + utils.fname())
        room.dialog.update_state(room_id=p.room_id, room_state=room.state.end, called_from=__path__ + ':' + utils.fname())
示例#16
0
def check_if_bot_firm_has_to_play(round_id, t):

    # Log
    utils.log("Called", f=utils.fname(), path=__path__)

    # Get round
    rd = Round.objects.filter(round_id=round_id).first()

    # Check if round contains bots
    if rd.real_players < parameters.n_firms:

        # Get round state
        round_state = RoundState.objects.get(round_id=round_id, t=t)

        # Get firm bot
        firm_bot = RoundComposition.objects.filter(round_id=round_id,
                                                   bot=1,
                                                   role="firm").first()

        # If active firm did not play and bot firms not already played
        if firm_bot.agent_id == round_state.firm_active \
                and not round_state.firm_active_played:

            bots.firm.play(round_id=round_id, t=t)

            round_state.firm_active_played = 1

            round_state.save()

            utils.log("Bot firm played.", f=utils.fname(), path=__path__)

            return True

        else:
            utils.log("Bot firm has already played (or is not active).",
                      f=utils.fname(),
                      path=__path__)

    else:
        utils.log("Round does not contain bots.",
                  f=utils.fname(),
                  path=__path__)

    return False
示例#17
0
def close_round(round_id):

    entry = Round.objects.get(round_id=round_id)
    entry.opened = 0
    entry.save()

    # Log
    utils.log("The round {} is now closed.".format(round_id),
              f=utils.fname(),
              path=__path__)
示例#18
0
def register(request):

    user_mail = request.POST["email"].lower()
    nationality = request.POST["nationality"]
    gender = request.POST["gender"]
    age = request.POST["age"]
    mechanical_id = request.POST["mechanical_id"]

    went_well = room.client.register_as_user(user_mail=user_mail,
                                             nationality=nationality,
                                             gender=gender,
                                             age=age,
                                             mechanical_id=mechanical_id)

    if went_well:
        return "reply", utils.fname(), 1

    else:
        return "reply", utils.fname(), 0, "sending_aborted"
示例#19
0
def ask_firm_init(request):

    player_id = request.POST["player_id"]

    to_reply = round.client.ask_firm_init(player_id=player_id)

    return (
        "reply",
        utils.fname(),
    ) + to_reply
示例#20
0
    def post(self, request, *args, **kwargs):

        if "delete" in request.POST:
            room_id = request.POST["delete"]
            utils.log("Delete room {}.".format(room_id), f=utils.fname(), path=__path__)

            # Delete room
            room.dashboard.delete(room_id=room_id)

        return redirect("/room_management")
示例#21
0
def register_firm_choices(round_id, agent_id, t, price, position, called_from):

    utils.log("Called by '{}'".format(called_from),
              f=utils.fname(),
              path=__path__)
    data.register_firm_choices(round_id=round_id,
                               agent_id=agent_id,
                               t=t,
                               price=price,
                               position=position)
示例#22
0
def delete(round_id):

    utils.log(
        "Delete composition corresponding to 'round_id' '{}'".format(round_id),
        path=__path__,
        f=utils.fname())

    rc = RoundComposition.objects.filter(round_id=round_id)
    if rc.count():
        rc.delete()
示例#23
0
def ask_firm_active_choice_recording(player_id, t, position, price):

    # -------  Get needed objects  --------------------------------------------------------------- #

    p = Players.objects.get(player_id=player_id)
    rd = Round.objects.get(round_id=p.round_id)
    rs = RoundState.objects.get(round_id=rd.round_id, t=t)
    rc = RoundComposition.objects.get(round_id=rd.round_id, player_id=p.player_id)

    # -------  Log stuff ------------------------------------------------------------------------- #
    utils.log(
        "Firm active {} of room {} and round {} asks to save its price and position.".format(
            player_id, p.room_id, rd.round_id
        ), f=utils.fname(), path=__path__)

    utils.log(
        "Client's time is {}, server's time is {}.".format(t, rd.t),
        f=utils.fname(), path=__path__)

    # -------  do stuff -------------------------------------------------------------------------- #

    assert rc.agent_id == rc.agent_id, "Non matching agent_id == agent_id"

    if t <= rd.t:

        if not rs.firm_active_played:

            data.register_firm_choices(
                round_id=rd.round_id,
                agent_id=rc.agent_id,
                t=t,
                position=position,
                price=price
            )

            state.check_if_consumers_have_to_play(round_id=rd.round_id, t=t)

        return t,  # ! Must be a tuple

    else:
        utils.log("Error: Time is superior!!!!", f=utils.fname(), path=__path__, level=3)
        return parameters.error["time_is_superior"],  # Time is superior!
示例#24
0
def ask_firm_active_consumer_choices(player_id, t):

    # -------  Get needed objects  ---------------------------------------------------------------- #

    p = Players.objects.get(player_id=player_id)
    rd = Round.objects.get(round_id=p.round_id)
    rs = RoundState.objects.get(round_id=rd.round_id, t=t)

    # -------  Get needed variables --------------------------------------------------------------- #

    agent_id = RoundComposition.objects.get(round_id=rd.round_id, player_id=player_id).agent_id

    # -------  Log stuff -------------------------------------------------------------------------- #

    utils.log(
        "Firm active {} of room {} and round {} asks the number of its clients.".format(
            player_id, p.room_id, rd.round_id
        ), f=utils.fname(), path=__path__)
    utils.log("Client's time is {}, server's time is {}.".format(t, rd.t), f=utils.fname(), path=__path__)

    # ---------------- Do stuff ------------------------------------------ #

    if t <= rd.t:

        is_end = int(state.is_end_of_game(round_id=rd.round_id, t=t))

        if rs.firm_active_played:

            consumer_choices = data.get_consumer_choices(round_id=rd.round_id, t=t)
            consumer_choices = [1 if i == agent_id else 0 if i != -1 else -1 for i in consumer_choices]

            if is_end:
                player.dialog.go_to_next_round(player_id=player_id, called_from=__path__ + ':' + utils.fname())

            return (t,) + tuple((i for i in consumer_choices)) + (is_end,)

        else:
            return parameters.error["wait"],  # Tuple is necessary!!

    else:
        utils.log("Error: Time is superior!!!!", f=utils.fname(), path=__path__, level=3)
        return parameters.error["time_is_superior"],  # Time is superior!
示例#25
0
def _no_opponent_found(player_id):

    p = Players.objects.get(player_id=player_id)
    rm = Room.objects.get(room_id=p.room_id)

    not_found = rm.missing_players and _is_timed_out(p.registration_time, "no_opponent_timeout")

    if not_found:
        room.dialog.close(room_id=rm.room_id, called_from=__path__+":"+utils.fname())

    return not_found
示例#26
0
def delete(round_id):

    utils.log("Delete data corresponding to 'round_id' '{}'".format(round_id),
              path=__path__,
              f=utils.fname())

    for table in \
            (FirmPositions, FirmPrices, FirmProfits, FirmProfitsPerTurn, ConsumerChoices):
        entry = table.objects.filter(round_id=round_id)
        if entry.count():
            entry.delete()
示例#27
0
def client_request(request):
    """
    main method taking request from client
    and returning
    :param request:
    :return: response
    """

    utils.log("Post request: {}".format(list(request.POST.items())),
              f=utils.fname(),
              path=__path__)

    demand = request.POST["demand"]

    try:
        # Retrieve functions declared in the current script
        functions = {
            f_name: f
            for f_name, f in globals().items() if not f_name.startswith("_")
        }
        # Retrieve demanded function
        func = functions[demand]
    except KeyError:
        raise Exception("Bad demand")

    to_reply = "/".join((str(i) for i in func(request)))

    utils.log("I will reply '{}' to client.".format(to_reply),
              f=utils.fname(),
              path=__path__)
    response = HttpResponse(to_reply)
    response["Access-Control-Allow-Credentials"] = "true"
    response[
        "Access-Control-Allow-Headers"] = "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time"
    response["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"
    response["Access-Control-Allow-Origin"] = "*"

    return response
示例#28
0
    def login(cls, request):

        username = request.POST['username']
        password = request.POST['password']

        user = authenticate(username=username, password=password)

        if user is not None:
            utils.log("Logging {} user.".format(user), f=utils.fname(), path=__path__)
            login(request, user)
            return redirect("/room_management/")

        else:
            return render(request, cls.template_name, {"fail": 1})
示例#29
0
def play(round_id, t):
    """
    called by game.round.state
    :param round_id:
    :param t:
    :return:
    """

    room_id = Round.objects.get(round_id=round_id).room_id

    positions, prices = round.dialog.get_positions_and_prices(
        round_id=round_id, t=t, called_from=__path__ + ':' + utils.fname())

    positions_seen = room.dialog.compute_field_of_view(room_id=room_id,
                                                       to_send=False,
                                                       called_from=__path__ +
                                                       "." + utils.fname())

    entries = RoundComposition.objects.filter(round_id=round_id,
                                              bot=1,
                                              role="consumer")

    for entry in entries:

        consumer_position = entry.agent_id - parameters.n_firms

        firm_choice = _choice(positions=positions,
                              prices=prices,
                              positions_seen=positions_seen[consumer_position])

        new_entry = ConsumerChoices(round_id=round_id,
                                    agent_id=entry.agent_id,
                                    t=t,
                                    value=firm_choice)
        new_entry.save()

        entry.save()
示例#30
0
def ask_firm_active_consumer_choices(request):
    """
    called by active firm
    """

    player_id = request.POST["player_id"]
    t = int(request.POST["t"])

    to_reply = round.client.ask_firm_active_consumer_choices(
        player_id=player_id, t=t)

    return (
        "reply",
        utils.fname(),
    ) + to_reply