【Pygame】格子を描画する

格子を描画するために_draw_gridメソッドを作成する。

import pygame
import sys

class LifeGame:
  def __init__(self):
    self.cells = [[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
    self.BLACK = (0, 0, 0)
    self.WHITE = (255,255,255)
    self.row = len(self.cells[0])
    self.col = len(self.cells)
    self.cell_size = 30
    self.screen_size = (self.row*self.cell_size,self.col*self.cell_size)
    pygame.init()
    self.screen = pygame.display.set_mode(self.screen_size)
    pygame.display.set_caption('Game of Life')

  def run_game(self):
    while True:
      self._check_events()
      self._update_screen()

  def update_cells(self):
    tmp = [[0]*self.row for _ in range(self.col)]
    for y in range(self.col):
      for x in range(self.row):
        tmp[y][x] = self._check_rules(x,y,sum(self._flatten(self._get_around(x,y))))
    self.cells = tmp.copy()

  def print_cells(self):
    for x in self.cells:
      print(*x)

  def _get_around(self,_x,_y):
    return [[self.cells[y][x] for x in range(max(_x-1,0),min(_x+2,self.row)) if x != _x or y != _y] for y in range(max(_y-1,0),min(_y+2,self.col))]

  def _flatten(self,_arr):
    return sum(_arr,[])

  def _check_rules(self,_x,_y,_num):
    if self.cells[_y][_x] == 0:
      if _num == 3:
        return 1
      else:
        return 0
    else:
      if _num <= 1 or _num >= 4:
        return 0
      else:
        return 1

  def _check_events(self):
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        sys.exit()

  def _update_screen(self):
    self.screen.fill(self.BLACK)
    self._draw_grid()
    pygame.display.update()

  def _draw_grid(self):
    for i in range(1,self.col):
      pygame.draw.line(self.screen,self.WHITE,(0,self.cell_size*i),(self.row*self.cell_size,self.cell_size*i))
    for i in range(1,self.row):
      pygame.draw.line(self.screen,self.WHITE,(self.cell_size*i,0),(self.cell_size*i,self.col*self.cell_size))

lg = LifeGame()
lg.run_game()

今回は、以下のように出力される。

タイトルとURLをコピーしました