TypeError: 'int' object is not callable хотя то на что жалуется питон не int а list

Рейтинг: 0Ответов: 1Опубликовано: 02.06.2023
import random

class GameWorld:
    def __init__(self, width, height, frequency, player_pos):
        self.width = width
        self.height = height
        self.frequency = frequency
        self.player_pos = player_pos
        self.world = self.generate_world()

    def generate_world(self):
        world = []
        for i in range(self.height):
            row = []
            for j in range(self.width):
                cell_type = 'земля' if random.random() > self.frequency else ('еда' if (i, j) == self.player_pos else 'камень')
                row.append(cell_type)
            world.append(row)
        return world

class Player:
    def __init__(self):
        self.health = random.randint(5, 10)
        self.strength = random.randint(2, 5)
        self.range = random.randint(1, 3)
        self.position = (0, 0)
        self.strategy = self.generate_strategy()

    def generate_strategy(self):
        directions = ['вниз', 'вверх', 'вправо', 'влево']
        strategy = {}
        for direction in directions:
            strategy[direction] = {}
            for cell_type in ['земля', 'еда', 'камень']:
                strategy[direction][cell_type] = {random.choice(directions): None}
        return strategy

    def play(self, world):
        best_strategy = self.strategy.copy()
        best_steps = float('inf')
        steps = 0
        while True:
            steps += 1
            current_strategy = self.mutate_strategy(best_strategy)
            current_steps = self.simulate_world(current_strategy, world)
            if current_steps < best_steps:
                best_strategy = current_strategy
                best_steps = current_steps
            else:
                return best_strategy, best_steps

    def mutate_strategy(self, strategy):
        new_strategy = strategy.copy()
        for direction, actions in strategy.items():
            for cell_type, next_directions in actions.items():
                new_strategy[direction][cell_type] = {random.choice(list(strategy.keys())): None}
        return new_strategy

    def simulate_world(self, strategy, world):
        steps = 0
        pos = self.position
        while world[pos[0]][pos[1]] != 'еда':
            visible_cells = self.get_visible_cells(pos, self.range, world)
            next_direction = strategy[self.get_direction(visible_cells)][world[pos[0]][pos[1]]]
            if next_direction:
                pos = self.get_next_position(pos, next_direction)
            else:
                pos = self.get_random_position(visible_cells)
            if world[pos[0]][pos[1]] == 'еда':
                break
            if world[pos[0]][pos[1]] == 'камень':
                self.health -= 1
                if self.health == 0:
                    break
            steps += 1
        return steps

    def get_direction(self, visible_cells):
        for direction in ['вниз', 'вверх', 'вправо', 'влево']:
            if visible_cells[direction]:
                return direction
        return None

    def get_visible_cells(self, pos, range, world):
        visible_cells = {'вниз': [], 'вверх': [], 'вправо': [], 'влево': []}
        for i in range(pos[0], min(pos[0] + range + 1, len(world))):
            visible_cells['вниз'].append((i, pos[1]))
        for i in range(pos[0], max(pos[0] - range - 1, -1), -1):
            visible_cells['вверх'].append((i, pos[1]))
        for j in range(pos[1], min(pos[1] + range + 1, len(world[0]))):
            visible_cells['вправо'].append((pos[0], j))

        for j in range(pos[1], max(pos[1] - range - 1, -1), -1):
            visible_cells['влево'].append((pos[0], j))
        return visible_cells

    def get_next_position(self, pos, direction):
        if direction == 'вниз':
            return (pos[0] + 1, pos[1])
        elif direction == 'вверх':
            return (pos[0] - 1, pos[1])
        elif direction == 'вправо':
            return (pos[0], pos[1] + 1)
        elif direction == 'влево':
            return (pos[0], pos[1] - 1)

    def get_random_position(self, visible_cells):
        pos_list = []
        for direction, cells in visible_cells.items():
            pos_list.extend(cells)
        return random.choice(pos_list)

width = 3
height = 3
frequency = 0.3
player_pos = (1, 2)

game = GameWorld(width, height, frequency, player_pos)
player = Player()
strategy, steps = player.play(game.world)

print("Лучшая стратегия:")
for direction, actions in strategy.items():
    print(f"Если смотреть {direction}:")
    for cell_type, next_directions in actions.items():
        print(f"Если на клетке {cell_type}, следующее действие - {next_directions}")
print(f"Количество ходов для достижения еды: {steps}")

да, большой

ошибка в выше приведённом коде такая:

Traceback (most recent call last):
  File "C:\Users\user\Desktop\аывф\main.py", line 120, in <module>
    strategy, steps = player.play(game.world)
                      ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\Desktop\аывф\main.py", line 45, in play
    current_steps = self.simulate_world(current_strategy, world)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\Desktop\аывф\main.py", line 63, in simulate_world
    visible_cells = self.get_visible_cells(pos, self.range, world)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\Desktop\аывф\main.py", line 86, in get_visible_cells
    for i in range(pos[0], min(pos[0] + range + 1, len(world))):
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'int' object is not callable

вроде как world это список, может быть ошибка в len(world)? хотя воде бы в for i in range ведь я пытался это исправить print(pos[0], min(pos[0] + range + 1, len(world))) выводит 0 2 и при моей попытке ввести эти значения в for i in range ошибка таже :/

Ответы

▲ 7
def get_visible_cells(self, pos, range, world):
                                 ^^^^^

Проблема в названии этой переменной. Вы её назвали range и она перекрыла оригинальный range. Чтобы исправить это просто переименуйте переменную