WMICraft/logic/grid.py

55 lines
2.0 KiB
Python

import random
import pygame
from common.constants import ROWS, COLUMNS, GRID_CELL_PADDING, GRID_CELL_WIDTH, GRID_CELL_HEIGHT, BORDER_WIDTH, \
BORDER_RADIUS
from .field import Field
class Grid:
def __init__(self, textures):
self.textures = textures
self.grid = []
self.free_fields = []
self.busy_fields = []
for row in range(ROWS):
self.grid.append(pygame.sprite.Group())
for column in range(COLUMNS):
box_rect = [(GRID_CELL_PADDING + GRID_CELL_WIDTH) * column + GRID_CELL_PADDING + 7,
(GRID_CELL_PADDING + GRID_CELL_HEIGHT) * row + GRID_CELL_PADDING + 7,
GRID_CELL_WIDTH,
GRID_CELL_HEIGHT]
texture_path, converted_texture = self.get_random_texture()
field = Field(
texture_path,
converted_texture,
pygame.transform.scale(converted_texture,
(GRID_CELL_WIDTH,
GRID_CELL_HEIGHT)),
pygame.Rect(box_rect),
row=row,
column=column
)
if field.busy:
self.busy_fields.append(field)
else:
self.free_fields.append(field)
self.grid[row].add(field)
def update(self, screen):
self.draw(screen)
def get_random_texture(self):
texture_index = random.randint(0, len(self.textures) - 1)
return self.textures[texture_index]
def draw(self, screen):
bg_width = (GRID_CELL_PADDING + GRID_CELL_WIDTH) * COLUMNS + BORDER_WIDTH
bg_height = (GRID_CELL_PADDING + GRID_CELL_HEIGHT) * ROWS + BORDER_WIDTH
pygame.draw.rect(screen, (255, 255, 255), pygame.Rect(5, 5, bg_width, bg_height), 0, BORDER_RADIUS)
for fields_row in self.grid:
fields_row.draw(screen)