Verteiltesystheme/Code/UI/PlayingField.py

74 lines
2.2 KiB
Python

import pygame as pygame
from Code.Communication.Direction import Direction
from Code.Communication.Neighbours import Neighbours
from Code.Config import GeneralConfig, Colors
from Code.GameLogic.Rules import Rules
from Code.UI.Field import Field
class GameState:
def __init__(self, neighbours: Neighbours):
self.neighbours = neighbours
self.run = True
self.pause_for_input = False
self.field = Field()
self.update_field_events = []
def event_handler(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.run = False
if event.type == pygame.MOUSEBUTTONUP:
self.update_field_events.append(event)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
self.pause_for_input = not self.pause_for_input
def update_field_with_input(self, event):
for line in self.field.squares:
for square in line:
if square.rect.collidepoint(event.pos):
square.update(not square.active)
def evolve(self):
rules = Rules()
self.field.update_squares(rules.evolve_field(self.field))
def redraw_field(self, window):
window.fill(Colors.BLACK)
self.field.draw_squares(window)
def update_borders(self):
self.field.fill_right_ghost_edge(self.neighbours.get_edge(Direction.RIGHT))
self.field.fill_left_ghost_edge(self.neighbours.get_edge(Direction.LEFT))
def run_game(game_state: GameState):
pygame.init()
pygame.display.set_caption(GeneralConfig.window_caption)
window = pygame.display.set_mode((GeneralConfig.width, GeneralConfig.height))
clock = pygame.time.Clock()
time_elapsed_since_last_action = 0
while game_state.run:
game_state.event_handler()
for event in game_state.update_field_events:
game_state.update_field_with_input(event)
game_state.update_field_events.remove(event)
clock.tick(GeneralConfig.fps)
time_elapsed_since_last_action += clock.get_time()
if game_state.pause_for_input:
if time_elapsed_since_last_action > 100:
# start = ti.time()
game_state.update_borders()
game_state.evolve()
# end = ti.time()
# print(end - start)
time_elapsed_since_last_action = 0 # reset it to 0 so you can count again
game_state.redraw_field(window)
pygame.display.update()