Advertisement
Guest User

Untitled

a guest
Nov 21st, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.84 KB | None | 0 0
  1. import pygame
  2. from pygame.locals import *
  3. import random
  4. import copy
  5.  
  6.  
  7. class GameOfLife:
  8.  
  9.     def __init__(self, width=640, height=480, cell_size=10, speed=10) -> None:
  10.         self.width = width
  11.         self.height = height
  12.         self.cell_size = cell_size
  13.  
  14.         # Устанавливаем размер окна
  15.         self.screen_size = width, height
  16.         # Создание нового окна
  17.         self.screen = pygame.display.set_mode(self.screen_size)
  18.  
  19.         # Вычисляем количество ячеек по вертикали и горизонтали
  20.         self.cell_width = self.width // self.cell_size
  21.         self.cell_height = self.height // self.cell_size
  22.  
  23.         # Скорость протекания игры
  24.         self.speed = speed
  25.  
  26.     def draw_grid(self) -> None:
  27.         """ Отрисовать сетку """
  28.         for x in range(0, self.width, self.cell_size):
  29.             pygame.draw.line(self.screen, pygame.Color('black'),
  30.                              (x, 0), (x, self.height))
  31.         for y in range(0, self.height, self.cell_size):
  32.             pygame.draw.line(self.screen, pygame.Color('black'),
  33.                              (0, y), (self.width, y))
  34.  
  35.     def draw_cell_list(self, cell_list: "CellList") -> None:
  36.         x = 0
  37.         y = 0
  38.         for cell in cell_list:
  39.             if cell.is_alive():
  40.                 pygame.draw.rect(self.screen, pygame.Color('green'),
  41.                                  [x + 1, y + 1, self.cell_size - 1, self.cell_size - 1])
  42.             else:
  43.                 pygame.draw.rect(self.screen, pygame.Color('white'),
  44.                                  [x + 1, y + 1, self.cell_size - 1, self.cell_size - 1])
  45.             x += self.cell_size
  46.             if x >= self.width:
  47.                 y += self.cell_size
  48.                 x = 0
  49.  
  50.     def run(self) -> None:
  51.         """ Запустить игру """
  52.         pygame.init()
  53.         clock = pygame.time.Clock()
  54.         pygame.display.set_caption('Game of Life')
  55.         self.screen.fill(pygame.Color('white'))
  56.  
  57.         cell_list = CellList(self.cell_height, self.cell_width, randomize=True)
  58.         running = True
  59.         while running:
  60.             for event in pygame.event.get():
  61.                 if event.type == QUIT:
  62.                     running = False
  63.             self.draw_grid()
  64.             # Отрисовка списка клеток
  65.             # Выполнение одного шага игры (обновление состояния ячеек)
  66.             self.draw_cell_list(cell_list)
  67.             cell_list.update()
  68.             pygame.display.flip()
  69.             clock.tick(self.speed)
  70.         pygame.quit()
  71.  
  72.  
  73. class Cell:
  74.  
  75.     def __init__(self, row: int, col: int, state=False) -> None:
  76.         self.state = state
  77.         self.row = row
  78.         self.col = col
  79.  
  80.     def is_alive(self) -> bool:
  81.         return self.state
  82.  
  83.  
  84. class CellList:
  85.  
  86.     def __init__(self, nrows: int, ncols: int, randomize=False) -> None:
  87.         self.nrows = nrows
  88.         self.ncols = ncols
  89.         self.grid = []
  90.         for st in range(nrows):
  91.             line = []
  92.             for elem in range(ncols):
  93.                 if randomize:
  94.                     line.append(Cell(st, elem, random.randint(0, 1)))
  95.                 else:
  96.                     line.append(Cell(st, elem, False))
  97.             self.grid.append(line)
  98.  
  99.     def get_neighbours(self, cell: Cell) -> list:
  100.         neighbours = []
  101.         col, row = cell.col, cell.row
  102.         for st in range(row - 1, row + 2):
  103.             for elem in range(col - 1, col + 2):
  104.                 if st in range(0, self.nrows) and elem in range(0, self.ncols) and (elem != col or st != row):
  105.                     neighbours.append(self.grid[st][elem])
  106.         return neighbours
  107.  
  108.     def update(self):
  109.         new_clist = copy.deepcopy(self.grid)
  110.         for cell in self:
  111.             neigh = sum(i.is_alive() for i in self.get_neighbours(cell))
  112.             if neigh != 2 and neigh != 3:
  113.                 new_clist[cell.row][cell.col].state = False
  114.             elif neigh == 3:
  115.                 new_clist[cell.row][cell.col].state = True
  116.         self.grid = new_clist
  117.         return self
  118.  
  119.     def __iter__(self):
  120.         self.st, self.elem = 0, 0
  121.         return self
  122.  
  123.     def __next__(self) -> Cell:
  124.         if self.st < self.nrows:
  125.             cell = self.grid[self.st][self.elem]
  126.             self.elem += 1
  127.             if self.elem == self.ncols:
  128.                 self.st += 1
  129.                 self.elem = 0
  130.             return cell
  131.         else:
  132.             raise StopIteration
  133.  
  134.     def __str__(self) -> str:
  135.         str = ''
  136.         str1 = ''
  137.         for st in range(self.nrows, 0):
  138.             for col in range(self.ncols, 0):
  139.                 if self.grid[st][col].state:
  140.                     str += '1'
  141.                 else:
  142.                     str += '0'
  143.             str1 += str[::-1]
  144.             str1 += '\n'
  145.         return str1
  146.  
  147.     @classmethod
  148.     def from_file(cls, filename: str) -> "CellList":
  149.         with open(filename, 'r') as file:
  150.             grid = []
  151.             row = 0
  152.             col = 0
  153.             ncol = 0
  154.             for st in file:
  155.                 line = []
  156.                 for c in st:
  157.                     if c == '0':
  158.                         line.append(Cell(row, col, False))
  159.                     if c == '1':
  160.                         line.append(Cell(row, col, True))
  161.                     col += 1
  162.                 ncol = col
  163.                 col = 0
  164.                 grid.append(line)
  165.             for line in grid:
  166.                 for cell in line:
  167.                     cell.row = row
  168.                 row += 1
  169.  
  170.             cell_list = CellList(row, ncol, False)
  171.             cell_list.grid = grid
  172.             return cell_list
  173.  
  174.  
  175. if __name__ == '__main__':
  176.     game = GameOfLife(320, 240, 20)
  177.     game.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement