Смысл сымитировать жизнь в пруду. Проблема в методе класса 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();
new_x
иnew_y
не вылезли за границы массива. В принципе, можно особо не заморачиваться, и обернуть вtry/catch
, чтобы не мучиться с лишними проверками. Только подумать, что вы хотите при обработке исключения и сколько раз вы хотите, чтобы цикл отработал (при исключении цикл как бы пропустится, хорошо ли это?)if new_x > 99: if new_y > 99:.
Только все вымирают, но это уже другая история xD