Exemplo n.º 1
0
    def play(self, mode: str):
        self.root.bind('<Escape>', self.reset_game)

        if mode == 'Easy':
            self.player1 = Player(1)
            self.player2 = RandomComputer(2)
            self.computer = True
        elif mode == 'Unbeatable':
            self.player1 = Player(1)
            self.player2 = SmartComputer(2)
            self.computer = True
        else:
            self.player1 = Player(1)
            self.player2 = Player(2)

        self.render()
Exemplo n.º 2
0
 def add_player(self, name, player_id):
     existing_names = [player.name for player in self.players]
     while name in existing_names:
         name = name + "!"  # avoid duplicate names by adding exclamation marks
     player = Player(name, player_id)
     self.players.append(player)
     return name
Exemplo n.º 3
0
def run_game(num_of_players, stdscr):
    turn = 1
    active_player = 0
    players = []

    for _ in range(num_of_players):
        players.append(Player())

    state = GameStateUi(stdscr, players)
    shop = Shop()
    update_board(players, active_player, state, shop)

    # game loop
    while True:
        curses.panel.update_panels()
        write_message(f"\nIt's player {active_player + 1}'s turn", state)
        two_dice = parse_yes_no_input("Do you want to roll with two dice?", state) if players[active_player].landmarks["Train Station"][0] \
            else False

        rolls = roll_dice(two_dice)
        roll = rolls[0] + rolls[1]
        write_message(f"Rolled: {rolls[0]}, {rolls[1]}", state) if rolls[1] else write_message(f"Rolled: {rolls[0]}", state)

        if players[active_player].landmarks['Radio Tower'][0]:
            if parse_yes_no_input("Do you want to roll again?", state):
                rolls = roll_dice(two_dice)
                roll = rolls[0] + rolls[1]
                write_message(f"Rolled: {rolls[0]}, {rolls[1]}", state) if rolls[1] else write_message(f"Rolled: {rolls[0]}", state)


        for ind in range(num_of_players):
            player_ind = (ind + active_player + 1) % 4

            for card in players[player_ind].cards:
                card_obj = card()
                if roll in card_obj.rolls_active and (card_obj.active_on_others_turns or player_ind == active_player):
                    for num_of_cards in range(players[player_ind].cards[card]):
                        card_obj.on_activate(players=players, card_owner_ind=player_ind, active_player_ind=active_player, state=state)

        update_board(players, active_player, state, shop)
        parse_buy(players[active_player], state, shop)
        update_board(players, active_player, state, shop)

        if len([x for x in players[active_player].landmarks if players[active_player].landmarks[x][0]]) == 4:
            write_message(f"Player {active_player + 1} wins the game!", state)
            write_message(f"Type yes to end the game", state)

            while get_input(state).lower() not in ["yes", 'y']:
                pass

            break

        turn += 1
        if not (rolls[0] == rolls[1] and players[active_player].landmarks['Amusement Park'][0]):
            active_player = (active_player + 1) % 4
        else:
            write_message(f"You rolled doubles this turn and own the Amusement Park! Have another", state)
Exemplo n.º 4
0
 def __init__(self, driver):
     self.PATH = 'serials'
     self.popup_film = PopupFilm(driver)
     super(SerialPage, self).__init__(driver, self.popup_film.locators.root)
     self.infoblock_film = InfoblockFilm(self.driver)
     self.navbar_form = NavbarForm(self.driver)
     self.card = Card(self.driver)
     self.player = Player(self.driver)
     self.auth_form = AuthForm(driver)
Exemplo n.º 5
0
 def start_hard(self):
     self.clear()
     self.scoreObj, self.bestObj = spawn_score(self.window)
     update_score(self.best, self.bestObj)
     self.PauseObj.draw(self.window)
     self.Players = Player(self.window, 3)
     self.draw_map()
     self.generate_coins()
     self.gameLoop(JERRY_WEIGHT_HARD)
Exemplo n.º 6
0
 def __init__(self):
     # Starting screen
     self.is_playing = False
     # Generate a new player
     self.all_players = pygame.sprite.Group()
     self.player = Player(self)
     self.all_players.add(self.player)
     # Create an empty group of monsters
     self.all_monsters = pygame.sprite.Group()
     # Get pressed keys
     self.pressed = {}
Exemplo n.º 7
0
 def create_player(self):
     return Entity().add_component(
         Stats(5), Inventory(), Controllable(),
         GridMovement(C.PLAYER_WALK_RELOAD),
         Orientable(C.DIRECTION_O, C.PLAYER_WALK_RELOAD),
         Position(None, None, None), AlignedBox(-0.5, -0.5, 0.5, 0.5),
         Sprite({
             tuple(self.load_images.obtain_entity('Player', 3)):
             lambda e: e.get_component(Orientable
                                       ).orientation == C.DIRECTION_N,
             tuple(self.load_images.obtain_entity('Player', 1)):
             lambda e: e.get_component(Orientable).orientation == C.
             DIRECTION_O,
             tuple(self.load_images.obtain_entity('Player', 0)):
             lambda e: e.get_component(Orientable
                                       ).orientation == C.DIRECTION_S,
             tuple(self.load_images.obtain_entity('Player', 2)):
             lambda e: True
         }), Player())
Exemplo n.º 8
0
    def startup(self, persistent):

        # pygame.mixer.music.load('assets/music/Omega.ogg')
        # pygame.mixer.music.set_volume(0.5)
        # pygame.mixer.music.play(-1, 0.0)
        pygame.mouse.set_visible(False)

        bg = parallax.ParallaxSurface((1400, 400), pygame.RLEACCEL)
        bg.add(BL3, 8, (WIDTH * 2, HEIGHT))
        bg.add(BL2, 6, (WIDTH * 2, HEIGHT))
        bg.add(BL1, 3, (WIDTH * 2, HEIGHT))
        bg.add(BL0, 2, (WIDTH * 2, HEIGHT))

        self.background = bg
        self.finished = False

        self.phase = 0

        self.num_of_enemies = 0
        self.score = 0
        self.shots_fired = 0
        self.streak = 1
        self.misses = 0

        self.mssg_group = pygame.sprite.Group()
        self.enemy_list = pygame.sprite.Group()
        self.asteroid_list = Asteroid_group()
        self.boss_list = pygame.sprite.Group()
        self.hud_items = pygame.sprite.Group()
        self.player_list = pygame.sprite.Group()
        self.player = Player(self.player_list)
        self.crosshair = Crosshair()

        self.wave1()

        signaly.subscribe('GAME_OVER', self.game_over, 1)
        signaly.subscribe('PLAYER_MSSG', self.player_mssg)

        super().startup(persistent)
Exemplo n.º 9
0
    def startup(self, persistent):
        pygame.mixer.music.load('assets/music/Omega.ogg')
        pygame.mixer.music.set_volume(0.5)
        pygame.mixer.music.play(-1, 0.0)

        self.phase = 0

        self.num_of_enemies = 15
        self.score = 0
        self.shots_fired = 0
        self.streak = 1
        self.misses = 0
        self.ammo = int(self.num_of_enemies * 100)

        self.enemy_list = pygame.sprite.Group()
        self.asteroid_list = Asteroid_group()
        self.bullet_list = pygame.sprite.Group()
        self.boss_list = pygame.sprite.Group()
        self.hud_items = pygame.sprite.Group()
        self.boss = Boss()
        self.player = Player()

        for i in range(self.num_of_enemies):
            enemy = Enemy()
            self.enemy_list.add(enemy)

        self.boss_list.add(self.boss)

        self.hud_score = Hud(570, 350, 120, 40, 'SCORE')
        self.hud_ammo = Hud(570, 300, 120, 40, 'AMMO')
        self.hud_multiplier = Hud(510, 350, 50, 40, '', 'x', True)
        self.hud_items.add(self.hud_score)
        self.hud_items.add(self.hud_ammo)
        self.hud_items.add(self.hud_multiplier)

        super().startup(persistent)
Exemplo n.º 10
0
 def __init__(self, num_players):
     self.table = Table(
         players=[Player(player_id=i) for i in range(num_players)])
Exemplo n.º 11
0
    def init_new_game(self, params):
        choice = params
        self.player = None
        self.levels = None
        self.time_counter = None
        # Create player
        inventory_component = Inventory(26)
        f_data = self.data.fighters["player"]
        fighter_component = Fighter(hp=f_data["hp"],
                                    ac=f_data["ac"],
                                    ev=f_data["ev"],
                                    power=f_data["power"],
                                    mv_spd=f_data["mv_spd"],
                                    atk_spd=f_data["atk_spd"],
                                    size=f_data["size"],
                                    fov=f_data["fov"])

        light_component = LightSource(radius=fighter_component.fov)
        player_component = Player(50)
        abilities_component = Abilities("player")
        status_effects_component = StatusEffects("player")
        summoner_component = Summoner()
        player = Entity(1,
                        1,
                        3,
                        player_component.char["player"],
                        "default",
                        "player",
                        blocks=True,
                        player=player_component,
                        fighter=fighter_component,
                        inventory=inventory_component,
                        light_source=light_component,
                        summoner=summoner_component,
                        indicator_color="gray",
                        abilities=abilities_component,
                        status_effects=status_effects_component,
                        stand_on_messages=False)
        player.player.avatar["player"] = fighter_component
        avatar_f_data = self.data.fighters[choice]
        a_fighter_component = Fighter(hp=avatar_f_data["hp"],
                                      ac=avatar_f_data["ac"],
                                      ev=avatar_f_data["ev"],
                                      power=avatar_f_data["power"],
                                      mv_spd=avatar_f_data["mv_spd"],
                                      atk_spd=avatar_f_data["atk_spd"],
                                      size=avatar_f_data["size"],
                                      fov=avatar_f_data["fov"])
        player.player.avatar[choice] = a_fighter_component
        player.player.avatar[choice].owner = player
        player.abilities.initialize_abilities(choice)
        player.player.char[choice] = tilemap()["monsters"][choice]
        player.player.char_exp[choice] = 20

        player.player.avatar[choice].max_hp += 20
        player.player.avatar[choice].hp += 20
        player.player.avatar[choice].power += 1
        player.player.insights = 200

        self.player = player

        character_menu = MenuData(name="avatar_info", params=self.player)
        self.menus.create_or_show_menu(character_menu)

        message_log = MessageLog(4)
        self.message_log = message_log
        self.message_log.owner = self

        # Initialize game camera
        game_camera = Camera(1, 1, self.ui.viewport.w, self.ui.viewport.h,
                             self.options)
        self.game_camera = game_camera
        self.game_camera.owner = self

        levels = Levels(tileset=self.options.gfx)
        self.levels = levels
        self.levels.owner = self

        blt.clear_area(2, self.ui.viewport.offset_h + self.ui.offset_y + 1,
                       self.ui.viewport.x, 1)

        # if settings.gfx == "ascii":
        #     player.char = tilemap()["player"]
        #     player.color = "lightest green"

        self.levels.change("hub")
        self.fov_recompute = True
        self.game_state = GameStates.PLAYER_TURN
        self.time_counter = self.TimeCounter(owner=self)
Exemplo n.º 12
0
def main():
    # hardware acceleration to reduce flickering. Works only in full screen
    flags = DOUBLEBUF | HWSURFACE | FULLSCREEN
    screen = pg.display.set_mode(WINDOW_SIZE, flags)

    # Display until loading finishes.
    screen.fill(COLORS["BLACK"])
    _render = FONTS["GAMEOVER"].render("LOADING...", 0, pg.Color("white"))
    SCREEN_RECT = pg.Rect((0, 0), WINDOW_SIZE)
    screen.blit(_render, _render.get_rect(center=SCREEN_RECT.center))

    pg.display.set_caption("QPong")

    # clock for timing
    clock = pg.time.Clock()
    old_clock = pg.time.get_ticks()

    # initialize scene, level and input Classes
    scene = Scene(QUBIT_NUM)

    # players
    players = []

    input = Input()

    # define ball
    ball = Ball()
    balls = (pg.sprite.Group()
             )  # sprite group type is needed for sprite collide function in pg

    balls.add(ball)

    # Show start screen to select difficulty
    input.running = scene.mode(screen)  # start screen returns running flag
    if not input.running:
        pg.quit()
        return

    input.running = scene.difficulty(
        screen, ball)  # start mode selections returns flag
    if not input.running:
        pg.quit()
        return

    if scene.game_mode == MODES["ONE_PLAYER"]:
        players += [
            Player(QUBIT_NUM, POSITIONS["RIGHT"], QUANTUM_COMPUTER_1P,
                   scene.game_mode)
        ]
        players += [
            Player(QUBIT_NUM, POSITIONS["LEFT"], CLASSICAL_COMPUTER,
                   scene.game_mode)
        ]
    elif scene.game_mode == MODES["TWO_PLAYER"]:
        players += [
            Player(QUBIT_NUM, POSITIONS["RIGHT"], QUANTUM_COMPUTER_1P,
                   scene.game_mode)
        ]
        players += [
            Player(QUBIT_NUM, POSITIONS["LEFT"], QUANTUM_COMPUTER_2P,
                   scene.game_mode)
        ]

    # Put all moving sprites a group so that they can be drawn together
    moving_sprites = pg.sprite.Group()
    moving_sprites.add(ball)
    for player in players:
        moving_sprites.add(player.paddle)

    # update the screen
    pg.display.flip()

    # reset the ball
    ball.reset()

    # a valuable to record the time when the paddle is measured
    measure_time = 100000

    # Main Loop
    while input.running:
        # set maximum frame rate
        clock.tick(60)

        # refill whole screen with black color at each frame
        screen.fill(COLORS["BLACK"])

        ball.update()  # update ball position
        scene.dashed_line(
            screen)  # draw dashed line in the middle of the screen
        scene.score(players, screen)  # print score

        for _, player in enumerate(players):
            if player.player_type in (QUANTUM_COMPUTER_1P,
                                      QUANTUM_COMPUTER_2P):
                player.statevector.draw(
                    screen)  # draw right paddle together with statevector grid
                player.circuit_grid.draw(screen)  # draw circuit grid
                moving_sprites.draw(screen)  # draw moving sprites

                # Show game over screen if the score reaches WIN_SCORE, reset everything if replay == TRUE
                if player.score >= WIN_SCORE:
                    input.running = scene.gameover(screen, player.player_type)
                    scene.replay(screen, players)

                    player.update_paddle(screen)

                if player.score >= WIN_SCORE:
                    input.running = scene.gameover(screen, player.player_type)
                    scene.replay(screen, players)

                    player.update_paddle(screen)

        # computer paddle movement
        if scene.game_mode == MODES["ONE_PLAYER"]:
            cpu_player = next(
                filter(lambda p: p.player_type == CLASSICAL_COMPUTER, players))
            qcpu_player = next(
                filter(
                    lambda p: p.player_type in
                    (QUANTUM_COMPUTER_1P, QUANTUM_COMPUTER_2P),
                    players,
                ))

            if cpu_player:
                if pg.time.get_ticks() - old_clock > 300:
                    cpu_player.paddle.rect.y = (
                        ball.y - qcpu_player.statevector_grid.block_size / 2 +
                        random.randint(-WIDTH_UNIT * 4, WIDTH_UNIT * 4))
                    old_clock = pg.time.get_ticks()

            # handle input events
            input.handle_input(players, screen)

            # check ball location and decide what to do
            ball.action(players)

            if ball.ball_action == BALL_ACTIONS["MEASURE_RIGHT"]:
                circuit = qcpu_player.circuit_grid_model.compute_circuit()
                pos = qcpu_player.statevector_grid.paddle_after_measurement(
                    qcpu_player.position, circuit, QUBIT_NUM, 1)
                qcpu_player.statevector.arrange()

                # paddle after measurement
                qcpu_player.paddle.rect.y = (pos * round(WINDOW_HEIGHT * 0.7) /
                                             (2**QUBIT_NUM))
                measure_time = pg.time.get_ticks()

            if pg.sprite.spritecollide(qcpu_player.paddle, balls, False):
                ball.bounce_edge()

            if pg.sprite.spritecollide(cpu_player.paddle, balls, False):
                ball.bounce_edge()

            if pg.time.get_ticks() - measure_time > 400:
                # refresh the screen a moment after measurement to update visual
                qcpu_player.update_paddle(screen)
                # add a buffer time before measure again
                measure_time = pg.time.get_ticks() + 100000

        elif scene.game_mode == MODES["TWO_PLAYER"]:
            # handle input events
            input.handle_input(players, screen)

            # check ball location and decide what to do
            ball.action(players)

            if ball.ball_action == BALL_ACTIONS["MEASURE_RIGHT"]:
                circuit = players[0].circuit_grid_model.compute_circuit()
                pos = players[0].statevector_grid.paddle_after_measurement(
                    players[0].position, circuit, QUBIT_NUM, 1)
                players[0].statevector.arrange()

                # paddle after measurement
                players[0].paddle.rect.y = (pos * round(WINDOW_HEIGHT * 0.7) /
                                            (2**QUBIT_NUM))
                measure_time = pg.time.get_ticks()

            if ball.ball_action == BALL_ACTIONS["MEASURE_LEFT"]:
                circuit = players[1].circuit_grid_model.compute_circuit()
                pos = players[1].statevector_grid.paddle_after_measurement(
                    players[1].position, circuit, QUBIT_NUM, 1)
                players[1].statevector.arrange()

                # paddle after measurement
                players[1].paddle.rect.y = (pos * round(WINDOW_HEIGHT * 0.7) /
                                            (2**QUBIT_NUM))
                measure_time = pg.time.get_ticks()

            if pg.sprite.spritecollide(players[0].paddle, balls, False):
                ball.bounce_edge()

            if pg.sprite.spritecollide(players[1].paddle, balls, False):
                ball.bounce_edge()

            if pg.time.get_ticks() - measure_time > 400:
                # refresh the screen a moment after measurement to update visual
                players[0].update_paddle(screen)
                players[1].update_paddle(screen)
                # add a buffer time before measure again
                measure_time = pg.time.get_ticks() + 100000

        # Update the screen
        if input.running:
            pg.display.flip()

    pg.quit()
Exemplo n.º 13
0
 def setPlayer1(self, name, ip, conn):
     self._players[0] = Player(name, ip, conn)
Exemplo n.º 14
0
 def setPlayer2(self, name, ip, conn):
     self._players[1] = Player(name, ip, conn)
Exemplo n.º 15
0
from constants import Constants

constants = Constants()
# initialize pygame
pygame.init()
# creating screen of width 800 and height 600
screen = pygame.display.set_mode((800, 600))
# game status
running = True
# background
background = pygame.image.load(constants.background)
# score
score_value = 0

# player
player = Player(screen=screen)

# enemy invader/s
enemies = Enemies(screen=screen, number_of_enemies=6)
enemies.init_enemies()

# bullet
bullet = Bullet(screen=screen)
# mechanics
mechanics = Mechanics()


def set_defaults():
    # background music
    mixer.music.load(constants.background_music)
    mixer.music.play(-1)
Exemplo n.º 16
0
 def setUp(self) -> None:
     self.pl1 = Player("Test", 3)
Exemplo n.º 17
0
 def __init__(self, driver):
     self.PATH = 'watch/'
     super(PlayerPage, self).__init__(driver, '')
     self.player = Player(self.driver)
Exemplo n.º 18
0
def setup_data_state(constants, run_tutorial=True, previous_data=None):
    pygame.init()
    pygame.display.set_caption("Formula")
    pygame.mixer.quit()
    pygame.key.set_repeat(100)
    main = pygame.display.set_mode(
        (constants.window_size.width, constants.window_size.height))

    assets = Assets.setup()

    godmode = False

    fps_per_second = 30

    story_loader = StoryLoader()
    story_data = StoryData(story_loader)

    timesystem = TimeSystem()

    visuals = VisualEffectSystem.setup(fps_per_second)

    clock = pygame.time.Clock()

    windows = WindowManager()
    rpw = RightPanelWindow(constants)
    windows.push(rpw)
    windows.push(GameWindow(constants, parent=rpw))
    windows.push(MessageLogWindow(constants, parent=rpw))

    windows.push(StoryWindow(constants, story_data, visible=True))
    windows.push(StoryHelpWindow(constants))
    windows.push(FormulaWindow(constants))
    windows.push(FormulaHelpWindow(constants))
    windows.push(GeneralHelpWindow(constants))
    windows.push(LevelUpWindow(constants))
    windows.push(AskQuitWindow(constants))
    windows.push(DeadWindow(constants))
    windows.push(VictoryWindow(constants))
    windows.push(ConsoleWindow(constants))
    windows.push(CraftingWindow(constants))
    windows.push(CraftingHelpWindow(constants))
    windows.push(InventoryWindow(constants))
    windows.push(InventoryHelpWindow(constants))

    text_width = constants.message_log_text_size.width / get_width(
        Assets.get().font_message)
    log = MessageLog(text_width)  # for some margin on the sides

    player = Player(godmode)
    formula_builder = FormulaBuilder(player.caster.num_slots,
                                     player.caster.num_formulas, run_tutorial)

    levels = 9
    planner = RunPlanner(levels, player, constants, timesystem, run_tutorial)
    fov_map = None

    ingredient_storage = IngredientStorage()
    if config.conf.pickupstartcount == "base":
        ingredient_storage.add_multiple({
            Ingredient.FIRE: 2,
            Ingredient.WATER: 2,
            Ingredient.EARTH: 2,
            Ingredient.RANGE: 1,
            Ingredient.AREA: 1,
        })
        if config.conf.trap:
            ingredient_storage.add_multiple({
                Ingredient.TRAP: 2,
            })
    else:
        for ing in Ingredient.all():
            ingredient_storage.add_multiple(
                {ing: config.conf.pickupstartcount})

    menu_data = AttrDict({"currchoice": 0})

    inventory = Inventory(max_count=constants.num_consumables,
                          num_quickslots=constants.num_quickslots)
    from components.consumable import Firebomb, Freezebomb, Teleporter, CooldownClear

    # for t in [Firebomb, Freezebomb, Teleporter, CooldownClear, Thingy, Thingmajig]:
    #    inventory.add(t())
    #inventory.add(Firebomb())
    #inventory.add(Teleporter())

    initial_state = GameStates.STORY_SCREEN

    logger = previous_data.logger if previous_data else BlobLogger()

    game_data = StateData(
        player=player,
        log=log,
        constants=constants,
        timesystem=timesystem,
        fov_map=fov_map,
        fov_recompute=True,
        story_data=story_data,
        run_planner=planner,
        formula_builder=formula_builder,
        menu_data=menu_data,
        ingredient_storage=ingredient_storage,
        inventory=inventory,
        logger=logger,
        initial_state=initial_state,
        initial_state_history=[GameStates.PLAY],
    )

    camera = Camera(constants.camera_size.width, constants.camera_size.height,
                    game_data)

    gfx_data = GfxState(
        main=main,
        assets=assets,
        camera=camera,
        fullscreen=False,
        visuals=visuals,
        fps_per_second=fps_per_second,
        clock=clock,
        windows=windows,
    )

    if not run_tutorial:
        game_data.prev_state = [GameStates.FORMULA_SCREEN, GameStates.PLAY]
        windows.activate_wnd_for_state(game_data.state, game_data, gfx_data)
        story_data.next_story()

    # create default formulas
    Formula.EMPTY, _ = formula_builder.get_empty_formula(caster=player)
    initial_formulas = formula_builder.evaluate_entity(caster=player)
    player.caster.set_formulas(initial_formulas)

    return game_data, gfx_data, initial_state