Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <body>
- <h2>GameOfLife</h2>
- <p id="demo"></p>
- <script>
- class GameOfLife {
- constructor(w, h) {
- this.w = w;
- this.h = h;
- this.board = Array.from({ length: h }, () => Array(w).fill(0).map(() => Math.random() > 0.8 ? 1 : 0));
- }
- setCell(x, y, v) { this.board[y][x] = v; }
- getCell(x, y) { return x < 0 || x >= this.w || y < 0 || y >= this.h ? 0 : this.board[y][x]; }
- countNeighbors(x, y) {
- let count = 0;
- for (let j = -1; j <= 1; j++) for (let i = -1; i <= 1; i++) count += j || i ? this.getCell(x + i, y + j) : 0;
- return count;
- }
- step() {
- this.board = this.board.map((row, y) => row.map((cell, x) => {
- const n = this.countNeighbors(x, y);
- return cell ? (n === 2 || n === 3 ? 1 : 0) : (n === 3 ? 1 : 0);
- }));
- }
- draw(canvas) {
- const ctx = canvas.getContext('2d');
- const cellSize = Math.min(canvas.width / this.w, canvas.height / this.h);
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- for (let y = 0; y < this.h; y++) {
- for (let x = 0; x < this.w; x++) {
- if (this.getCell(x, y)) {
- ctx.fillRect(x * cellSize, y * cellSize, cellSize, cellSize);
- }
- }
- }
- }
- }
- // Пример использования
- const gol = new GameOfLife(50, 50);
- // Создаем и настраиваем canvas
- const canvas = document.createElement('canvas');
- canvas.width = 600;
- canvas.height = 600;
- document.body.appendChild(canvas);
- // Отображаем клетки на canvas
- function update() {
- gol.draw(canvas);
- gol.step();
- setTimeout(update, 200);
- }
- update();
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement