Apr-19-2019, 12:59 AM
Here a quick floodit example using NumPy and SciPy.
import pygame import numpy from scipy.ndimage import label as sci_label # Simple Scene Interface class Scene: def draw(self, surface, game): pass def event(self, event, game): pass def update(self, game): pass class Game: def __init__(self, caption, width, height): # Basic pygame setup pygame.display.set_caption(caption) self.rect = pygame.Rect(0, 0, width, height) self.surface = pygame.display.set_mode(self.rect.size) self.clock = pygame.time.Clock() self.running = False self.fps = 30 self.delta = 0 # Scene Interface self.scene = Scene() Game.info = self def mainloop(self): self.running = True while self.running: for event in pygame.event.get(): self.scene.event(event, self) self.keys = pygame.key.get_pressed() self.scene.update(self) self.scene.draw(self.surface, self) pygame.display.flip() self.delta = self.clock.tick(self.fps) class FloodIt(Scene): def __init__(self): self.colors = tuple(map(pygame.Color, ['dodgerblue', 'gold', 'firebrick1', 'darkslateblue', 'forestgreen', 'darkorange', 'mediumorchid'] )) self.surface = pygame.Surface((420, 420)) self.new_game() def new_game(self): self.grid = numpy.random.randint(1, 8, size=(14, 14)).astype(numpy.uint8) self.update_grid() def draw(self, surface, game): surface.blit(self.surface, (190, 100)) def event(self, event, game): if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: x, y = event.pos if 190 < x < 610: if 100 < y < 520: self.selected_block((x - 190) // 30, (y - 100) // 30) elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self.new_game() elif event.type == pygame.QUIT: game.running = False def selected_block(self, x, y): if self.grid[0, 0] != self.grid[x, y]: value = self.grid[x, y] v = self.grid[0, 0] vl, vc = sci_label(self.grid == v) # Assume first group will always be right w = numpy.where(vl == 1) for x ,y in zip(*w): self.grid[x, y] = value self.update_grid() def update_grid(self): for x, row in enumerate(self.grid): for y, col in enumerate(row): self.surface.fill(self.colors[col - 1], (x * 30, y * 30, 29, 29)) def main(): pygame.init() game = Game("FloodIt", 800, 600) game.scene = FloodIt() game.mainloop() pygame.quit() main()
99 percent of computer problems exists between chair and keyboard.