def __init__(self, window):
     super().__init__(window)
     self.player1_name = "Dark Conqueror"
     self.player2_name = "Knight of Light"
     self.game_keys = GAME_KEYS
     self.pressed_keys = {}
     for key in self.game_keys:
         self.pressed_keys[key] = False
     self.prev_pressed_keys = {}
     for key in self.game_keys:
         self.prev_pressed_keys[key] = False
     self.images = {}
     self.gui_textures = {self.player1_name: [], self.player2_name: []}
     self.init_gui_textures()
     self.player_name_font_size = 30
     self.player_name_font = pygame.font.SysFont(None,
                                                 self.player_name_font_size)
     self.does_menu = False
     self.menu = pygame_menu.Menu(title="Game menu",
                                  height=250,
                                  width=500,
                                  theme=pygame_menu.themes.THEME_DARK)
     self.menu.add.button("Quit", switch_to_menu, self.event_manager)
     self.engine = GameEngine(Player(self.player1_name),
                              Player(self.player2_name))
     self.end_time_frame_ended = get_time()
     self.fps_sys = FpsRenderSystem(window)
     self.end_time = None
Пример #2
0
def run_game():
    global CONNECTED_PEOPLE
    global THREADS
    player1 = Player("Dark Conqueror")
    player2 = Player("Knight of Light")
    engine = GameEngine(player1, player2)
    game_running = True
    frame_in_period = 0
    dt = 1 / 60
    start_frame_time = get_time()
    print("GAME")
    end_time = None
    keys = [None] * 2
    while game_running:
        frame_in_period += 1

        # get players keys (non blocking)
        for i in range(len(CONNECTED_PEOPLE)):
            try:
                keys[i] = recv_data_on_open_socket(CONNECTED_PEOPLE[i])
            except socket.error:
                keys[i] = None

        # update logic
        state = engine.update(dt, keys[0], keys[1])

        # check for endgame
        if state.has_ended and end_time is None:
            end_time = get_time()
        if end_time and (get_time()-end_time) * 1e-9 >= 1:
            state.should_exit = True
            print("Game over")

        if state.should_exit:
            for i in range(len(CONNECTED_PEOPLE)):
                WANT_TO_PLAY[i] = False
                # block sockets
                block_socket(CONNECTED_PEOPLE[i])
                # create threads
                player_thread = threading.Thread(target=threaded_client, args=[CONNECTED_PEOPLE[i], i])
                player_thread.start()
                THREADS.append(player_thread)

            game_running = False


        # send data (if period ended)
        if frame_in_period % SENDING_PERIOD == 0 or state.should_exit:
            frame_in_period = 0
            for i in range(len(CONNECTED_PEOPLE)):
                if not send_data_on_open_socket(CONNECTED_PEOPLE[i], state):
                    print("Client exited.")
                    return False

        # calculate frame time
        end_frame_time = get_time()
        dt = (end_frame_time - start_frame_time) * 1e-9
        start_frame_time = get_time()
    return True
Пример #3
0
 def run(self):
     while not self.workdone[-1]:
         try:
             # Ok to block
             response, start, work = self.results.get(timeout=1)
             try:
                 self.return_queue.put_nowait(
                     APIResult(
                         tuple(
                             Player(
                                 p['account_id'],
                                 p['nickname'],
                                 p['created_at'],
                                 p['last_battle_time'],
                                 p['updated_at'],
                                 p['statistics']['all']['battles'],
                                 'xbox' if p['nickname'][-2:] == '-x' else 'ps',
                                 p['statistics']['all']['spotted'],
                                 p['statistics']['all']['wins'],
                                 p['statistics']['all']['damage_dealt'],
                                 p['statistics']['all']['frags'],
                                 p['statistics']['all']['dropped_capture_points']
                             ) for __, p in response['data'].items() if p),
                         start.timestamp(),
                         work[0]
                     )
                 )
             except KeyError:
                 self.log.warning('Batch %i has no "data" key', work[0])
                 self.log.warning('Batch %i: %s', work[0], str(response))
         except Empty:
             pass
Пример #4
0
    def play_scenario(self, idsc=0, interactive=True):
        interp_u = np.zeros((len(self.times), len(self.lats), len(self.lons)))
        interp_v = np.zeros((len(self.times), len(self.lats), len(self.lons)))
        mag = np.zeros((len(self.times), len(self.lats), len(self.lons)))

        for t, time in enumerate(self.times):
            for ii, lat in enumerate(self.lats):
                for j, lon in enumerate(self.lons):
                    query_pt = [time, lat, lon]
                    interp_u[t][ii][j] = self.uWindAvg(query_pt)
                    interp_v[t][ii][j] = self.vWindAvg(query_pt)
                    mag[t][ii][j] = (interp_u[t][ii][j]**2 +
                                     interp_v[t][ii][j]**2)**0.5

        # %% PLOT
        font = {'family': 'normal', 'weight': 'bold', 'size': 22}
        proj = 'mill'
        res = 'i'
        Dline = 5
        density = 1
        matplotlib.rc('font', **font)
        fig = plt.figure(figsize=(8, 5))

        m = Basemap(projection=proj, lat_ts=10, llcrnrlon=self.lons.min(), \
                    urcrnrlon=self.lons.max(), llcrnrlat=self.lats.min(), urcrnrlat=self.lats.max(), \
                    resolution=res)

        x, y = m(*np.meshgrid(self.lons, self.lats))
        contour = m.pcolormesh(x, y, mag[0], shading="flat", cmap=plt.cm.jet)
        cbar = m.colorbar(location='right')
        quiv = m.quiver(x, y, interp_u[0], interp_v[0], color='black')
        cbar.ax.set_ylabel('Wind magnitude m/s')

        m.drawcoastlines()
        m.fillcontinents()
        m.drawmapboundary()
        m.drawparallels(self.lats[0::Dline], labels=[1, 0, 0, 0])
        m.drawmeridians(self.lons[0::Dline], labels=[0, 0, 0, 1])
        tit = plt.title('Scenario ' + str(idsc) + ' at time : ' +
                        str(self.times[0]) + ' days')

        ### using this class is as easy as using FuncAnimation:

        def update(i):
            contour.set_array(mag[i][:-1, :-1].ravel())
            quiv.set_UVC(interp_u[i], interp_v[i])
            tit.set_text('Scenario ' + str(idsc) + ' at time : ' +
                         str(self.times[i]) + ' days')
            cbar.set_clim(vmin=mag[i].min(), vmax=mag[i].max())
            cbar.draw_all()

        if interactive:
            ani = Player(fig, update, maxi=len(interp_v) - 1)
        else:
            ani = animation.FuncAnimation(fig,
                                          update,
                                          frames=len(interp_v),
                                          interval=600)
        plt.show()
        return ani
Пример #5
0
def change_player_name(update, context):
    player = Player(update.message.from_user.id)
    new_name = ' '.join(context.args)
    player.change_player_name(new_name, update.message.from_user.id)
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text="Имя игрока изменено на: {}".format(
                                 new_name.title()))
Пример #6
0
def defense(update, context):
    player = Player(update.message.from_user.id)
    mobname = context.user_data['mobname']
    text = update.message.text
    context.user_data['player_translate'] = text
    player_translate = context.user_data['player_translate']

    if str(player_translate).lower() in context.user_data['translations_list']:
        update.message.reply_text('Защита успешна🛡', reply_markup=end_turn)
    else:
        update.message.reply_text('Неверно!\n'
                                  'Монстр наносит вам {} урона!'.format(
                                      mobname.dmg),
                                  reply_markup=end_turn)
        player.curr_hp -= mobname.dmg
        db.update_cur_hp(player.curr_hp, update.message.from_user.id)
        if player.curr_hp <= 0:
            context.bot.send_message(chat_id=update.effective_chat.id,
                                     text='Битва проиграна😔\n'
                                     'Нужно лечение!',
                                     reply_markup=ReplyKeyboardRemove())

            return ConversationHandler.END

    return TURN
Пример #7
0
def heal(update, context):
    player = Player(update.message.from_user.id)
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text="Исцеляю...".format(player.curr_hp))
    player.heal(update.message.from_user.id)
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text="Готово!\n"
                             "Текущие ХП: {}".format(player.curr_hp))
Пример #8
0
def main():
    glob.players = [
        Player(i) for i in range(cfg.getint('map', 'playerNumber'))
    ]
    glob.the_map = MapDefinition.Map()
    glob.actionEventManager = MapDefinition.ActionEventManager()

    mainGamelogic = mainGamelogicThread("gameLogic")
    mainGamelogic.start()
Пример #9
0
def process_csv(year: int) -> List[Player]:
    print(f"Processing {year}")
    dicts = read_csv(year)
    return [
        Player(
            id=int(d["IDplayer"]),
            team=Team(id=int(d["Team ID"]),
                      name=d["Название"],
                      city=d["Город"],
                      year=year),
            first_name=d["Имя"],
            middle_name=d["Отчество"],
            last_name=d["Фамилия"],
        ) for d in dicts
    ]
    def setUp(self, agent_opts=None):
        spec = {
            "players": [Player(42, "SPEAKER", Pos(5, 63, 5), Look(270, 0), Item(0, 0))],
            "mobs": [],
            "item_stacks": [],
            "ground_generator": flat_ground_generator,
            "agent": {"pos": (0, 63, 0)},
            "coord_shift": (-16, 54, -16),
        }
        world_opts = Opt()
        world_opts.sl = 32
        self.world = World(world_opts, spec)
        self.agent = FakeAgent(self.world, opts=agent_opts)

        self.set_looking_at((0, 63, 0))
        self.speaker = self.agent.get_other_players()[0].name
        self.agent.perceive()
Пример #11
0
    def setup(self):
        arcade.set_background_color(arcade.color.AMAZON)
        self.all_sprites = arcade.SpriteList()
        self.coin_list = arcade.SpriteList()
        self.wall_list = arcade.SpriteList()
        self.cubicle_list = arcade.SpriteList()
        self.worker_list = arcade.SpriteList()
        self.button_list = []

        self.score = STARTSCORE
        self.coin_type = arcade.Sprite
        self.level_scores = []
        self.level_number = 0
        self.question_up = False
        self.question = None
        self.graphing = False
        self.touching = None

        player_images = [[
            arcade.load_texture('bin/boehm_walk/walk_boehm0.png', scale=0.75)
        ],
                         [
                             arcade.load_texture(
                                 'bin/boehm_walk/walk_boehm0.png',
                                 scale=0.75,
                                 mirrored=True)
                         ],
                         [
                             arcade.load_texture(
                                 'bin/boehm_walk/walk_boehm{}.png'.format(i),
                                 scale=0.75) for i in range(6)
                         ],
                         [
                             arcade.load_texture(
                                 'bin/boehm_walk/walk_boehm{}.png'.format(i),
                                 scale=0.75,
                                 mirrored=True) for i in range(6)
                         ]]

        self.player = Player(player_images)

        # start a level
        self.level()
        self.physics_engine = arcade.PhysicsEngineSimple(
            self.player, self.cubicle_list)
 def __init__(self):
     # Replica of test environment
     spec = {
         "players":
         [Player(42, "SPEAKER", Pos(5, 63, 5), Look(270, 0), Item(0, 0))],
         "mobs": [],
         "ground_generator":
         flat_ground_generator,
         "agent": {
             "pos": (0, 63, 0)
         },
         "coord_shift": (-16, 54, -16),
     }
     world_opts = Opt()
     world_opts.sl = 32
     self.world = World(world_opts, spec)
     self.agent = FakeAgent(self.world, opts=None)
     self.speaker = "cat"
Пример #13
0
def ask_answer(update, context):
    player = Player(update.message.from_user.id)
    mobname = context.user_data['mobname']
    text = update.message.text

    if text == str(context.user_data['answer']):
        update.message.reply_text('<b>{}</b> получает <b>{}</b> урона'.format(
            mobname.rus_name.title(), player.dmg),
                                  parse_mode='html')
        mobname.hp -= player.dmg
        if mobname.hp <= 0:
            context.bot.send_message(
                chat_id=update.effective_chat.id,
                text='Противник повержен!\nОтличная битва!\n'
                '<b>Получено {} опыта.</b>'.format(mobname.exp),
                parse_mode='html',
                reply_markup=ReplyKeyboardRemove())
            new_exp = player.curr_exp + mobname.exp
            player.update_curr_exp(new_exp, update.message.from_user.id)

            if player.curr_exp > player.next_lvl_exp:
                db.lvl_up(update.message.from_user.id)
                db.set_exp_to_next_lvl()
                context.bot.send_message(
                    chat_id=update.effective_chat.id,
                    text='Поздравляем, вы получили уровень!',
                    reply_markup=ReplyKeyboardRemove())
                return ConversationHandler.END
            else:
                return ConversationHandler.END
    else:
        update.message.reply_text('<b>Промах!</b>', parse_mode='html')

    context.bot.send_message(chat_id=update.effective_chat.id,
                             text='Защищайся!')
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text='Переверди на русский: <b>{}</b>'.format(
                                 context.user_data['translation'][0]),
                             parse_mode="html")
    word = context.user_data['translation'][0]
    translations_list = translation(word)
    context.user_data['translations_list'] = translations_list

    return DEFENSE
Пример #14
0
def turn(update, context):
    player = Player(update.message.from_user.id)
    mobname = context.user_data['mobname']
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text='🔸ХП Игрока: {}\n🔸ХП Монстра: {}'.format(
                                 player.curr_hp, mobname.hp))
    # Определеяется сложность моба:
    difficulty = mobname.difficulty
    ops = calc.rand_calc(difficulty)
    for k, v in ops.items():
        operation = k
        answer = v
        context.user_data['answer'] = answer
        context.user_data['wrong_answers'] = [
            random.randint(int(answer),
                           int(answer) + 15) for i in range(3)
        ]

        update.message.reply_text('<b>{}</b>'.format(operation),
                                  reply_markup=keyboard_generator(context),
                                  parse_mode='html')
        context.user_data['translation'] = db.word_for_tr()

    return ASK_ANSWER
Пример #15
0
 def getPlayer(self):
     return Player(Vector(.5, .5), Vector(0, 0), 150000, 150, 0.02)
Пример #16
0
def player():
    return Player(123, 1513454219, 999999, 999999, 1)
Пример #17
0
    def plot_hist_best_policy(self, idscenario=-1, interactive=False):
        """
        Plot the best policy as in :py:meth:`plot_best_policy`, with the histogram of the best action at each node\
         (`Animation <https://matplotlib.org/api/animation_api.html>`_)

        :param int idscenario: id of the corresponding worker tree to be plot. If -1 (default), the global tree is plotted.
        :param bool interactive: if True the plot is not an animation but can be browsed step by step
        :return: `Animation <https://matplotlib.org/api/animation_api.html>`_
        """
        # check if the best_policy has been computed
        if len(self.best_policy) == 0:
            self.get_best_policy()

        # Get the right policy:
        nodes_policy = self.best_nodes_policy[idscenario]
        policy = self.best_policy[idscenario]

        # Plot
        fig, ax1 = self.plot_best_policy(idscenario=idscenario,
                                         number_subplots=2)

        ax2 = fig.add_subplot(1, 2, 2)
        ax2.set_title("Histogram of returns for given action")
        barcollection = ax2.bar(Hist.MEANS, [0 for _ in Hist.MEANS],
                                Hist.THRESH[1] - Hist.THRESH[0])
        pt, = ax1.plot(0, 0, color="green", marker='o', markersize='7')
        x0, y0 = 0, 0
        x_list = [x0]
        y_list = [y0]
        for node in nodes_policy[1:]:
            x = x0 + 1 * sin(node.arm * pi / 180)
            y = y0 + 1 * cos(node.arm * pi / 180)
            x_list.append(x)
            y_list.append(y)
            x0, y0 = x, y

        def animate(i):
            n = nodes_policy[i]
            if i == len(nodes_policy) - 1:
                # last nodes: same reward for all actions
                a = 0
            else:
                a = A_DICT[policy[i]]
            if idscenario is -1:
                hist = sum(n.rewards[ii, a].h * self.probability[ii]
                           for ii in range(len(n.rewards[:, a])))
            else:
                hist = n.rewards[idscenario, a].h
            for j, b in enumerate(barcollection):
                b.set_height(hist[j])
            ax2.set_ylim([0, np.max(hist) + 1])
            pt.set_data(x_list[i], y_list[i])

            return barcollection, pt

        if interactive:
            anim = Player(fig, animate, maxi=len(nodes_policy) - 1)
        else:
            anim = animation.FuncAnimation(fig,
                                           animate,
                                           frames=len(nodes_policy),
                                           interval=1000,
                                           blit=False)
        plt.show()

        return anim
Пример #18
0
hall = Hall()
connection_list = []
connection_list.append(listen_sock)


while True:
    conn, addr = s.accept()
    print("Connected to ", addr)

    # Player.fileno()
    read_players, write_players, error_sockets = select.select(
        connection_list, [], [])
    for player in read_players:
        if player is listen_sock:  # new connection, player is a socket
            new_socket, add = player.accept()
            new_player = Player(new_socket)
            connection_list.append(new_player)
            hall.welcome_new(new_player)

        else:  # new message
            msg = player.socket.recv(4096)
            if msg:
                msg = msg.decode().lower()
                hall.handle_msg(player, msg)
            else:
                player.socket.close()
                connection_list.remove(player)

    for sock in error_sockets:  # close error sockets
        sock.close()
        connection_list.remove(sock)
Пример #19
0
    log_formatter = logging.Formatter(
        "%(asctime)s [%(filename)s:%(lineno)s - %(funcName)s() %(levelname)s]: %(message)s"
    )
    logging.getLogger().setLevel(logging.DEBUG)
    logging.getLogger().handlers.clear()
    # set up stdout logging
    sh = logging.StreamHandler()
    sh.setLevel(logging.DEBUG)
    sh.setFormatter(log_formatter)
    logging.getLogger().addHandler(sh)

    opts = Opt()
    opts.sl = 32
    spec = {
        "players":
        [Player(42, "SPEAKER", Pos(0, 68, 0), Look(270, 80), Item(0, 0))],
        "mobs":
        [SimpleMob(make_mob_opts("cow")),
         SimpleMob(make_mob_opts("chicken"))],
        "agent": {
            "pos": (1, 68, 1)
        },
        "coord_shift": (-opts.sl // 2, 63 - opts.sl // 2, -opts.sl // 2),
    }
    world = World(opts, spec)
    agent = FakeAgent(world, opts=None)
    speaker_name = agent.get_other_players()[0].name
    move_speaker_pos = {
        "action_type": "MOVE",
        "location": {
            "location_type": "SPEAKER_POS"
Пример #20
0
 def to_play(self) -> Player:
     return Player()
Пример #21
0
def player_info(update, context):
    player = Player(update.message.from_user.id)
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text=player.player_info(),
                             parse_mode='html')
Пример #22
0
 def get_player(self):
     return Player(1, "fake_agent", Pos(*self.pos), Look(0, 0), Item(0, 0))
Пример #23
0
 def resolve(self, game):
     game.players.append(Player(game, len(game.players), self.value))
     return PlayerJoinedMessage(game.players[-1],
                                name=game.players[-1].name)
pygame.mixer.pre_init(44100, -16, 2)
pygame.mixer.music.load("Burzum-Den_onde_ysten.wav")
pygame.mixer.music.play()
dp = pygame.mixer.Sound("batflyby.wav")
bark = pygame.mixer.Sound("dogbark.wav")

#direction will store the players directions
direction = "stop"
mons_dir = "stop"

#get the center of the screen and set the player there
screen_center = screen.get_rect().center
player_imgs = [
    "dogefront.png", "dogeback.png", "dogeright.png", "dogeleft.png"
]
player = Player(player_imgs[0], screen_center)
player.setImage(player_imgs[0])
life = 3

#mob initialization
mobs = Player("bat.png", screen_center)
spawn = False
hurt_time = 0
hurt = False

#get other relevant images
lives = pygame.image.load("Dog Treat 1.png").convert_alpha()

#battery life
outline = pygame.image.load("Empty Battery Meter 128 px.png").convert_alpha()
fill = pygame.image.load("Battery Meter Fill.png").convert_alpha()
Пример #25
0
 def get_player(self):
     return Player(1, "fake_agent", Pos(*self.pos), self.get_look(), Item(*self._held_item))
Пример #26
0
 def create_player_enemy(self):
     self.player = Player(self.center_x*3/4, self.center_y//3, resources.player_image_sprite, 5)
     self.enemy = Enemy(self.center_x*3/4, 7*self.center_y//4, resources.enemy_image_sprite, 50)
     return (self.player, self.enemy)
Пример #27
0
 def get_other_players(self):
     return [Player(42, "SPEAKER", Pos(5, 63, 5), Look(270, 0), Item(0, 0))]
    def setUp(self, agent_opts=None):
        spec = {
            "players":
            [Player(42, "SPEAKER", Pos(5, 63, 5), Look(270, 0), Item(0, 0))],
            "mobs": [],
            "ground_generator":
            flat_ground_generator,
            "agent": {
                "pos": (0, 63, 0)
            },
            "coord_shift": (-16, 54, -16),
        }
        world_opts = Opt()
        world_opts.sl = 32
        self.world = World(world_opts, spec)
        self.agent = FakeAgent(self.world, opts=agent_opts)

        # More helpful error message to encourage test writers to use self.set_looking_at()
        self.agent.get_player_line_of_sight = Mock(
            side_effect=NotImplementedError(
                "Cannot call into C++ function in this unit test. " +
                "Call self.set_looking_at() to set the return value"))

        self.speaker = self.agent.get_other_players()[0].name
        self.agent.perceive()

        # Combinable actions to be used in test cases
        self.possible_actions = {
            "destroy_speaker_look": {
                "action_type": "DESTROY",
                "reference_object": {
                    "location": {
                        "location_type": "SPEAKER_LOOK"
                    }
                },
            },
            "copy_speaker_look_to_agent_pos": {
                "action_type": "BUILD",
                "reference_object": {
                    "location": {
                        "location_type": "SPEAKER_LOOK"
                    }
                },
                "location": {
                    "location_type": "AGENT_POS"
                },
            },
            "build_small_sphere": {
                "action_type": "BUILD",
                "schematic": {
                    "has_name": "sphere",
                    "has_size": "small"
                },
            },
            "build_1x1x1_cube": {
                "action_type": "BUILD",
                "schematic": {
                    "has_name": "cube",
                    "has_size": "1 x 1 x 1"
                },
            },
            "move_speaker_pos": {
                "action_type": "MOVE",
                "location": {
                    "location_type": "SPEAKER_POS"
                },
            },
            "build_diamond": {
                "action_type": "BUILD",
                "schematic": {
                    "has_name": "diamond"
                }
            },
            "build_gold_cube": {
                "action_type": "BUILD",
                "schematic": {
                    "has_block_type": "gold",
                    "has_name": "cube"
                },
            },
            "fill_all_holes_speaker_look": {
                "action_type": "FILL",
                "location": {
                    "location_type": "SPEAKER_LOOK"
                },
                "repeat": {
                    "repeat_key": "ALL"
                },
            },
            "go_to_tree": {
                "action_type": "MOVE",
                "location": {
                    "location_type": "REFERENCE_OBJECT",
                    "reference_object": {
                        "has_name": "tree"
                    },
                },
            },
            "build_square_height_1": {
                "action_type": "BUILD",
                "schematic": {
                    "has_name": "square",
                    "has_height": "1"
                },
            },
            "stop": {
                "action_type": "STOP"
            },
            "fill_speaker_look": {
                "action_type": "FILL",
                "location": {
                    "location_type": "SPEAKER_LOOK"
                },
            },
            "fill_speaker_look_gold": {
                "action_type": "FILL",
                "has_block_type": "gold",
                "location": {
                    "location_type": "SPEAKER_LOOK"
                },
            },
        }