0

Смысл сымитировать жизнь в пруду. Проблема в методе класса reproduction(self). выдает "list index out of range", как мне ее нормально исправить?

import pygame
from pygame import *
import random

stone_count = 50;
seawed_count = 50;
width,height = 100, 50;
directions = [
    [-1,0],
    [1,0],
    [0,1],
    [0,-1],
    [-1,1],
    [-1,-1],
    [1,-1],
    [1,1],
    [0,0],
    ]

def derictionRandomazer(arr):
    random.shuffle(arr)
    # print(arr);
    return arr

# def is_suitable(arr):
#     print(arr);


pygame.init()

screen = pygame.display.set_mode( (width * 10, height * 10) )
pygame.display.set_caption("Life in Pond"); 
class Place:
    color = (52,152,219)
    def __init__(self, x,y):
        self.x = x
        self.y = y 

    def aseta(self):
        square = pygame.Rect(self.x*10, self.y*10, 10, 10)
        pygame.draw.rect(screen, self.color, square)

class Stone(Place):
    color = (0,0,0)

class Seaweed(Place):
    lifePeriod = 20;
    color = (2,124,2)
    reproductivePeriod = 5;
    def __init__(self,x,y):
        super().__init__(x,y)
        self.age = 0;

    def aging(self):
        self.age += 1;
        if self.age == self.lifePeriod:
            self.dying();
        elif self.age % self.reproductivePeriod == 0:
            self.reproduction();
    
    def reproduction(self):
        for direction in derictionRandomazer(directions):
            new_x = self.x + direction[0];
            new_y = self.y + direction[1];
            if type(pond[new_x][new_y]) == Place:
                pond[new_x][new_y] = Seaweed(new_x,new_y)
                pond[new_x][new_y].aseta();

    def dying(self):
        pond[self.x][self.y] = Place(self.x, self.y)
        pond[self.x][self.y].aseta();

pond = [[ 0 for x in range(width)] for y in range(width)]

# заполнили массив обьектами Place
for y in range(height):
    for x in range(width):
        pond[x][y] = Place(x,y);
        pond[x][y].aseta();

pygame.display.flip();

num = 0

# Добавляем Stone
while num <= stone_count:
    x = random.randint(1,width-2)
    y = random.randint(1,height-2)
    if type(pond[x][y]) == Place:
        pond[x][y] = Stone(x,y)
        pond[x][y].aseta();
        num += 1


pygame.display.flip();

seawedNum = 0

# Добавляем Seaweeds
while seawedNum <= seawed_count:
    x = random.randint(1,width-2)
    y = random.randint(1,height-2)
    if type(pond[x][y]) == Place:
        pond[x][y] = Seaweed(x,y)
        pond[x][y].aseta();
        seawedNum += 1

pygame.display.flip();
s = 0
while True:

    for y in range(height):
        for x in range(width):
            if type(pond[x][y]) == Seaweed:
                s+=1
                # print(s)
                pond[x][y].aging();
    pygame.display.flip();
4
  • 1
    Ну так надо же проверять, что новые координаты new_x и new_y не вылезли за границы массива. В принципе, можно особо не заморачиваться, и обернуть в try/catch, чтобы не мучиться с лишними проверками. Только подумать, что вы хотите при обработке исключения и сколько раз вы хотите, чтобы цикл отработал (при исключении цикл как бы пропустится, хорошо ли это?)
    – CrazyElf
    8 апр 2021 в 14:58
  • @CrazyElf добавил просто проверочку if new_x > 99: if new_y > 99:. Только все вымирают, но это уже другая история xD 8 апр 2021 в 15:17
  • 1
    На выход в другую сторону (меньше 0) тоже надо проверять по идее )
    – CrazyElf
    8 апр 2021 в 15:27
  • 1
    @CrazyElf Кароче надо посидеть, колония мертвецов все равно получаеться. Напиши решение твое, поставлю в ответ. 8 апр 2021 в 15:52

1 ответ 1

2
def reproduction(self):
    for direction in derictionRandomazer(directions):
        new_x = self.x + direction[0];
        new_y = self.y + direction[1];
        if type(pond[new_x][new_y]) == Place: # <- ЗДЕСЬ ВОЗМОЖЕН ВЫЛЕТ
            pond[new_x][new_y] = Seaweed(new_x,new_y)
            pond[new_x][new_y].aseta();

Вылетает тут видимо при обращении к pond[new_x][new_y] из-за выхода за границы 2-мерного списка pond. Нужно проверять, что new_x и new_y не вышли за отведённые границы, например, так:

if 0 <= new_x < width and 0 <= new_y < height:
    if type(pond[new_x][new_y]) == Place:

Хотя при создании pond у вас используется только width, а height не используется, это похоже ошибка:

pond = [[ 0 for x in range(width)] for y in range(width)]

Должно быть, наверное, так:

pond = [[ 0 for x in range(width)] for y in range(height)]

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.