Esempio n. 1
0
def create_player(name, view, controller):
    player_obj = mod.Player(
        name,
        view.Player(),
        controller.Player(),
    )
    return player_obj
Esempio n. 2
0
def main():
    pygame.mixer.init()
    pygame.mixer.music.\
        load('music/Game of Thrones - Main Theme (Extended) HD.mp3')
    pygame.mixer.music.play(-1)
    ev_manager = controller.EventManager()
    game_view = view.GameView(ev_manager)
    game = model.Game(ev_manager)

    mouse_controller = controller.MouseController(ev_manager, game_view, game)
    mouse_controller.notify(events.TickEvent())
    cpu_spinner = controller.CPUSpinnerController(ev_manager)

    human_player = model.Player(game)
    human_player.set_name("Human")

    game.players.append(human_player)
    game.set_active_player(human_player)

    cpu_player = model.AIPlayer(game)
    cpu_player.set_name("AI Player")
    game.players.append(cpu_player)
    game.main_player = game.players[0]

    ev_manager.post(events.MenuBuildEvent())
    cpu_spinner.run()
Esempio n. 3
0
    def __init__(self):
        self.background = usefull_func.load_image("desert-backgorund.png", 800,
                                                  600, 0)

        self.player_one = model.Player("sprite_02.png", 16, 25, (400, 500), 0)
        self.player_two = model.Player("sprite_02.png", 16, 25, (400, 90), 180)
        self.players = pygame.sprite.Group((self.player_one, self.player_two))

        self.player_one_hb = model.Bar("bar_0.png", RED,
                                       self.player_one.health, 10, (690, 580))
        self.player_two_hb = model.Bar("bar_0.png", RED,
                                       self.player_two.health, 10, (10, 10))

        self.player_one_bullets = []
        self.player_two_bullets = []

        self.game_run = True
Esempio n. 4
0
def process_character(x,y):
    if data.level[y][x] == '#':
        model.Wall(x*data.tilesize,y*data.tilesize)
    elif data.level[y][x] == '@':
        model.Player(x*data.tilesize,y*data.tilesize)
    elif data.level[y][x] == 'M':
        model.Monster(x*data.tilesize, y*data.tilesize)
    elif data.level[y][x] == 'x':
        model.Gold(x*data.tilesize,y*data.tilesize)
Esempio n. 5
0
    def create_game(self, host_name, sid):
        game = model.Game()
        player = model.Player(name=host_name, sid=sid, game=game)
        player.games.append(game)
        game.host = player

        db.session.add(game)
        db.session.add(player)

        return game
Esempio n. 6
0
 def add_player_in_database(self):
     """
     Ajoute un joueur en base de données.
     :return: None
     """
     player = model.Player(*get_inputs_for_player_parameters())
     try:
         self.db.check_if_player_already_exist(player)
         self.db.add_player(player)
         self.set_output(view.format_output_player, player)
     except model.DataBaseTinyDBError as e:
         self.set_output(view.format_error, e)
Esempio n. 7
0
def create_players_model(player_names, view, controller):

    if len(player_names) > 5 or len(player_names) < 3:
        raise ValueError('Wrong number of players.')

    players = []
    for p_name in player_names:
        p = mod.Player(p_name, view, controller)

        # Add board empty board
        p.board = mod.Board()
        players.append(p)

    return players
Esempio n. 8
0
def multiplayer():
    board = model.Board(seed=BOARD_SEED)
    board.populate(DENSITY, CEILING)
    seed = JAR_SEED or random.getrandbits(32)
    players = []
    for i in range(PLAYERS):
        b = board.copy()
        j = model.Jar(1, seed)
        e = engine.Engine()
        if i == 0 and HUMAN:
            e = None
        player = model.Player(b, j, e)
        players.append(player)
    return players
Esempio n. 9
0
 def join_game(self, game, name, sid):
     game_stage = db.session.query(model.Game.stage).filter(
         db.and_(model.Game.id == game.id)).first()
     if game_stage is None:
         raise errors.GameNotFound()
     elif game_stage[0] != model.GameStage.pending:
         raise errors.ForbiddenAction()
     elif len(
             db.session.query(model.Player.id).filter(
                 model.Player.game_id ==
                 game.id).all()) == self.max_players:
         raise errors.GameFull()
     player = model.Player(name=name, sid=sid, game_id=game.id)
     player.games.append(game)
     db.session.add(player)
     return player
def write_player_stats(stats, team_id):
    for p in stats:
        stat = nested_get(p, ["statistics"])
        player = model.Player()
        player.player_id = p.get("id")
        player.team_id = team_id
        player.first_name = p.get("first_name")
        player.last_name = p.get("last_name")
        player.jersey_number = p.get("jersey_number")
        player.points = stat.get("points")
        player.rebounds = stat.get("rebounds")
        player.assists = stat.get("assists")
        player.fg_percent = stat.get("field_goals_pct")
        session.add(player)
        session.flush()
        session.commit()
Esempio n. 11
0
def show_player_detail(player_id):
	player = model.Player(player_id)
	general_info = player.get_general_info()
	height = general_info[0]
	weight = general_info[1]
	name = player.get_name()
	age = player.get_age()
	general_attr = player.get_general_attr()
	attack_fig = player.get_attack_attr()
	skill_fig = player.get_skill_attr()
	move_fig = player.get_move_attr()
	power_fig = player.get_power_attr()
	ment_fig = player.get_ment_attr()
	def_fig = player.get_def_attr()
	gk_fig = player.get_gk_attr()
	return render_template("playerdetail.html", height=height, weight=weight, name=name, 
		age=age, general_attr=general_attr, attack_fig=attack_fig, skill_fig=skill_fig, 
		move_fig=move_fig, power_fig=power_fig, ment_fig=ment_fig, def_fig=def_fig, 
		gk_fig=gk_fig)
Esempio n. 12
0
def run(weights, rain=False):
    players = []
    board = model.Board()
    board.populate(0.25, 6)
    seed = random.getrandbits(32)
    for w in weights:
        b = board.copy()
        j = model.Jar(1, seed)
        e = engine.Engine(w)
        p = model.Player(b, j, e)
        players.append(p)
    winners = []
    losers = []
    done = set()
    while True:
        germs = [p.board.germ_count for p in players]
        print germs
        #print group([p.display() for p in players[:10]])
        if len(done) == len(players):
            break
        for p in players:
            if p in done:
                continue
            if p.state == model.OVER or p.jar.count > 250:
                losers.append(p)
                done.add(p)
            if p.state == model.WIN:
                winners.append(p)
                done.add(p)
        for p in players:
            if p in done:
                continue
            c = p.update()
            if rain and len(c) > 1:
                for q in players:
                    if p == q:
                        continue
                    q.rain.extend(c)
    losers.reverse()
    rank = winners + losers
    rank = [players.index(p) for p in rank]
    print 'Rank:', rank
    return rank
Esempio n. 13
0
    def connect(self, account_id: str) -> None:
        """AType 20"""

        if self.storage.players.count(account_id) == 0:
            player = model.Player(
                account_id, model.Player.initialize(account_id, online=True))
            self.storage.players.update(player)

        player = self.storage.players.find(account_id)
        if not self.config.main.offline_mode:
            if not self.rcon.connected:
                self.rcon.connect()
                self.rcon.auth(self.config.main.rcon_login,
                               self.config.main.rcon_password)
            if player.ban_expire_date and player.ban_expire_date > datetime.datetime.now(
            ):
                self.rcon.banuser(player.account_id)
            else:
                self.rcon.private_message(player.account_id,
                                          f'Hello {player.nickname}!')
Esempio n. 14
0
def login():
    #If user is already in session, redirect to choose game.
    if current_user and current_user.is_authenticated:
        return redirect("/choose_game")

    #Sign up view to add player id, name, email, and hashed password to database.
    form = forms.RegistrationForm()
    if form.validate_on_submit():
        email_query = model.session.query(model.Player).filter_by(email=form.email.data).all()
        hashed = bcrypt.hashpw(form.password.data, bcrypt.gensalt(10))
        if not email_query:
            player = model.Player(id=None, name=form.name.data, email=form.email.data,
                                  password=hashed)
            model.session.add(player)
            model.session.commit()
            login_user(player)
            return redirect("/choose_game")
        else:
            print email_query
            flash('Account exists. Please log in.')
            return redirect('/')

    #Login view to allow user to log in, compares given password to salted password.
    login_form = forms.LoginForm()
    if login_form.validate_on_submit():
        player = model.session.query(model.Player).filter_by(email=login_form.email.data).first()
        if player is None:
            flash('Invalid login. Please try again.')
            return redirect('/')
        elif bcrypt.hashpw(login_form.password.data, player.password) == player.password:
                login_user(player)
                return redirect("/choose_game")
        else:
            flash('Invalid password. Please try again.')
            return redirect('/')
    else:
        return render_template("login.html", form=form)
Esempio n. 15
0
    def __init__(self):
        hero = model.Player(400, 710)
        pygame.init()

        bg_size = width, height = 400, 710  # backgroundsize
        screen = pygame.display.set_mode(bg_size)  # set bg  # set bg
        pygame.display.set_caption("Space invaders")
        background = pygame.image.load("image/background.png")  # bg picture
        # """image"""
        use_image = pygame.image.load("image/pause.png")  # pause_button_image
        resume_image = pygame.image.load("image/resume.png")
        gameover_image = pygame.image.load(
            "image/game_over.png")  # bg_game_over
        gameover_rect = gameover_image.get_rect()
        button_inst = pygame.image.load("image/instruction.png")
        button_quit = pygame.image.load("image/quit.png")

        bg_inst = pygame.image.load("image/bg_inst.png")

        pygame.display.set_caption('SPACE INVADERS')

        clock = pygame.time.Clock()

        # ==================Initialize==================
        pygame.mixer.init()
        background = pygame.image.load(
            "image/background.png")  # Load background image
        # ==========Load music and sound====================
        #pygame.mixer.music.load("sound/background.wav")
        #pygame.mixer.music.set_volume(0.3)
        #bullet_sound = pygame.mixer.Sound("sound/bullet.wav")
        #pygame.mixer.Sound.set_volume(bullet_sound, 0.3)
        #enemy_down_sound = pygame.mixer.Sound("sound/enemy_down.wav")
        #pygame.mixer.Sound.set_volume(enemy_down_sound, 0.3)
        #hero_down_sound = pygame.mixer.Sound("sound/hero_down.wav")
        #pygame.mixer.Sound.set_volume(hero_down_sound, 0.3)
        #button_sound = pygame.mixer.Sound("sound/button.wav")
        #pygame.mixer.Sound.set_volume(button_sound, 0.3)
        # ==========Load image and button====================
        #pause_image = pygame.image.load("image/pause.png")
        #resume_image = pygame.image.load("image/resume.png")
        #gameover_image = pygame.image.load("image/game_over.png")
        #gameover_rect = gameover_image.get_rect()
        #button_inst = pygame.image.load("image/instruction.png")
        #button_quit = pygame.image.load("image/quit.png")
        #button_restart = pygame.image.load("image/resume.png")
        #bg_inst = pygame.image.load("image/bg_inst.png")
        #score_image = pygame.image.load("image/score.png")
        #top_score_image = pygame.image.load("image/top_score.png")
        # ==========Main program start====================
        gameexit = False
        while not gameexit:
            screen.blit(background, (0, 0))
            screen.blit(hero.image, hero.rect)
            pygame.display.flip()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    gameexit = True

                elif event.type == pygame.KEYDOWN:

                    if event.key == pygame.K_UP:
                        hero.move_up()

                    if event.key == pygame.K_DOWN:
                        hero.move_down()

                    if event.key == pygame.K_LEFT:
                        hero.move_left()

                    if event.key == pygame.K_RIGHT:
                        hero.move_right()
Esempio n. 16
0
    def start(self, connection, event, extra, dbconn, msg_type):
        with model.db_session:
            genders = [to_utf8(g.name) for g in model.Gender.select()]
            races = [to_utf8(r.name) for r in model.Race.select(lambda x: not x.is_npc)]

        parser = plugins.ThrowingArgumentParser(prog="start", description=self.__doc__)
        parser.add_argument("gender", metavar="gender", choices=genders, help=", ".join(genders))
        parser.add_argument("race", metavar="race", choices=races, help=", ".join(races))

        try:
            pargs = parser.parse_args(extra["args"], decode=False)
            if parser.help_requested:
                return parser.format_help().strip()
        except Exception as e:
            return u"Error: %s" % exc2str(e)

        def random_birthday(s):
            tm = time.gmtime(s)
            return time.mktime((tm.tm_year, randint(1, 12), randint(1, 31), randint(0, 23), randint(0, 59), randint(0, 61), 0, 1, -1))

        def random_value(val, p):
            rand = 1.0 + p * (2 * random() - 1)
            return val * rand

        with model.db_session:
            network_id = self.tehbot.settings.network_id(connection)
            r = model.Race.get(name=pargs.race)
            p = model.Player(
                    network_id=network_id,
                    nick=event.source.nick,
                    name=event.source.nick,
                    gender=model.Gender.get(name=pargs.gender),
                    race=r,
                    birthday = random_birthday(self.sltime() - random_value(r.age, 0.2) * 365 * 24 * 60 * 60),
                    height = random_value(r.height, 0.2),
                    own_weight = random_value(r.own_weight, 0.2),
                    options = {},
                    hp = 0,
                    mp = 0,
                    distance = 0,
                    xp = 0,
                    xp_level = 0,
                    karma = 0,
                    bad_karma = 0,
                    level = 0,
                    bounty = 0,
                    bounty_done = 0,
                    quests_done = 0,
                    nuyen = 0,
                    known_words = [],
                    known_spells = [],
                    known_places = "",
                    bank_nuyen = 0,
                    bank_items = "",
                    effects = "",
                    const_vars = "",
                    combat_ai = "",
                    game_ai = "",
                    feelings = model.Feelings(),
                    attributes = model.Attributes(),
                    skills = model.Skills(),
                    knowledge = model.Knowledge(),
                    lock = 0,
                    transport = 0,
                    stats = model.PlayerStats(),
                    equipment = model.Equipment(),
                    )
            p.init_player()
            party = model.Party(options={})
            p.party = party

        msgs = [
                _("Your character has been created with \x02Age\x02: %dyears, \x02Height\x02: %.2fm, \x02Weight\x02: %.2fkg.") % (self.player_age(p), p.height, p.own_weight),
                ]

        notices = [
                _("You wake up in a bright room... It seems like it is past noon...looks like you are in a hotel room."),
                _("What happened... You can`t remember anything.... Gosh, you even forgot your name."),
                _("You check your %s and find a pen from 'Renraku Inc.'. You leave your room and walk to the counter. Use %s to talk with the hotelier." % (self.cmd("inventory"), self.cmd("talk"))),
                _("Use %s to see all available commands. Check %s to browse the Shadowlamb help files. Use %s to see the help for a command or subject." % (self.cmd("commands"), self.cmd("help"), self.cmd("help <word>")))
                ]

        notices += self.give_item(p, model.Item.get(name="Pen"))
        notices += self.give_word(p, model.Word.get(name="Shadowrun"))
        notices += self.give_word(p, model.Word.get(name="Renraku"))
        notices += self.give_place(p, model.Place.get(name="Redmond_Hotel"))
        self.party_push_action(party, model.PartyAction.inside, "Redmond_Hotel")

        if msg_type == "notice":
            notices = msgs + notices
            msgs = []
        else:
            for m in msgs:
                if irc.client.is_channel(event.target):
                    plugins.say_nick(connection, event.target, event.source.nick, m, dbconn)
                else:
                    plugins.say(connection, event.source.nick, m, dbconn)

        for m in notices:
            plugins.notice(connection, event.source.nick, m, dbconn)

        self.announce("Welcome a new player: %s the %s %s." % (p.fullname(), p.gender.name, p.race.name), dbconn)
        return None
Esempio n. 17
0
##CHRIS NELSON NHC 2017

import view as v  # imports 3 other files from this directory
import model as m  # refers to functions / classes from these with v. m.
import functions as f  # or f. prefix. hit_check() stayed local for efficiency

dat = m.Datastore()  # instantiate class
p1 = m.Player()  # see def __init__() for variables in class definitions
p2 = m.Player()  # found in model.py (m.) - now p1 and p2 can

# represent players one and two


# hit_check handles score, hit log update, and ship map update
def hit_check(
        player, x,
        y):  # collision detection, send it a player and some coordinates -
    if player == 1:  # the player is shooting, the coords are a target in y,x format
        if p2.ship_grid[int(y)][int(x)] == "#":  # is it a ship?
            print("\t\tHIT!")  # congratulate
            p1.score += 1  # increment score
            p1.hit_grid[int(y)][int(x)] = "X"  # log hit on hit_grid
            p2.ship_grid[int(y)][int(x)] = "~"  # remove section of hit ship
        else:
            print("\t\tMISS")
            p1.hit_grid[int(y)][int(x)] = "0"  # log miss on hit_grid
    elif player == 2:
        if p1.ship_grid[int(y)][int(
                x)] == "#":  # same again for player 2... could put
            # this whole function in a loop or
            print("\t\tHIT!!")  # external function, but its clear,
Esempio n. 18
0
def insert_players(players, teamnum, teamname):
    # lazy so doing this intermediate step for now
    """ 
    Takes the player objects and puts info into mysql db 
    
    args:
    * players: list of player objects
    * teamnum: CSL id for team, e.g. 182
    * teamname: string for teamname, e.g. 'Harvard University'

    returns:
        nothing
    """

    active = len(players)
    singleplayers = 0
    teamplayers = 0
    zerg = 0
    protoss = 0
    terran = 0
    random = 0

    for player in players:

        games = len(player.match.keys())

        ztotal = 0
        ptotal = 0
        ttotal = 0
        zwins = 0
        pwins = 0
        twins = 0
        wins = 0
        plays = [0] * 9

        if games is not 0:
            zgames = player.record[ZERG]
            pgames = player.record[PROTOSS]
            tgames = player.record[TERRAN]

            ztotal = int(zgames[0]) + int(zgames[1])
            ptotal = int(pgames[0]) + int(pgames[1])
            ttotal = int(tgames[0]) + int(tgames[1])

            try:
                # this doesn't work as an equality because CSL website doesn't
                # account for random players in their record
                assert int(games) >= int(ztotal + ptotal + ttotal)
            except:
                print player.character
                sys.stdout.flush()

            zwins = int(zgames[0])
            pwins = int(pgames[0])
            twins = int(tgames[0])

            wins = zwins + pwins + twins

            maps = ['Antiga', 'Daybreak', 'Dual', 'Metal', 'Shakuras',\
                    'Shattered', 'Tal', 'Testbug', 'XelNaga']
            plays = [0] * len(maps)

            for m in player.maps.keys():
                for mm in maps:
                    if mm in m:
                        plays[maps.index(mm)] = player.maps[m]

        teamgames = 0
        teamwins = -1  # TODO: not implemented yet
        team = [0] * 4
        for race in player.teamgame_race.keys():
            teamgames += player.teamgame_race[race]
            #teamwins += player.teamwins_race[race] # not implemented yet
            if ZERG in race:
                team[0] = player.teamgame_race[race]
            elif PROTOSS in race:
                team[1] = player.teamgame_race[race]
            elif TERRAN in race:
                team[2] = player.teamgame_race[race]
            else:
                team[3] = player.teamgame_race[race]

        assert teamgames == (team[0] + team[1] + team[2] + team[3])
        assert teamwins <= teamgames

        # to get case of 'not found' for player's points
        try:
            pts = int(player.points)
        except:
            pts = -1

        session.add(model.Player(cslid=player.CSLid,\
                            name=player.character,\
                            character=player.character.split('.')[0],\
                            code=player.character.split('.')[1],\
                            team=teamnum,\
                            race=player.race,\
                            league=player.league,\
                            points=pts,\
                            games=games,\
                            zgames=ztotal,\
                            pgames=ptotal,\
                            tgames=ttotal,\
                            wins=wins,\
                            zwins=zwins,\
                            pwins=pwins,\
                            twins=twins,\
                            antiga=plays[0],\
                            daybreak=plays[1],\
                            dualsight=plays[2],\
                            metalopolis=plays[3],\
                            shakuras=plays[4],\
                            shattered=plays[5],\
                            taldarim=plays[6],\
                            testbug=plays[7],\
                            xelnaga=plays[8],\
                            ace=player.ace,\
                            teamgames=teamgames,\
                            teamwins=teamwins,\
                            zteam=team[0],\
                            pteam=team[1],\
                            tteam=team[2],\
                            rteam=team[3]))

        session.commit()

        if player.match:
            singleplayers += 1
        if player.teamgame:
            teamplayers += 1

        if player.race is ZERG:
            zerg += 1
        elif player.race is PROTOSS:
            protoss += 1
        elif player.race is TERRAN:
            terran += 1
        else:
            random += 1


    session.add(model.Team(cslid=teamnum,\
                    name=teamname,\
                    active_players=len(players),\
                    single=singleplayers,\
                    team=teamplayers,\
                    zerg=zerg,\
                    protoss=protoss,\
                    terran=terran,\
                    random=random))

    session.commit()

    session.close()
Esempio n. 19
0
def load_game_from_state(state, view, controller):
    '''
    Load the game from a state.
    '''
    n_players = len(state['players'])

    all_tiles = create_all_objects_of_type(get_number_of_plantation_tiles(),
                                           create_tile)

    all_buildings = create_all_objects_of_type(get_number_of_buildings(),
                                               create_building)

    all_goods = create_all_objects_of_type(get_number_of_goods(), create_good)
    all_colonists = (y for y in create_colonists(n_players))
    all_vp = (y for y in create_victory_points(n_players))
    all_roles = create_all_objects_of_type(get_number_of_role_cards(n_players),
                                           create_role)

    players = []
    for player in state['players']:
        player_obj = mod.Player(
            player['name'],
            view.Player(),
            controller.Player(),
        )
        add_player_properties(player_obj, player, all_tiles, all_buildings,
                              all_goods, all_colonists, all_vp)

        players.append(player_obj)

    if state['current_role'] is not None:
        current_role = next(all_roles[state['current_role']])
    else:
        current_role = None

    remaining_roles = []
    for (role, doubloon_count) in state['roles_doubloon_count']:
        role_i = next(all_roles[role])
        role_i.doubloons = doubloon_count
        remaining_roles.append(role_i)

    trading_house = mod.TradingHouse()
    for good in state['trading_house']:
        trading_house.add_good(next(all_goods[good]))

    colonist_portal = create_colonist_portal(state['colonist']['ship'],
                                             all_colonists, n_players)

    on_display = [
        next(all_tiles[tile_type])
        for tile_type in state['tiles']['on_display']
    ]
    tiles_portal = create_tiles_portal(all_tiles, n_players, on_display)

    # Assume that correct number of cargo ships are included
    cargo_ships = create_cargo_ships(n_players)
    for (cap, ship) in cargo_ships.items():
        ship.load(
            [next(all_goods[load]) for load in state['cargo_ships'][cap]])

    remaining_buildings = list(it.chain.from_iterable(all_buildings.values()))
    remaining_goods = {k: list(v) for (k, v) in all_goods.items()}

    game = mod.Game(
        players,
        remaining_roles,
        cargo_ships,
        colonist_portal,
        tiles_portal,
        list(all_vp),
        remaining_buildings,
        remaining_goods,
        trading_house,
        view.Game(),
    )

    game.current_role = current_role
    return game
Esempio n. 20
0
 def find(self, account_id) -> model.Player:
     """Найти документ игрока в БД"""
     document = self.collection.find_one({constants.ID: account_id})
     return model.Player(account_id, document)