Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # coding=utf-8
- import pygame
- from pygame.locals import QUIT, MOUSEMOTION, MOUSEBUTTONDOWN, KEYDOWN, K_RETURN
- BOARD_SIZE = (150, 100)
- CELL_SIZE = 8
- DISPLAY_SIZE = (BOARD_SIZE[0] * CELL_SIZE, BOARD_SIZE[1] * CELL_SIZE)
- class Board(object):
- def __init__(self, width=DISPLAY_SIZE[0], height=DISPLAY_SIZE[1]):
- self.surface = pygame.display.set_mode((width, height), 0, 32)
- def draw(self, *args):
- for drawable in args:
- drawable.draw_on(self.surface)
- pygame.display.update()
- class Population(object):
- def __init__(self, cols=BOARD_SIZE[0], rows=BOARD_SIZE[1]):
- self.generation = [[False for row in range(rows)] for col in range(cols)]
- self.cols = cols
- self.rows = rows
- def draw_on(self, surface):
- for col in range(len(self.generation)):
- for row in range(len(self.generation[col])):
- if self.generation[col][row]:
- pygame.draw.rect(surface, (255,255,255), (col*CELL_SIZE, row*CELL_SIZE, CELL_SIZE, CELL_SIZE), 0)
- def check_cells(self, x, y): #zlicza żywe komórki naokoło
- count = 0
- for nx in (-1, 0, 1):
- if (x + nx) >= self.cols or (x + nx) < 0: continue
- for ny in (-1, 0, 1):
- if (y + ny) >= self.rows or (y + ny) < 0 or (nx == ny == 0): continue
- if self.generation[x+nx][y+ny] == True: count +=1
- return count
- def handle_mouse(self):
- buttons = pygame.mouse.get_pressed()
- if any(buttons):
- pos = pygame.mouse.get_pos()
- x, y = int(pos[0]/CELL_SIZE), int(pos[1]/CELL_SIZE)
- #zamiana wartości komorki
- self.generation[x][y] = not self.generation[x][y]
- def next_gen(self):
- self.temp = [[False for y in range(self.rows)] for x in range(self.cols)]
- for x in range(self.cols):
- for y in range(self.rows):
- if self.check_cells(x, y) == 2:
- self.temp[x][y] = self.generation[x][y]
- elif self.check_cells(x, y) == 3:
- self.temp[x][y] = True
- else:
- self.temp[x][y] = False
- self.generation = self.temp
- class Game(object):
- def __init__(self):
- pygame.init()
- self.board = Board()
- self.population = Population()
- self.clock = pygame.time.Clock()
- self.started = False
- def run(self):
- while not self.handle_events():
- self.board.draw(self.population)
- if self.started:
- self.population.next_gen()
- self.clock.tick(15)
- def handle_events(self):
- for event in pygame.event.get():
- if event.type == QUIT:
- pygame.quit()
- return True
- if event.type == MOUSEMOTION or event.type == MOUSEBUTTONDOWN:
- self.population.handle_mouse()
- if event.type == KEYDOWN and event.key == K_RETURN:
- self.started = not self.started
- if __name__ == "__main__":
- game = Game()
- game.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement