Ejemplo n.º 1
0
async def scramble(ctx):
    guild = ctx.message.guild
    logging.info(guild)
    players = models.Player_list()
    players.load_all()
    for p in players.items:
        old_team_id = p.team_id
        # Pick a number & update player
        team_id = randint(1, 3)
        if old_team_id != team_id:
            p.team_id = team_id
            p.update()
            old_team = models.Team()
            old_team.load(old_team_id)
            team = models.Team()
            team.load(team_id)
            # Clear/Assign role
            old_team_role = get(guild.roles, name=old_team.name)
            team_role = get(guild.roles, name=team.name)
            member = guild.get_member(int(p.discord_id))
            if member is None:
                logging.info(
                    "Player w/ id {} not found. Maybe they left the server.".
                    format(p.discord_id))
                continue
            await member.remove_roles(old_team_role,
                                      reason="Automated Team Scramble")
            await member.add_roles(team_role, reason="Automated Team Scramble")
            logging.info("{} (ID:{}) moved from {} to {}".format(
                member.nick, p.discord_id, old_team.name, team.name))
            await asyncio.sleep(1)
    models.save()
    logging.info("Scramble complete")
Ejemplo n.º 2
0
async def on_member_join(member):
    pa_chan = get(member.guild.text_channels, name="player-assignments")
    ins_chan = get(member.guild.text_channels, name="instructions")
    # Assign the new member to one of the three teams randomly
    # FIXME Get number of teams through the DB and not hardcode a 3
    team_id = randint(1, 3)
    t = models.Team()
    t.load(team_id)
    # Add flair to user
    role = get(member.guild.roles, name=t.name)
    await member.add_roles(role)
    # Create new Player record.
    p = models.Player()
    # First check if they already exist
    try:
        p.custom_load("discord_id = ?", (member.id, ))
        t.load(p.team_id)
        await pa_chan.send("Welcome back, {}! the **{}** missed you!".format(
            member.mention, t.name))
        return
    except Exception:
        pass
    p.discord_id = member.id
    p.team_id = team_id
    p.coins = config['starting_coins']
    p.last_active_day = 0
    p.shares = 100
    p.insert()
    models.save()

    # Post message to player-assignments channel
    await pa_chan.send("Welcome, {}! You have been assigned to the **{}**!\n\
        Make sure to check out the {} and good luck!".format(
        member.mention, t.name, ins_chan.mention))
Ejemplo n.º 3
0
async def pay(ctx, target_location, amount):
    if not config['game_ongoing']: return

    amount = int(amount)  # dumb.
    member = ctx.message.author
    p = models.Player()
    try:
        p.custom_load("discord_id = ?", (member.id, ))
    except Exception:
        await ctx.send("I don't have you listed as a player, {}\n\
            If you believe this is an error, please talk to a Lord or the King"
                       .format(member.mention))
        return
    # Make sure player has enough coins!!!
    if amount < 1:
        await ctx.send("You can't pay 0 or negative coins, {}".format(
            member.mention))
        return
    elif amount > p.coins:
        await ctx.send("{}, you don't have enough coins!".format(
            member.mention))
        return
    # Get team, current location id, available locations
    t = models.Team()
    t.load(p.team_id)
    current_loc = t.current_location_id
    avail_locs = graphanalyzer.get_next_location_list(t.team_id)
    # Make sure it's a valid target location.
    if target_location.lower() not in (name.lower()
                                       for name in avail_locs.keys()):
        await ctx.send(
            "I don't think {} is a valid location. Maybe you mistyped it?".
            format(target_location))
        return
    # Get the ID for the target location...
    target_loc = models.Location()
    target_loc.custom_load("name = ? COLLATE NOCASE", (target_location, ))

    edge = models.LocationEdge()
    edge.custom_load("start_location_id = ? AND end_location_id = ?", (
        current_loc,
        target_loc.location_id,
    ))
    # Store the payment in the db
    payment = models.Payment()
    payment.player_id = p.player_id
    payment.team_id = p.team_id
    payment.amount = amount
    payment.location_edge = edge.edge_id
    payment.time = helpers.get_game_day()
    payment.insert()

    # Remove coins from player's account.
    p.coins -= amount
    p.last_active_day = helpers.get_game_day()
    p.update()
    models.save()
    # Send confirmation message.
    await ctx.send("{} has paid **{}** coins toward **{}**".format(
        member.mention, amount, target_loc.name))
Ejemplo n.º 4
0
async def team(ctx):
    if not config['game_ongoing']: return
    member = ctx.message.author
    try:
        p = models.Player()
        p.custom_load("discord_id = ?", (member.id, ))
        if p.last_active_day != helpers.get_game_day():
            p.last_active_day = helpers.get_game_day()
            p.update()
            models.save()
    except Exception:
        await ctx.send("I don't think you're playing, {}\n\
            (If you think this is a mistake, please talk to a Lord or the King)"
                       .format(member.mention))
        return
    t = models.Team()
    t.load(p.team_id)
    l = models.Location()
    l.load(t.current_location_id)
    funding_table = paymentreducer.get_funding_table(p.team_id,
                                                     helpers.get_game_day())
    await ctx.send(
        "Your team is in **{}**, with at least **{}km** to go!\nHere is how today's funding is going:\n{}"
        .format(
            l.name,
            graphanalyzer.dijkstra(graphanalyzer.graph, t.current_location_id,
                                   0), "```" + funding_table + "```"))
Ejemplo n.º 5
0
async def spectate(ctx):
    member = ctx.message.author
    player = models.Player()
    team = models.Team()
    try:
        player.custom_load("discord_id = ?", (str(member.id), ))
        team.load(player.team_id)
    except Exception as e:
        await ctx.send(
            "I think you're already out of the game, {}. If you think this was a mistake, please talk to a Lord or the King"
            .format(member.mention))
        logging.error(e)
        return
    # Remove flair from user
    role = get(member.guild.roles, name=team.name)
    await member.remove_roles(role, reason='Player left game')
    # Add spectator role
    role = get(member.guild.roles, name='Spectator')
    await member.add_roles(role, reason='Player left game')

    player.delete()
    models.save()

    logging.info("{} has switched to spectating".format(member.id))
    await ctx.send("{}, you're now a spectator. Enjoy the show!".format(
        member.mention))
Ejemplo n.º 6
0
def player_update():
    sys.stdout.flush()
    my_scraper = scraper.NBADataScraper()
    headers, data = my_scraper.set_players()
    update_players(data)
    players = models.Player.query.all()
    for player in players:
        if player.last_scraped and (not player.active or player.last_scraped >= datetime.datetime.utcnow()):
            pass
        else:
            print(player.get_name(), player.nba_id)
            random.seed()
            time.sleep(random.randint(1, 3))
            headers, data = my_scraper.get_play_season_totals(player.nba_id)
            for season in data:
                season = {i[0]: i[1] for i in zip(headers[0], season)}
                if season['TEAM_ABBREVIATION'] == 'Tot':
                    pass
                else:
                    nba_season = models.Season.query.filter_by(season_code=season['SEASON_ID']).first()
                    if not nba_season:
                        nba_season = models.Season()
                        nba_season.season_code = season['SEASON_ID']
                        nba_season.season_start = int(season['SEASON_ID'].split("-")[0])
                        nba_season.season_end = nba_season.season_start + 1

                        nba_season.add_object()

                    team = models.Team.query.filter_by(nba_team_id=season['TEAM_ID']).first()
                    if not team:
                        team = models.Team()
                        team.nba_team_id = season['TEAM_ID']
                        team.team_abbr = season['TEAM_ABBREVIATION']

                        team.add_object()
                    player_season = models.PlayerSeason.query.filter_by(player_id=player.player_id,
                                                                        season_id=nba_season.season_id,
                                                                        team_id=team.team_id).first()
                    updating_season = True
                    if not player_season:
                        player_season = models.PlayerSeason()
                        updating_season = False
                    player_season.player_id = player.player_id
                    player_season.season_id = nba_season.season_id
                    player_season.team_id = team.team_id
                    for item in season:
                        attr = player_season.get_attr_title(item)
                        if attr:
                            setattr(player_season, attr, season[item])
                    if updating_season:
                        player_season.update_object()
                    else:
                        player_season.add_object()

            player.last_scraped = datetime.datetime.utcnow()

            player.update_object()

    return "Player Seasons Gotten"
Ejemplo n.º 7
0
def check_click(hex_id):
    player_selected = None
    # TODO replace with match class
    current_teams = ["Rage", "Peace"]
    players_on_field = []
    for team_name in current_teams:
        players_on_field = players_on_field + models.Team(
            team_name).player_list
    for player_x in players_on_field:
        if models.Player(player_x).current_tile == hex_id:
            player_selected = player_x
    return player_selected
Ejemplo n.º 8
0
def getAllTeams(min, max):
    totalTeams = []
    for pos in range(min, max):
        name = getSingleData(data4, "Add Your Team Name", pos)
        users = getSingleData(
            data4,
            "List ALL members of your team. Please ONLY put your team members discord username. DO NOT include their tag. DO NOT include their current nickname. (separate users between one comma and one space) Example: Darrow8, Povellesto",
            pos)
        newTeam = md.Team(users=users, name=name, desc=None, sht_desc=None)
        totalTeams.append(newTeam)

    return totalTeams
Ejemplo n.º 9
0
    def GetTeam(self, team_id):
        """
        Returns team with id from database
        """
        self.mydb.commit()
        mycursor = self.mydb.cursor()
        mycursor.execute("SELECT * FROM Teams WHERE id = %(id)s",
                         {'id': team_id})

        team = mycursor.fetchone()
        mycursor.close()

        if team is not None:
            return models.Team(team)
        else:
            return None
Ejemplo n.º 10
0
    def GetTeams(self, jam_id):
        """
        Returns a list of teams from jam with id from database
        """
        self.mydb.commit()
        mycursor = self.mydb.cursor()
        expression = "SELECT * FROM Teams WHERE Jam_id = %s;"
        mycursor.execute(expression, (jam_id, ))

        teams = []
        row = mycursor.fetchone()
        while row is not None:
            team = models.Team(row)
            teams.append(team)
            row = mycursor.fetchone()

        mycursor.close()
        return teams
Ejemplo n.º 11
0
def team_attempt_move(team_id):
    process_log = ""
    # Load team.
    t = models.Team()
    t.load(team_id)
    flns = paymentreducer.get_funding_list(team_id,
                                           helpers.get_game_day() - 1, False)
    fl = paymentreducer.get_funding_list(team_id,
                                         helpers.get_game_day() - 1, True)

    # Check for best-funded succesful path
    new_loc = t.current_location_id
    biggest_funding = -1
    was_sabotaged = False
    for k, v in flns.items():
        le = models.LocationEdge()
        le.load(k)
        if v >= le.weight and v > biggest_funding:
            new_loc = le.end_location_id
            biggest_funding = v
            if fl[k] < le.weight:
                was_sabotaged = True
            else:
                was_sabotaged = False

    if biggest_funding == -1:
        process_log = "The {} didn't raise enough to book passage anywhere...".format(
            t.name)
    else:
        l = models.Location()
        l.load(new_loc)
        if was_sabotaged:
            process_log = "The {} tried to travel to {}, but someone sabotaged them and they were stopped by the Black Cats!".format(
                t.name, l.name)
        else:
            t.current_location_id = new_loc
            t.update()
            process_log = "The {} have successfully reached {}!".format(
                t.name, l.name)

    models.save()
    return process_log + "\n"
Ejemplo n.º 12
0
async def join(ctx):
    member = ctx.message.author
    if config['game_ongoing']:
        await ctx.send(
            "Sorry, {}, you can't join the game while it's ongoing!".format(
                member.mention))
        return
    p = models.Player()
    # Make sure player doesn't already exist
    try:
        p.custom_load('discord_id = ?', (member.id, ))
        await ctx.send(
            "I think you're already playing, {}. If you think this is an error, please talk to a Lord or the King"
            .format(member.mention))
        return
    except Exception:
        pass
    # Pick a team
    team_id = randint(1, 3)
    team = models.Team()
    team.load(team_id)

    # Add flair to user
    role = get(member.guild.roles, name=team.name)
    await member.add_roles(role, reason='Player joined game')
    # Remove spectator role
    role = get(member.guild.roles, name='Spectator')
    if role in member.roles:
        await member.remove_roles(role, reason='Player joined game')

    # Create new player
    p.discord_id = member.id
    p.team_id = team_id
    p.coins = config['starting_coins']
    p.last_active_day = 0
    p.shares = 100
    p.insert()
    models.save()
    logging.info("{} has joined the {}".format(member.id, team.name))
    await ctx.send("{}, you've been added to the **{}**! Good Luck!".format(
        member.mention, team.name))
Ejemplo n.º 13
0
def get_next_location_list(team_id):
    locations = {}

    team = models.Team()
    team.load(team_id)
    edges = models.LocationEdge_list()
    edges.custom_load("start_location_id = ?", (team.current_location_id, ))
    # Load end locations
    ls = models.Location_list()
    # HACK HACK HACK
    ls.custom_load(
        "location_id IN ({})".format(','.join(["?"] * len(edges.items))),
        [x.end_location_id for x in edges.items])

    # MUCH BIGGER HACK that could have been solved with a join instead but why bother
    for l in ls.items:
        locations[l.name] = list(
            filter(lambda x: x.end_location_id == l.location_id,
                   edges.items))[0].weight

    return locations
Ejemplo n.º 14
0
def get_funding_table(team_id, day=-1):
    #f = get_funding_list(team_id, day=helpers.get_game_day(), show_sabotage=False)
    f = get_funding_list(team_id, day, show_sabotage=False)
    if len(f.keys()) == 0:
        return "No payments have been made yet today!"

    t = models.Team()
    t.load(team_id)
    tab = []
    row_format = "{:<18}{:<8}{:<8}\n"
    tab.append(row_format.format('Location', 'Toll', 'Paid'))
    tab.append("-" * (34) + "\n")
    # FIXME toooo many queries
    for k, v in f.items():
        le = models.LocationEdge()
        le.load(k)
        l = models.Location()
        l.load(le.end_location_id)
        tab.append(row_format.format(l.name, le.weight, v))

    return "".join(tab)
Ejemplo n.º 15
0
def action_possible_hexes(action_selected, current_gui, current_field):
    possible_hexes = []
    if action_selected == "Move":
        # find options to move
        current_hex_id = models.Player(
            current_gui.player_id_selected).current_tile
        adj_hexes = current_field.adjacent_hexes(current_hex_id)
        for hex_id in adj_hexes:
            player_occupied = check_click(hex_id)
            if player_occupied is None:
                possible_hexes.append(hex_id)
    elif action_selected == "Throw":
        # find options to throw
        current_hex_id = models.Player(
            current_gui.player_id_selected).current_tile
        current_teams = ["Rage", "Peace"]
        players_on_field = []
        player_hexes = []
        for team_name in current_teams:
            players_on_field = players_on_field + models.Team(
                team_name).player_list
        # check validity of throw, only sideways and back passes
        check_y = current_field.current_field[current_hex_id].hex_coord_y
        for player_x in players_on_field:
            hex_x = current_field.current_field[models.Player(
                player_x).current_tile]
            if hex_x.hex_coord_y <= check_y:
                possible_hexes.append(hex_x.hex_id)
    elif action_selected == "Tackle":
        # find options to tackle
        current_hex_id = models.Player(
            current_gui.player_id_selected).current_tile
        adj_hexes = current_field.adjacent_hexes(current_hex_id)
        for hex_id in adj_hexes:
            player_occupied = check_click(hex_id)
            if player_occupied is not None:
                possible_hexes.append(hex_id)
    else:
        print("Error, action not possible: ", action_selected)
    return possible_hexes
Ejemplo n.º 16
0
async def validateteams(ctx):
    bad = 0
    guild = ctx.message.guild
    logging.info(guild)
    players = models.Player_list()
    players.load_all()
    for p in players.items:
        member = guild.get_member(int(p.discord_id))
        t = models.Team()
        t.load(p.team_id)
        if member is None:
            logging.info(
                "Player w/ id {} not found. Maybe they left the server.".
                format(p.discord_id))
        else:
            if member.top_role.name != t.name:
                logging.error(
                    "{} (ID:{})'s role is {}, but it should be {}".format(
                        member.nick, p.discord_id, member.top_role.name,
                        t.name))
                bad += 1
    logging.info("Validation done. {}/{} roles are correct.".format(
        len(players.items) - bad, len(players.items)))
Ejemplo n.º 17
0
def init_db():
    import models

    # Creating tables
    Base.metadata.create_all(bind=engine)

    # Populating Release table
    release = models.Release()
    release.name = 'All'
    db_session.add(release)

    release = models.Release()
    release.name = 'Kilo'
    db_session.add(release)

    release = models.Release()
    release.name = 'Juno'
    db_session.add(release)

    release = models.Release()
    release.name = 'Icehouse'
    db_session.add(release)

    release = models.Release()
    release.name = 'Havana'
    db_session.add(release)

    release = models.Release()
    release.name = 'Grizzly'
    db_session.add(release)

    release = models.Release()
    release.name = 'Folsom'
    db_session.add(release)

    release = models.Release()
    release.name = 'Essex'
    db_session.add(release)

    release = models.Release()
    release.name = 'Diablo'
    db_session.add(release)

    release = models.Release()
    release.name = 'Cactus'
    db_session.add(release)

    release = models.Release()
    release.name = 'Bexar'
    db_session.add(release)

    release = models.Release()
    release.name = 'Austin'
    db_session.add(release)
    db_session.commit()

    # Populating User table
    user1 = models.User()
    user1.name = 'Arx Cruz'
    user1.email = '*****@*****.**'
    user1.user_id = 'arxcruz'
    db_session.add(user1)

    user2 = models.User()
    user2.name = 'David Kranz'
    user2.email = '*****@*****.**'
    user2.user_id = 'david-kranz'
    db_session.add(user2)

    user3 = models.User()
    user3.name = 'Arx Cruz Delete'
    user3.email = '*****@*****.**'
    user3.user_id = 'arxcruz'
    db_session.add(user3)
    db_session.commit()

    # Populating team
    team = models.Team()
    team.name = 'Demo team 1'
    team.users.append(user1)
    team.users.append(user2)
    db_session.add(team)

    team = models.Team()
    team.name = 'Demo team 2'
    team.users.append(user1)
    team.users.append(user2)
    db_session.add(team)
    db_session.commit()

    report = models.CustomReport()
    report.name = 'Test'
    report.description = 'Test description'
    report.url = 'http://www.redhat.com'
    db_session.add(report)

    report = models.CustomReport()
    report.name = 'Test'
    report.description = 'Test description'
    report.url = ('http://www.thisisaverybigurl.com/?withalotofinformation'
                  'topassthroughblablablaaasfasfdasfdasfasfdasdfasdfasdfasdf')
    db_session.add(report)
    db_session.commit()
Ejemplo n.º 18
0
def seed():
    """Seed the database with sample data."""
    import models
    # the rooms

    room_features = ['Projector', 'TV', 'Webcam', 'Phone Line']

    rooms = {
        '1560': ['Projector'],
        '1561': ['TV', 'Webcam'],
        '1562': ['Projector'],
        '1563': ['TV'],
        '1564': ['Projector'],
        '1565': ['TV', 'Webcam'],
        '1665': ['TV', 'Webcam'],
        '1663': ['TV'],
        '1662': ['Projector'],
        '1661': ['Projector'],
        '1660': ['Projector']
    }

    feature_dict = {}
    for feature in room_features:
        f = models.RoomFeature(name=feature)
        get_db().add(f)
        feature_dict[feature] = f

    rooms_dict = {}
    for room_number in rooms:
        r = models.Room(number=room_number)
        for feature in rooms[room_number]:
            f = feature_dict[feature]
            r.features.append(f)
        rooms_dict[room_number] = r
        get_db().add(r)

    # the types of team
    teamtype_dict = {}
    teamtype_dict['single'] = models.TeamType(
        name='single',
        priority=4,
        advance_time=7 * 2  # 2 weeks
    )
    get_db().add(teamtype_dict['single'])
    get_db().add(
        models.TeamType(
            name='other_team',
            priority=4,
            advance_time=7 * 2  # 2 weeks
        ))
    get_db().add(
        models.TeamType(
            name='class',
            priority=3,
            advance_time=7 * 2  # 2 weeks
        ))
    get_db().add(
        models.TeamType(
            name='colab_class',
            priority=2,
            advance_time=7 * 2  # 2 weeks
        ))
    get_db().add(
        models.TeamType(
            name='senior_project',
            priority=1,
            advance_time=7 * 2  # 2 weeks
        ))

    # the permissions

    perm_names = [
        'team.create', 'team.create.elevated', 'team.delete',
        'team.delete.elevated', 'team.read', 'team.read.elevated',
        'team.update', 'team.update.elevated', 'reservation.create',
        'reservation.delete', 'reservation.delete.elevated',
        'reservation.read', 'reservation.update',
        'reservation.update.elevated', 'room.update.elevated',
        'room.create.elevated', 'room.read', 'room.delete.elevated',
        'feature.create', 'feature.delete', 'feature.update', 'feature.read',
        'role.create', 'role.delete', 'role.update'
    ]
    perm_dict = {}
    for perm in perm_names:
        p = models.Permission(name=perm)
        get_db().add(p)
        perm_dict[perm] = p

    roles = {
        'student': [
            'team.create', 'team.delete', 'team.read', 'team.update',
            'reservation.create', 'reservation.delete', 'reservation.read',
            'reservation.update', 'room.read', 'feature.read'
        ],
        'labbie': [
            'team.create', 'team.delete', 'team.read', 'team.update',
            'reservation.create', 'reservation.delete', 'reservation.read',
            'reservation.update', 'room.read', 'feature.read',
            'team.read.elevated'
        ],
        'professor': [
            'team.create', 'team.delete', 'team.read', 'team.update',
            'reservation.create', 'reservation.delete', 'reservation.read',
            'reservation.update', 'room.read', 'feature.read',
            'team.create.elevated', 'team.read.elevated'
        ],
        'admin': [
            'team.create', 'team.create.elevated', 'team.delete',
            'team.delete.elevated', 'team.read', 'team.read.elevated',
            'team.update', 'team.update.elevated', 'reservation.create',
            'reservation.delete', 'reservation.delete.elevated',
            'reservation.read', 'reservation.update',
            'reservation.update.elevated', 'room.update.elevated',
            'room.create.elevated', 'room.read', 'room.delete.elevated',
            'feature.create', 'feature.delete', 'feature.update',
            'feature.read', 'role.create', 'role.delete', 'role.update'
        ]
    }
    users_dict = {}
    for role in roles:
        r = models.Role(name=role)
        for permission in roles[role]:
            p = perm_dict[permission]
            r.permissions.append(p)
        get_db().add(r)
        # seed a user TODO don't do this in production?
        u = models.User(name=role, email=role + "@example.com")
        u.roles.append(r)
        team = models.Team(u.name)
        team_type = teamtype_dict['single']
        team.team_type = team_type
        team.members.append(u)
        u.teams.append(team)
        users_dict[role] = u
        get_db().add(team)
        get_db().add(u)

    reservation = models.Reservation(
        start=datetime.datetime.now() + datetime.timedelta(days=7),
        end=datetime.datetime.now() + datetime.timedelta(days=7, hours=1),
        team=users_dict['admin'].teams[0],
        room=rooms_dict['1660'],
        created_by=users_dict['admin'])
    get_db().add(reservation)

    get_db().commit()
Ejemplo n.º 19
0
def db_start():
    engine = create_engine('sqlite:///tmp/test.db', convert_unicode=True)
    db.create_all()
    db.session.commit()

    user = models.User()
    user.username = "******"
    user.password = sha256_crypt.encrypt("pppp1234")
    user.email = '*****@*****.**'
    user.job = "szef projektu"
    user.admin = True
    user.poweruser = True
    user.organizer = True
    user.birthdate = "01.01.1999"
    user.about = "Jestem dobrym adminem"
    user.why = "Chcę organizować gamejam, poniewż uważam, że jest to jest to idealna forma rozwoju dla młodych ludzi."
    db.session.add(user)
    db.session.commit()

    user = models.User()
    user.username = "******"
    user.password = sha256_crypt.encrypt("pppp1234")
    user.email = '*****@*****.**'
    user.job = "szef projektu"
    user.admin = True
    user.poweruser = True
    user.organizer = True
    user.birthdate = "01.01.1999"
    user.about = "Jestem dobrym adminem"
    user.why = "Chcę organizować gamejam, poniewż uważam, że jest to jest to idealna forma rozwoju dla młodych ludzi."
    db.session.add(user)
    db.session.commit()

    user = models.User()
    user.username = "******"
    user.password = sha256_crypt.encrypt("wikwoj")
    user.email = '*****@*****.**'
    user.job = "pierwszy user"
    user.admin = False
    user.poweruser = True
    user.organizer = True
    user.birthdate = "01.01.1889"
    user.about = "Jestem dobrym szefem"
    user.why = "Chcę zwyciężyć każdy jam"
    db.session.add(user)
    db.session.commit()

    user = models.User()
    user.username = "******"
    user.password = sha256_crypt.encrypt("marek")
    user.email = '*****@*****.**'
    user.job = "programista"
    user.admin = False
    user.poweruser = True
    user.organizer = False
    user.birthdate = "01.01.1889"
    db.session.add(user)
    db.session.commit()

    user = models.User()
    user.username = "******"
    user.password = sha256_crypt.encrypt("stefan")
    user.email = '*****@*****.**'
    user.job = "dzwiękowiec"
    user.admin = False
    user.poweruser = True
    user.birthdate = "01.01.1889"
    db.session.add(user)
    db.session.commit()

    team = models.Team()
    team.name = "BestTeam"
    team.master = "patryk"
    team.master_email = '*****@*****.**'
    team.contributors = ['adam', 'innygosc', 'jakiskoles']
    team.gameinjams = ['Jam testowy', 'Pierwszy jam', 'Ten jam nie istnieje']
    db.session.add(team)
    db.session.commit()

    team = models.Team()
    team.name = "DrużynaWygrywów"
    team.master = "wikwoj"
    team.master_email = '*****@*****.**'
    team.contributors = ['wikwoj', 'bedegralwgre', 'jestemhardkorem']
    team.gameinjams = [
        'Jam testowy', 'Szybki jam', 'Ten jam nie istnieje', 'Global game jam'
    ]
    db.session.add(team)
    db.session.commit()

    team = models.Team()
    team.name = "MonsterCouch"
    team.master = "marek"
    team.master_email = '*****@*****.**'
    team.contributors = ['Krzyś', 'artur', 'Helena']
    team.gameinjams = [
        'Pierwszy jam', 'Szybki jam', 'Ten jam nie istnieje', 'Global game jam'
    ]
    db.session.add(team)
    db.session.commit()

    team = models.Team()
    team.name = "LameTeam"
    team.master = "stefan"
    team.master_email = '*****@*****.**'
    team.contributors = ['Chyzio', 'Zyzio', 'Dyzio']
    team.gameinjams = ['Pierwszy jam', 'Szybki', 'Global game jam']
    db.session.add(team)
    db.session.commit()

    message = models.Message()
    message.title = 'testowa wiadomość'
    message.adresser = 'patryk'
    message.author = 'wikwoj'
    message.content = 'No hej'
    message.created = datetime.now()
    db.session.add(message)
    db.session.commit()

    jam = models.Jam()
    jam.title = "Jam testowy"
    jam.master = "patryk"
    jam.theme = "destruction"
    jam.description = "Jam o rozwalaniu"
    jam.master_email = '*****@*****.**'
    jam.teams = ['BestTeam', "DrużynaWygrywów"]
    jam.active = False
    db.session.add(jam)
    db.session.commit()

    game = models.Game()
    game.title = "Demolition n' Destruction"
    game.team = "BestTeam"
    game.description = 'gra o rozwalaniu i zniszczeniu'
    game.jam = 'Jam testowy'
    game.path = "Demolition n' Destruction.zip"
    db.session.add(game)
    db.session.commit()

    game = models.Game()
    game.title = "Diablo Origins"
    game.team = "DrużynaWygrywów"
    game.description = 'gra o niszczniu potworów'
    game.jam = 'Jam testowy'
    game.path = "Diablo Origins.zip"
    db.session.add(game)
    db.session.commit()

    jam = models.Jam()
    jam.title = "Pierwszy jam"
    jam.master = "patryk"
    jam.theme = "destruction"
    jam.description = "Jam o rozwalaniu"
    jam.master_email = '*****@*****.**'
    jam.teams = ['BestTeam', "MonsterCouch", 'LameTeam']
    db.session.add(jam)
    db.session.commit()

    game = models.Game()
    game.title = "Doom 0"
    game.team = "BestTeam"
    game.description = 'Prequel Doom'
    game.jam = 'Pierwszy jam'
    game.path = "Doom 0.zip"
    db.session.add(game)
    db.session.commit()

    game = models.Game()
    game.title = "Jabba The Hutt - Fat worm story"
    game.team = "MonsterCouch"
    game.description = 'Przemierzaj pustynię Tatooine pod postacią grubego robaka i zjadaj szturmowców'
    game.jam = 'Pierwszy jam'
    game.path = "Jabba The Hutt - Fat worm story.zip"
    db.session.add(game)
    db.session.commit()

    game = models.Game()
    game.title = "Devil ain't cry"
    game.team = "LameTeam"
    game.description = 'Doprowadź diabła do płaczu'
    game.jam = 'Pierwszy jam'
    game.path = "devil ain't cry.zip"
    db.session.add(game)
    db.session.commit()

    jam = models.Jam()
    jam.title = "Szybki jam"
    jam.master = "wikwoj"
    jam.theme = "Stranger things"
    jam.description = "Jam o dziwnych i zwariowanych grach"
    jam.master_email = '*****@*****.**'
    jam.teams = ['DrużynaWygrywów', 'MonsterCouch', 'LameTeam']
    db.session.add(jam)
    db.session.commit()

    game = models.Game()
    game.title = "Lightsaber tactics"
    game.team = "DrużynaWygrywów"
    game.description = 'Platformowa gra 2D, w której poruszasz się zbuntowanym rycerzem Jedi i zabijasz młodych adeptów'
    game.jam = 'Szybki jam'
    game.path = "Lightsaber tactics.zip"
    db.session.add(game)
    db.session.commit()

    game = models.Game()
    game.title = "Quit now"
    game.team = "MonsterCouch"
    game.description = 'Ciężka gra platformowa'
    game.jam = 'Szybki jam'
    game.path = "Quit now.zip"
    db.session.add(game)
    db.session.commit()

    game = models.Game()
    game.title = "Worms arena"
    game.team = "LameTeam"
    game.description = 'Bijesz się na areni będąc robakiem'
    game.jam = 'Szybki jam'
    game.path = "worms arena.zip"
    db.session.add(game)
    db.session.commit()

    jam = models.Jam()
    jam.title = "Ten jam nie istnieje"
    jam.master = "patryk"
    jam.theme = "matrix"
    jam.description = "Jam o niebyciu"
    jam.master_email = '*****@*****.**'
    jam.teams = ['DrużynaWygrywów', 'BestTeam', 'MonsterCouch']
    jam.active = False
    db.session.add(jam)
    db.session.commit()

    game = models.Game()
    game.title = "Satelite destroyer"
    game.team = "BestTeam"
    game.description = 'Jako operator działa niszcz zbliżające się satelity wroga'
    game.jam = 'Ten jam nie istnieje'
    game.path = "Satelite destroyer.zip"
    db.session.add(game)
    db.session.commit()

    game = models.Game()
    game.title = "Wolfenstein: the old order"
    game.team = "DrużynaWygrywów"
    game.description = 'Gra, w której musisz zabić Wiliama Josepha Blazkowicza'
    game.jam = 'Ten jam nie istnieje'
    game.path = "Wolfenstein the old order!.zip"
    db.session.add(game)
    db.session.commit()

    game = models.Game()
    game.title = "Path of Neo"
    game.team = "MonsterCouch"
    game.description = 'Symulator Wiary'
    game.jam = 'Ten jam nie istnieje'
    game.path = "Path of neo.zip"
    db.session.add(game)
    db.session.commit()

    jam = models.Jam()
    jam.title = "Global game jam"
    jam.master = "wikwoj"
    jam.theme = "Wszystkie gry"
    jam.description = "Jam, w ktorym tolerowane sa wszystkie gatunki gier"
    jam.master_email = '*****@*****.**'
    jam.teams = ['DrużynaWygrywów', "MonsterCouch", 'LameTeam']
    jam.active = False
    db.session.add(jam)
    db.session.commit()

    game = models.Game()
    game.title = "Military trucks"
    game.team = "MonsterCouch"
    game.description = 'Prosta gra wyścigowa z pojazdami wojskowymi'
    game.jam = 'Global game jam'
    game.path = "Military trucks.tar.zip"
    db.session.add(game)
    db.session.commit()

    game = models.Game()
    game.title = "Battle of tatooine"
    game.team = "DrużynaWygrywów"
    game.description = 'Jako operator działa niszcz zbliżające się statki wroga'
    game.jam = 'Global game jam'
    game.path = "Battle of tatooine.zip"
    db.session.add(game)
    db.session.commit()

    game = models.Game()
    game.title = "Shoot fast! Don't die!"
    game.team = "LameTeam"
    game.description = 'Multiplayer FPS typu arena'
    game.jam = 'Global game jam'
    game.path = "Shoot fast! Don't die!.zip"
    db.session.add(game)
    db.session.commit()
Ejemplo n.º 20
0
def drawBoard(field_current, gui_current):
    # Draw background of board.
    DISPLAYSURF.blit(BGIMAGE, BGIMAGE.get_rect())

    board_width_hexes = 7
    board_height_hexes = 5
    unique_id = 0
    hex_x = 0

    # draw hexagon field
    for x in range(board_width_hexes):
        hex_x += 1
        hex_y = 0

        for y in range(board_height_hexes):
            hex_y += 1
            hex_details = models.Hex()
            hex_side = SPACESIZE / math.sqrt(3)
            hex_height_tip = abs(math.sin(math.degrees(30)) * hex_side)
            hex_radius = abs(math.cos(math.degrees(30)) * hex_side)

            # even row
            if x % 2 == 0:
                starty = (y * 2 * hex_radius) + YMARGIN
                startx = (x * (hex_side + hex_height_tip)) + XMARGIN
            # odd row
            else:
                starty = (y * 2 * hex_radius + hex_radius) + YMARGIN
                startx = (x * (hex_side + hex_height_tip)) + XMARGIN

            polygon_points = [
                [hex_height_tip + startx, starty],
                [hex_height_tip + hex_side + startx, starty],
                [hex_height_tip * 2 + hex_side + startx, hex_radius + starty],
                [hex_height_tip + hex_side + startx, hex_radius * 2 + starty],
                [hex_height_tip + startx, hex_radius * 2 + starty],
                [startx, hex_radius + starty]
            ]

            unique_id += 1
            center_x = int(startx + hex_height_tip + (hex_side / 2))
            center_y = int(starty + hex_radius)

            if field_current.field_layout[unique_id] == "field":
                pygame.draw.polygon(DISPLAYSURF, DARKGRAY, polygon_points, 5)

            # Label tiles, can hide
            font_obj = pygame.font.Font('freesansbold.ttf', 15)
            coord_to_write = "(" + str(hex_x) + ", " + str(hex_y) + ") " + str(
                unique_id)
            text_surface_object = font_obj.render(coord_to_write, True, BLACK)
            text_rect_object = text_surface_object.get_rect()
            text_rect_object.center = (center_x, center_y)
            DISPLAYSURF.blit(text_surface_object, text_rect_object)

            # assign tiles values and then make the field dict of hex class
            hex_details.hex_id = unique_id
            hex_details.hex_coord_x = hex_x
            hex_details.hex_coord_y = hex_y
            hex_details.pix_box_x = startx
            hex_details.pix_box_y = starty
            hex_details.center_pix_x = center_x
            hex_details.center_pix_y = center_y
            field_current.current_field.setdefault(unique_id, hex_details)

    # Draw the players
    # TODO replace with either Match class or store this in the field?
    teams_in_match = ["Peace", "Rage"]
    human_team_name = "Rage"
    all_player_list = []
    human_team_list = []
    for team_name in teams_in_match:
        team_x = models.Team(team_name)
        all_player_list = team_x.player_list + all_player_list
        if team_name is human_team_name:
            human_team_list = team_x.player_list
    for player_id in all_player_list:
        player_x = models.Player(player_id)
        hex_x = field_current.current_field[player_x.current_tile]
        team_x = models.Team(player_x.team_name)
        if team_x.team_color == "blue":
            tile_color = BLUE
        elif team_x.team_color == "red":
            tile_color = RED
        elif team_x.team_color == "white":
            tile_color = WHITE
        else:
            tile_color = BLACK
        pygame.draw.circle(DISPLAYSURF, tile_color,
                           (hex_x.center_pix_x, hex_x.center_pix_y),
                           PLAYERSIZE)
        font_obj = pygame.font.SysFont('couriernew.ttf', 25)
        if "Captain" in player_x.title:
            player_title = "C"
        elif "Tank" in player_x.title:
            player_title = "T"
        else:
            player_title = "WTF"
        text_surface_object = font_obj.render(player_title, True, BLACK,
                                              tile_color)
        text_rect_object = text_surface_object.get_rect()
        text_rect_object.center = (hex_x.center_pix_x, hex_x.center_pix_y)
        DISPLAYSURF.blit(text_surface_object, text_rect_object)

    topbar_surface = pygame.Surface((BOARDWIDTH * SPACESIZE, YMARGIN - 10))
    topbar_surface.fill(LIGHTERBLUE)
    details_font = pygame.font.SysFont('couriernew.ttf', 40)
    to_blit_list = [[topbar_surface, (5 + XMARGIN, 5)]]
    text_color = BLACK
    text_row = gui_current.top_message
    text_surf = details_font.render(text_row, True, text_color, LIGHTERBLUE)
    y_pos = int(YMARGIN / 2)
    x_pos = XMARGIN + int(BOARDWIDTH * SPACESIZE / 2)
    text_rect = text_surf.get_rect(center=(x_pos, y_pos))
    to_blit_list.append([text_surf, text_rect])
    DISPLAYSURF.blits(to_blit_list)

    # Draw the player menu and selected player
    if gui_current.player_id_selected is not None and gui_current.player_highlight is True:
        current_field_dict = field_current.current_field

        # circle around selected player
        hex_to_highlight = models.Player(
            gui_current.player_id_selected).current_tile
        player_x = current_field_dict[hex_to_highlight].center_pix_x
        player_y = current_field_dict[hex_to_highlight].center_pix_y
        pygame.draw.circle(DISPLAYSURF, YELLOW, (player_x, player_y),
                           PLAYERSIZE, 2)

        # player details on left side
        sidebar_surface = pygame.Surface(
            (XMARGIN - 10, int(BOARDWIDTH * SPACESIZE / 2)))
        sidebar_surface.fill(DARKGRAY)
        details_font = pygame.font.SysFont('couriernew.ttf', 25)
        text_row_list = ["Player Details"]
        row_i = 1
        to_blit_list = [[sidebar_surface, (5, YMARGIN)]]
        text_row_list.append(
            "Name: " +
            models.Player(gui_current.player_id_selected).player_name)
        text_row_list.append(
            "Team: " + models.Player(gui_current.player_id_selected).team_name)
        text_row_list.append(
            "Title: " + models.Player(gui_current.player_id_selected).title)
        for row in text_row_list:
            text_surf = details_font.render(row, True, GREEN, DARKGRAY)
            y_pos = YMARGIN + int((SPACESIZE * row_i) / 2)
            row_i += 1
            text_rect = text_surf.get_rect(center=(int((XMARGIN - 5) / 2),
                                                   y_pos))
            to_blit_list.append([text_surf, text_rect])
        DISPLAYSURF.blits(to_blit_list)

        # if player character, the show action menu
        # can store menu as a dict with positions in gui_current, actions come from player class
        action_list = ["Move", "Throw", "Tackle"]
        action_button_dict = {}
        if gui_current.player_id_selected in human_team_list:
            sidebar_surface = pygame.Surface(
                (XMARGIN - 10, BOARDWIDTH * SPACESIZE))
            sidebar_surface.fill(LIGHTGRAY)
            details_font = pygame.font.SysFont('couriernew.ttf', 25)
            text_row_list = ["Action Menu"]
            row_i = 1
            to_blit_list = [[
                sidebar_surface,
                (5 + XMARGIN + BOARDWIDTH * SPACESIZE, YMARGIN)
            ]]
            for action_x in action_list:
                text_row_list.append(action_x)
            for row in text_row_list:
                # cheat for not showing options when not possible
                text_color = WHITE
                if field_current.ball_hex == models.Player(gui_current.player_id_selected).current_tile and \
                        row == "Tackle":
                    text_color = LIGHTGRAY
                elif field_current.ball_hex != models.Player(gui_current.player_id_selected).current_tile and \
                        row == "Throw":
                    text_color = LIGHTGRAY
                text_surf = details_font.render(row, True, text_color,
                                                LIGHTGRAY)
                y_pos = YMARGIN + int((SPACESIZE * row_i) / 2)
                x_pos = XMARGIN + BOARDWIDTH * SPACESIZE + int(XMARGIN / 2)
                text_rect = text_surf.get_rect(center=(x_pos, y_pos))
                if row_i > 1:  # not box around the menu title
                    button_rect_shape = pygame.Rect(text_rect.top,
                                                    text_rect.left,
                                                    XMARGIN - 30,
                                                    int(SPACESIZE / 2))
                    button_rect_shape.centerx = int(XMARGIN / 2)
                    button_rect_shape.centery = int(row_i * SPACESIZE / 2)
                    button_rect = pygame.draw.rect(sidebar_surface, DARKGRAY,
                                                   button_rect_shape, 2)
                    action_button_dict.setdefault(row, button_rect_shape)
                row_i += 1
                to_blit_list.append([text_surf, text_rect])
            DISPLAYSURF.blits(to_blit_list)
            gui_current.button_dict = action_button_dict

    # reset ball if not in play
    if field_current.ball_hex is None:
        field_current.ball_hex = 16
    ball_x = field_current.current_field[
        field_current.ball_hex].center_pix_x - int(SPACESIZE / 5)
    ball_y = field_current.current_field[
        field_current.ball_hex].center_pix_y + int(SPACESIZE / 3)
    pygame.draw.circle(DISPLAYSURF, BRIGHTBLUE, (ball_x, ball_y),
                       int(SPACESIZE / 5))

    # draw highlighted hexes for actions
    if len(gui_current.possible_hexes) > 0:
        for hex_id in gui_current.possible_hexes:
            highlight_x = field_current.current_field[hex_id].center_pix_x
            highlight_y = field_current.current_field[hex_id].center_pix_y
            pygame.draw.circle(DISPLAYSURF, YELLOW, (highlight_x, highlight_y),
                               PLAYERSIZE - 5, 2)

    return field_current, gui_current
Ejemplo n.º 21
0
def implement_moves(current_field, move_list):
    # TODO implement results display
    for move_x in move_list:
        if move_x.action_type == "Move":
            # check if player is still there
            if models.Player(
                    move_x.player_action).current_tile == move_x.hex_start:
                # check if end space is free
                # TODO replace with match class
                teams_in_play = ["Rage", "Peace"]
                all_player_hexes = []
                for team_x in teams_in_play:
                    all_player_hexes = all_player_hexes + models.Team(
                        team_x).players_field_hexes()
                if move_x.hex_end not in all_player_hexes:
                    # move player
                    player_0 = models.Player(move_x.player_action)
                    player_0.current_tile = move_x.hex_end
                    player_0.update_db()
        elif move_x.action_type == "Throw":
            print("Throw")
        elif move_x.action_type == "Tackle":
            # check if player is still there
            if models.Player(
                    move_x.player_action).current_tile == move_x.hex_start:
                # check if end space has an opponent
                teams_in_play = ["Rage", "Peace"]
                all_player_hexes = []
                for team_x in teams_in_play:
                    all_player_hexes = all_player_hexes + models.Team(
                        team_x).players_field_hexes()
                if move_x.hex_end in all_player_hexes and \
                        move_x.hex_end != models.Player(move_x.player_action).current_tile:
                    # move player
                    player_0 = models.Player(move_x.player_action)
                    player_0.current_tile = move_x.hex_end
                    player_0.update_db()
                    # move tackled player
                    player_1 = models.Player(check_click(move_x.hex_end))
                    tackle_complete = False
                    hex_3_x = None
                    hex_3_y = None
                    while tackle_complete is False:
                        hex_0 = current_field.current_field[move_x.hex_start]
                        hex_1 = current_field.current_field[
                            player_1.current_tile]
                        delta_x = 0
                        delta_y = 0
                        if hex_0.hex_coord_x == hex_1.hex_coord_x:
                            delta_x = 0
                            if hex_0.hex_coord_y > hex_1.hex_coord_y:
                                delta_y = -1
                            else:
                                delta_y = 1
                        elif hex_0.hex_coord_x > hex_1.hex_coord_x:
                            delta_x = -1
                            if hex_0.hex_coord_y == hex_1.hex_coord_y:
                                delta_y = -1
                        else:
                            delta_x = 1
                            if hex_0.hex_coord_y == hex_1.hex_coord_y:
                                delta_y = -1
                        hex_3_x = hex_1.hex_coord_x + delta_x
                        hex_3_y = hex_1.hex_coord_y + delta_y
                        # TODO check for player already in place and resolve
                        tackle_complete = True
                    for hex_id, hex_x in current_field.current_field.items():
                        if hex_x.hex_coord_x == hex_3_x and hex_x.hex_coord_y == hex_3_y:
                            player_1.current_tile = hex_id
                            player_1.update_db()
                elif move_x.hex_end == models.Player(
                        move_x.player_action).current_tile:
                    print("Self-tackle")
                else:
                    print("No one to tackle", move_x.hex_end, all_player_hexes)
            # move both players
        else:
            print("action not found ", move_x.action_type)
    return current_field
Ejemplo n.º 22
0
def runGame():

    # get the right database for the starting players
    db_creation.clean_db()
    db_creation.new_db_empty()
    db_creation.fill_db()

    # set the stage
    turn = 'player'
    current_match = models.Match()
    current_match.match_number = 1
    current_match.match_teams = ["Rage", "Peace"]
    current_match.human_team = "Rage"
    starting_field = models.Field()
    starting_gui = models.Gui()

    current_field, current_gui = drawBoard(starting_field, starting_gui)

    while True:  # main game loop
        # Keep looping for player and computer's turns.
        player_move_commit_list = []
        computer_move_commit_list = []
        if turn == 'player':
            # Player's turn:
            moves_committed = False
            moves_commit_list = []
            while moves_committed is False:
                # Keep looping until the player submits three moves
                checkForQuit()
                for event in pygame.event.get():  # event handling loop
                    if event.type == MOUSEBUTTONUP:
                        # Handle mouse click events
                        mousex, mousey = event.pos
                        hex_id, button_name = getSpaceClicked(
                            mousex, mousey, current_field, current_gui)
                        player_selected = check_click(hex_id)

                        if current_gui.action_selection is False and player_selected is not None:
                            # print(hex_id,models.Player(player_selected).player_name)
                            current_gui.player_highlight = True
                            current_gui.player_id_selected = player_selected
                            if player_selected in models.Team(
                                    current_match.human_team).player_list:
                                current_gui.action_menu = True
                                current_gui.top_message = "Choose an action for " + models.Player(
                                    player_selected).player_name
                        elif button_name is not None:
                            # draw possible hexes for an action
                            current_gui.possible_hexes = action_possible_hexes(
                                button_name, current_gui, current_field)
                            if len(current_gui.possible_hexes) > 0:
                                current_gui.action_selection = True
                                current_gui.action_to_do = button_name
                                current_gui.top_message = "Choose a hex for " + button_name
                            # TODO add back button or someway to cancel selection
                        elif hex_id in current_gui.possible_hexes and current_gui.action_selection is True:
                            # after hex selected
                            move_commit_x = action_commit(hex_id, current_gui)
                            moves_commit_list.append(move_commit_x)
                            current_gui.action_selection = False
                            current_gui.action_to_do = None
                            current_gui.possible_hexes = []
                            current_gui.player_id_selected = None
                            current_gui.player_highlight = False
                            m2 = len(
                                models.Team(
                                    current_match.human_team).player_list)
                            m1 = len(moves_commit_list)
                            current_gui.top_message = str(
                                m1) + " out of " + str(m2) + " moves committed"

                # update drawing of game board
                current_field, current_gui = drawBoard(current_field,
                                                       current_gui)

                # update display
                MAINCLOCK.tick(FPS)
                pygame.display.update()

                # checks if all moves_committed
                if len(moves_commit_list) >= len(
                        models.Team(current_match.human_team).player_list):
                    moves_committed = True
                    current_gui.top_message = "Player's turn complete. Computer's turn."
                    player_move_commit_list = moves_commit_list

            # End the turn
        else:
            # Computer's turn:

            current_field, current_gui = drawBoard(current_field, current_gui)

            # Make it look like the computer is thinking by pausing a bit.
            pauseUntil = time.time() + random.randint(5, 15) * 0.1
            while time.time() < pauseUntil:
                pygame.display.update()

            current_gui.top_message = "Computer turn complete. Human's turn"

        current_field = implement_moves(current_field, player_move_commit_list)

        # update board
        current_field, current_gui = drawBoard(current_field, current_gui)

        # update display
        MAINCLOCK.tick(FPS)
        pygame.display.update()

        # Only set for the player's turn if they can make a move.
        turn = 'player'
Ejemplo n.º 23
0
async def sabotage(ctx, target_team, target_location, amount):
    if not config['game_ongoing']: return
    # just pay() but with negative coins and another team
    amount = int(amount)  # still dumb
    member = ctx.message.author
    p = models.Player()
    try:
        p.custom_load("discord_id = ?", (member.id, ))
    except Exception:
        await ctx.send(
            "Gonna be hard to sabotage when I don't have you listed as a player, {}\n\
            If you believe this is a mistake, please talk to a Lord or the King"
            .format(member.mention))
        return
    # Mke sure player has enough coins
    if amount < 1:
        await ctx.send("You can't pay 0 or negative coins, {}".format(
            member.mention))
        return
    elif amount > p.coins:
        await ctx.send("{}, you don't have enough coins!".format(
            member.mention))
        return

    t = models.Team()
    try:
        t.custom_load("name = ? COLLATE NOCASE",
                      (target_team, ))  # TODO make this more user-friendly
    except Exception:
        await ctx.send(
            "I don't think {} is a real team, {}. Make sure you type the full name!"
            .format(target_team, member.mention))
        return

    if t.team_id == p.team_id:
        await ctx.send(
            "You can't sabotage your own team, {}!!! They won't like you for that!"
            .format(member.mention))
        return

    current_loc = t.current_location_id
    avail_locs = graphanalyzer.get_next_location_list(t.team_id)
    # Validate target location...
    if target_location.lower() not in (name.lower()
                                       for name in avail_locs.keys()):
        await ctx.send(
            "I don't think {} is a valid location. Maybe a typo?".format(
                target_location))
        return
    # Get id for the target location...
    location = models.Location()
    location.custom_load("name = ? COLLATE NOCASE", (target_location, ))

    edge = models.LocationEdge()
    edge.custom_load("start_location_id = ? AND end_location_id = ?",
                     (current_loc, location.location_id))

    # Store the payment!
    payment = models.Payment()
    payment.player_id = p.player_id
    payment.team_id = t.team_id
    payment.amount = -amount  # VERY IMPORTANT DIFFERENCE
    payment.location_edge = edge.edge_id
    payment.time = helpers.get_game_day()
    payment.insert()

    # Remove coins from the player's account
    p.coins -= amount
    p.last_active_day = helpers.get_game_day()
    p.update()
    models.save()
    # Send confirmation message.
    await ctx.send(
        "{} has paid **{}** coins to sabotage the **{}'** trip to **{}**".
        format(member.mention, amount, t.name, location.name))
Ejemplo n.º 24
0
def main():
    conn = pymysql.connect(host=migrate_config.OLD_HOST,
                           port=migrate_config.OLD_PORT,
                           user=migrate_config.OLD_USER,
                           password=migrate_config.OLD_PASSWORD,
                           db=migrate_config.OLD_DATABASE)
    joined_teams: Dict[int, List[int]] = {}
    user_admin_teams: Dict[int, List[int]] = {}
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    cursor.execute("SELECT * FROM users")
    print("loading user...")
    for item in cursor.fetchall():
        joined_teams[item["id"]] = json.loads(item["joined_teams"])
        print(item["username"])
        user = models.User(id=item["id"],
                           banned=item["banned"],
                           username=item["username"],
                           password=item["password"],
                           description=item["description"],
                           email=item["email"],
                           register_time=item["register_time"],
                           rating_history=json.loads(item["rating_history"]),
                           rating=item["rating"],
                           permission_group=item["permission_group"],
                           permissions=json.loads(item["permissions"]),
                           force_logout_before=item["force_logout_before"],
                           phone_number=None,
                           phone_verified=False)
        db.session.add(user)
    db.session.commit()
    print("loading problems...")
    cursor.execute("SELECT * FROM problems")
    for item in cursor.fetchall():
        print(item["id"], item["title"])
        prob = models.Problem(id=item["id"],
                              uploader_id=item["uploader_id"],
                              title=item["title"],
                              background=item["background"],
                              content=item["content"],
                              input_format=item["input_format"],
                              output_format=item["output_format"],
                              hint=item["hint"],
                              example=json.loads(item["example"]),
                              files=json.loads(item["files"]),
                              downloads=json.loads(item["downloads"]),
                              provides=json.loads(item["provides"]),
                              subtasks=json.loads(item["subtasks"]),
                              public=item["public"],
                              spj_filename=item["spj_filename"],
                              using_file_io=item["using_file_io"],
                              input_file_name=item["input_file_name"],
                              output_file_name=item["output_file_name"],
                              problem_type=item["problem_type"],
                              can_see_results=item["can_see_results"],
                              create_time=item["create_time"],
                              extra_parameter=json.loads(
                                  item["extra_parameter"]),
                              remote_judge_oj=item["remote_judge_oj"],
                              remote_problem_id=item["remote_problem_id"],
                              cached_submit_count=0,
                              cached_accepted_count=0,
                              team_id=None,
                              invite_code=str(uuid.uuid1()),
                              submission_visible=True)
        db.session.add(prob)
    db.session.commit()
    print("loading submissions...")
    cursor.execute("SELECT * FROM submissions")
    for item in cursor.fetchall():
        print(item["id"])
        item.update(
            dict(judge_result=json.loads(item["judge_result"]),
                 selected_compile_parameters=json.loads(
                     item["selected_compile_parameters"])))
        submission = models.Submission(**item)
        db.session.add(submission)
    db.session.commit()
    print("loading contests..")
    cursor.execute("SELECT * FROM contest")
    for item in cursor.fetchall():
        print(item["id"])
        item.update(dict(closed=False, problems=json.loads(item["problems"])))
        contest = models.Contest(**item)
        db.session.add(contest)
    db.session.commit()
    print("loading teams..")
    cursor.execute("SELECT * FROM team")
    for item in cursor.fetchall():
        team = models.Team(id=item["id"],
                           name=item["name"],
                           description=item["description"],
                           owner_id=item["owner_id"],
                           tasks=json.loads(item["tasks"]),
                           create_time=item["create_time"],
                           invite_code=str(uuid.uuid1()),
                           private=False,
                           team_contests=[],
                           team_problems=[],
                           team_problemsets=[])
        for uid in item["admins"]:
            if uid not in user_admin_teams:
                user_admin_teams[uid] = []
            user_admin_teams[uid].append(item["id"])
        db.session.add(team)
    db.session.commit()
    for user, teams in joined_teams.items():
        admin_teams = user_admin_teams.get(user, set())
        for x in teams:
            db.session.add(
                models.TeamMember(uid=user,
                                  team_id=x,
                                  is_admin=x in admin_teams))
    db.session.commit()
    print("loading permission groups..")
    db.session.query(models.PermissionGroup).delete()
    db.session.commit()
    cursor.execute("SELECT * FROM permission_groups")
    for item in cursor.fetchall():
        item.update(dict(permissions=json.loads(item["permissions"])))
        db.session.add(models.PermissionGroup(**item))
    db.session.commit()
    print("loading problemsets...")
    cursor.execute("SELECT * FROM problem_set")
    for item in cursor.fetchall():
        item.update(dict(problems=json.loads(item["problems"])))
        db.session.add(models.ProblemSet(**item))
    db.session.commit()
    print("loading remote accounts...")
    cursor.execute("SELECT * FROM remote_accounts")
    for item in cursor.fetchall():
        item.update(dict(session=item["session"]))
        db.session.add(models.RemoteAccount(**item))
    db.session.commit()
    print("loading discussions..")
    cursor.execute("SELECT * FROM discussions")
    for item in cursor.fetchall():
        db.session.add(models.Discussion(**item, private=False))
    db.session.commit()
    print("loading comments..")
    cursor.execute("SELECT * FROM comments")
    for item in cursor.fetchall():
        if not db.session.query(
                models.Discussion).filter_by(id=item["discussion_id"]).count():
            continue
        db.session.add(models.Comment(**item))
    db.session.commit()
    print("Done!")
Ejemplo n.º 25
0
def ask_for_teams_at_event(event_code):
    """
    Return an list of teams at the event code event_code
    :param event_code the TBA code of the event
    :return a list of Team objects
    """
    teams_filename = '{}-teams.json'.format(event_code)

    # Check if list of teams already exists
    try:
        with open(teams_filename, 'r') as f:
            teams_from_file = json.loads(f.read())
            local_teams = [
                models.Team(tba_dictionary=team, from_file=True)
                for team in teams_from_file
            ]
            logger.info('Loaded teams from {}'.format(teams_filename))
            return local_teams
    except FileNotFoundError:
        logger.info('no previously saved base team info. fetching.')

    endpoint = 'https://www.thebluealliance.com/api/v3/event/{}/teams/simple'.format(
        event_code)
    headers = {'X-TBA-Auth-Key': tba_key}
    logger.info('Asking for teams at event from {}'.format(endpoint))
    if event_code in last_asked['teams_at_event']:
        modified_since = last_asked['teams_at_event'][event_code]
        logger.info('Using If-Modified-Since: {}'.format(modified_since))
        headers['If-Modified-Since'] = modified_since

    r = None
    try:
        r = requests.get(endpoint, headers=headers)
    except requests.exceptions.ConnectionError as e:
        logger.error('Connection error while requesting event code {}'.format(
            event_code))
        return []

    logger.info('Status code: {}'.format(r.status_code))
    if r.status_code == 304:
        logger.info('No change in teams at event since last request')
    elif r.status_code != 200:
        return

    response_json = r.json()
    local_teams = []
    for team in response_json:
        team_object = models.Team(tba_dictionary=team)
        local_teams.append(team_object)
    logger.info('Added {} teams: {}'.format(
        len(local_teams),
        ', '.join([str(team.number) for team in local_teams])))

    last_asked['teams_at_event'][event_code] = r.headers['Last-Modified']

    teams_as_dicts = [team.__dict__ for team in local_teams]
    teams_filename = '{}-teams.json'.format(event_code)
    with open(teams_filename, 'w') as f:
        f.write(json.dumps(teams_as_dicts))

    return local_teams
Ejemplo n.º 26
0
 def read_tournament(self, json):
     # Se recuperan los datos del JSON
     league = models.League(self.league_name)
     tournament = models.Tournament(discord_id=self.discord_id,
                                    tournament_name=self.tournament)
     # Ultima actualizacion de goblin spy
     tournament.last_update = json["Info"]["rows"][0][3]
     # Se guardan las instancias de equipos
     all_teams = {}
     ranking = models.Ranking()
     # Lista de los equipos inscritos ordenados por puntuación
     ranking_data = json["LeagueStandings"]["rows"]
     for team_data in ranking_data:
         # team[10] es la casilla del coachbame. Get_Coach revisa si el nombre está inscrito en la DB de usuarios
         recover_coach = self.get_coach(team_data[10])
         coach = models.Coach(team_data[10], team_data[10])
         if recover_coach != team_data[10]:
             coach.display_name = recover_coach[0]
             coach.user_discord_id = recover_coach[1]
         # Se guarda la raza como el emoticono de la raza (bb<race_name>)
         team = models.Team(coach=coach,
                            team_name=team_data[17],
                            race=bloodBowl.Get_Race(int(team_data[16])),
                            wins=team_data[22],
                            draws=team_data[23],
                            loses=team_data[24],
                            rank=team_data[18],
                            td=team_data[25])
         ranking.add_team(team)
         all_teams[team.team_name] = team
     # Primero se recuperan los datos del histórico. Después, si la competición no es de tipo escalera y tiene partidos programados, se recuperan estos, incluidos los ya jugados
     # NOTA: Se crea una nueva instancia de un mismo partido porque en el json no hay ningun identificador comun entre Matches y Schedule
     # Recuoperación del histórico
     tournament.ranking = ranking
     history = models.History()
     matches_data = json["Matches"]["rows"]
     for match_data in matches_data:
         match = models.Match(local_team=all_teams[match_data[14]],
                              visitor_team=all_teams[match_data[17]],
                              local_score=match_data[15],
                              visitor_score=match_data[16],
                              status="played",
                              played_time=match_data[4])
         history.add_match(match)
     tournament.match_history = history
     schedule_data = json["Schedule"]["rows"]
     if schedule_data == None or len(schedule_data) == 0:
         tournament_type = "ladder"
     else:
         tournament_type = schedule_data[0][7]
         schedule = models.Schedule()
         for match_data in schedule_data:
             match = models.Match(local_team=all_teams[match_data[19]],
                                  visitor_team=all_teams[match_data[25]],
                                  local_score=match_data[29],
                                  visitor_score=match_data[30],
                                  status=match_data[10])
             if match.status == "scheduled":
                 if schedule.current_round == 0:
                     schedule.current_round = match_data[8]
                 # Recupera si los usuarios de dicord han establecido una hora para jugar
                 match.programmed_time = self.get_programmed_time(match)
             schedule.add_match(match_data[8], match)
         tournament.schedule = schedule
     league.add_tournament(tournament)
     return league
Ejemplo n.º 27
0
                       ("Peace", "200", "white")]
        cursor.executemany('''INSERT INTO teams (team_name, team_id, team_color) VALUES (?,?,?)''', teams_tuple)
    except Exception as e:
        print("Fill failed", e)
    try:
        # technically a list of tuples, replace later with an excel or back db?
        players_tuple = [(5000, "Bloodbeard", "Captain", 17, "Rage"),
                         (5001, "Meatwall", "Tank", 18, "Rage"),
                         (5002, "Love Dragon", "Captain", 20, "Peace"),
                         (5003, "Flower", "Tank", 14, "Peace")]
        cursor.executemany(
            '''INSERT INTO players (id, player_name, title, current_tile,team_name) VALUES (?,?,?,?,?)''',
            players_tuple)
    except Exception as e:
        print("Fill failed", e)
    db.commit()
    db.close()

# TODO connect to mongoDB at startup

# # run functions
# clean_db()
# new_db_empty()
# fill_db()
# p1 = models.Player(5000)
# print(p1.player_name, p1.current_tile)
team1 = models.Team("Peace")
print(team1.player_list, team1.team_color)
team1 = models.Team("Rage")
print(team1.player_list, team1.team_color)
Ejemplo n.º 28
0
def create_user_team(db: Session, team: schemas.TeamCreate, worker_id: int):
    db_team = models.Team(**team.dict(), owner_id=worker_id)
    db.add(db_team)
    db.commit()
    db.refresh(db_team)
    return db_team