Prompt Title: Python окно клеточный алгоритм

Created 1 year ago
Votes 0
Views 244 times
0

Prompt Detail:

Извините за предыдущие неполадки. Давайте попробуем другой подход. Вместо того чтобы добавлять новые паттерны по щелчку мыши во время эмуляции, давайте добавим возможность создавать новые паттерны на холсте, а затем запустим эмуляцию, нажав клавишу "Enter". Вот исправленный код:

python
import tkinter as tk import random WIDTH = 800 HEIGHT = 800 CELL_SIZE = 10 GRID_WIDTH = WIDTH // CELL_SIZE GRID_HEIGHT = HEIGHT // CELL_SIZE def create_empty_grid(): return [[0 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)] def count_neighbors(grid, x, y): count = 0 for i in range(-1, 2): for j in range(-1, 2): if i == 0 and j == 0: continue if (x + i < 0) or (y + j < 0) or (x + i >= GRID_WIDTH) or (y + j >= GRID_HEIGHT): continue if grid[y + j][x + i] == 1: count += 1 return count def next_generation(grid): new_grid = [[0 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)] for y in range(GRID_HEIGHT): for x in range(GRID_WIDTH): neighbors = count_neighbors(grid, x, y) if grid[y][x] == 1 and (neighbors == 2 or neighbors == 3): new_grid[y][x] = 1 elif grid[y][x] == 0 and neighbors == 3: new_grid[y][x] = 1 return new_grid def draw_grid(canvas, grid): canvas.delete('all') for y in range(GRID_HEIGHT): for x in range(GRID_WIDTH): if grid[y][x] == 1: canvas.create_rectangle(x * CELL_SIZE, y * CELL_SIZE, (x + 1) * CELL_SIZE, (y + 1) * CELL_SIZE, fill='black') def main_loop(canvas, grid): grid = next_generation(grid) draw_grid(canvas, grid) canvas.after(100, main_loop, canvas, grid) def on_left_click(event, canvas, grid): x = event.x // CELL_SIZE y = event.y // CELL_SIZE grid[y][x] = 1 - grid[y][x] draw_grid(canvas, grid) def on_key_press(event, canvas, grid): if event.keysym == 'Return': main_loop(canvas, grid) def main(): grid = create_empty_grid() root = tk.Tk() root.title("Conway's Game of Life") canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, background='white') canvas.pack() canvas.bind("<Button-1>", lambda event: on_left_click(event, canvas, grid)) canvas.bind("<Key>", lambda event: on_key_press(event, canvas, grid)) canvas.focus_set() root.mainloop() if __name__ == '__main__': main()

Теперь вы можете добавлять паттерны на холст, щелкая левой кнопкой мыши. Запустите э

avatar
Xochipilli
Shared 1 prompt
Created 1 year ago

Leave a Comment

Related Tag Prompts

0
0
Sắp xếp mảng số.
1 year ago 2023-03-16 03:31:52 code
0
1
Bootstrap HTML/PHP Project Help.
1 year ago 2023-03-20 15:15:09 prem
0
0
Why should I sleep
1 year ago 2023-04-18 07:51:13 Donny